blob: 8b159d0b71abf3bfb55862e3d7b29c5652aa845a [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;
37import android.app.ActivityThread;
38import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070039import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020040import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070042import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.app.IApplicationThread;
44import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070045import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070046import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.app.IServiceConnection;
48import android.app.IThumbnailReceiver;
49import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070050import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070051import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070053import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080054import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020055import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080056import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080057import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070058import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070060import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.ContentResolver;
62import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020063import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.content.Intent;
65import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070066import android.content.IIntentReceiver;
67import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070068import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.content.pm.ActivityInfo;
70import android.content.pm.ApplicationInfo;
71import android.content.pm.ConfigurationInfo;
72import android.content.pm.IPackageDataObserver;
73import android.content.pm.IPackageManager;
74import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080075import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070077import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.content.pm.ProviderInfo;
79import android.content.pm.ResolveInfo;
80import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070081import android.content.pm.UserInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070082import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040083import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.content.res.Configuration;
85import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070086import android.net.Proxy;
87import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.net.Uri;
89import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080090import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080091import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070092import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080093import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080095import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.FileUtils;
97import android.os.Handler;
98import android.os.IBinder;
99import android.os.IPermissionController;
100import android.os.Looper;
101import android.os.Message;
102import android.os.Parcel;
103import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700105import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.RemoteException;
107import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700108import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.os.SystemClock;
110import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700111import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700113import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700115import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800116import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800117import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.util.PrintWriterPrinter;
119import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700120import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700121import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.view.Gravity;
123import android.view.LayoutInflater;
124import android.view.View;
125import android.view.WindowManager;
126import android.view.WindowManagerPolicy;
127
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700128import java.io.BufferedInputStream;
129import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700130import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700131import java.io.DataInputStream;
132import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133import java.io.File;
134import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700135import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700137import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200138import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800139import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700141import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import java.lang.IllegalStateException;
143import 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;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700154import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700155import java.util.concurrent.atomic.AtomicBoolean;
156import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700158public final class ActivityManagerService extends ActivityManagerNative
159 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700160 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700162 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400164 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final boolean DEBUG_SWITCH = localLOGV || false;
166 static final boolean DEBUG_TASKS = localLOGV || false;
167 static final boolean DEBUG_PAUSE = localLOGV || false;
168 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
169 static final boolean DEBUG_TRANSITION = localLOGV || false;
170 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800171 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700172 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700174 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_VISBILITY = localLOGV || false;
176 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700177 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800178 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700180 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700181 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700182 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700183 static final boolean DEBUG_POWER = localLOGV || false;
184 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700185 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 static final boolean VALIDATE_TOKENS = false;
187 static final boolean SHOW_ACTIVITY_START_TIME = true;
188
189 // Control over CPU and battery monitoring.
190 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
191 static final boolean MONITOR_CPU_USAGE = true;
192 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
193 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
194 static final boolean MONITOR_THREAD_CPU_USAGE = false;
195
Dianne Hackborn1655be42009-05-08 14:29:01 -0700196 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700197 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700198
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800199 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700201 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 // Maximum number of recent tasks that we can remember.
204 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700205
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700206 // Amount of time after a call to stopAppSwitches() during which we will
207 // prevent further untrusted switches from happening.
208 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
210 // How long we wait for a launched process to attach to the activity manager
211 // before we decide it's never going to come up for real.
212 static final int PROC_START_TIMEOUT = 10*1000;
213
Jeff Brown3f9dd282011-07-08 20:02:19 -0700214 // How long we wait for a launched process to attach to the activity manager
215 // before we decide it's never going to come up for real, when the process was
216 // started with a wrapper for instrumentation (such as Valgrind) because it
217 // could take much longer than usual.
218 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 // How long to wait after going idle before forcing apps to GC.
221 static final int GC_TIMEOUT = 5*1000;
222
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700223 // The minimum amount of time between successive GC requests for a process.
224 static final int GC_MIN_INTERVAL = 60*1000;
225
Dianne Hackborn287952c2010-09-22 22:34:31 -0700226 // The rate at which we check for apps using excessive power -- 15 mins.
227 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
228
229 // The minimum sample duration we will allow before deciding we have
230 // enough data on wake locks to start killing things.
231 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
232
233 // The minimum sample duration we will allow before deciding we have
234 // enough data on CPU usage to start killing things.
235 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800238 static final int BROADCAST_FG_TIMEOUT = 10*1000;
239 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
241 // How long we wait for a service to finish executing.
242 static final int SERVICE_TIMEOUT = 20*1000;
243
244 // How long a service needs to be running until restarting its process
245 // is no longer considered to be a relaunch of the service.
246 static final int SERVICE_RESTART_DURATION = 5*1000;
247
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700248 // How long a service needs to be running until it will start back at
249 // SERVICE_RESTART_DURATION after being killed.
250 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
251
252 // Multiplying factor to increase restart duration time by, for each time
253 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
254 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
255
256 // The minimum amount of time between restarting services that we allow.
257 // That is, when multiple services are restarting, we won't allow each
258 // to restart less than this amount of time from the last one.
259 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 // Maximum amount of time for there to be no activity on a service before
262 // we consider it non-essential and allow its process to go on the
263 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700264 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265
266 // How long we wait until we timeout on key dispatching.
267 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 // How long we wait until we timeout on key dispatching during instrumentation.
270 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
271
Dan Egnor42471dd2010-01-07 17:25:22 -0800272 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273
274 static final String[] EMPTY_STRING_ARRAY = new String[0];
275
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700276 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700277
278 private final boolean mHeadless;
279
Joe Onorato54a4a412011-11-02 20:50:08 -0700280 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
281 // default actuion automatically. Important for devices without direct input
282 // devices.
283 private boolean mShowDialogs = true;
284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700286 * Description of a request to start a new activity, which has been held
287 * due to app switches being disabled.
288 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700289 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700290 ActivityRecord r;
291 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700292 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700293 }
294
295 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
296 = new ArrayList<PendingActivityLaunch>();
297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800299 BroadcastQueue mFgBroadcastQueue;
300 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800301 // Convenient for easy iteration over the queues. Foreground is first
302 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800303 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800304
305 BroadcastQueue broadcastQueueForIntent(Intent intent) {
306 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
307 if (DEBUG_BACKGROUND_BROADCAST) {
308 Slog.i(TAG, "Broadcast intent " + intent + " on "
309 + (isFg ? "foreground" : "background")
310 + " queue");
311 }
312 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
313 }
314
315 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
316 for (BroadcastQueue queue : mBroadcastQueues) {
317 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
318 if (r != null) {
319 return r;
320 }
321 }
322 return null;
323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324
325 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 * Activity we have told the window manager to have key focus.
327 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700328 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700329 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 * List of intents that were used to start the most recent tasks.
331 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700332 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333
334 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700335 * Process management.
336 */
337 final ProcessList mProcessList = new ProcessList();
338
339 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 * All of the applications we currently have running organized by name.
341 * The keys are strings of the application package name (as
342 * returned by the package manager), and the keys are ApplicationRecord
343 * objects.
344 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700345 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346
347 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800348 * The currently running isolated processes.
349 */
350 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
351
352 /**
353 * Counter for assigning isolated process uids, to avoid frequently reusing the
354 * same ones.
355 */
356 int mNextIsolatedProcessUid = 0;
357
358 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700359 * The currently running heavy-weight process, if any.
360 */
361 ProcessRecord mHeavyWeightProcess = null;
362
363 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 * The last time that various processes have crashed.
365 */
366 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
367
368 /**
369 * Set of applications that we consider to be bad, and will reject
370 * incoming broadcasts from (which the user has no control over).
371 * Processes are added to this set when they have crashed twice within
372 * a minimum amount of time; they are removed from it when they are
373 * later restarted (hopefully due to some user action). The value is the
374 * time it was added to the list.
375 */
376 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
377
378 /**
379 * All of the processes we currently have running organized by pid.
380 * The keys are the pid running the application.
381 *
382 * <p>NOTE: This object is protected by its own lock, NOT the global
383 * activity manager lock!
384 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700385 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386
387 /**
388 * All of the processes that have been forced to be foreground. The key
389 * is the pid of the caller who requested it (we hold a death
390 * link on it).
391 */
392 abstract class ForegroundToken implements IBinder.DeathRecipient {
393 int pid;
394 IBinder token;
395 }
396 final SparseArray<ForegroundToken> mForegroundProcesses
397 = new SparseArray<ForegroundToken>();
398
399 /**
400 * List of records for processes that someone had tried to start before the
401 * system was ready. We don't start them at that point, but ensure they
402 * are started by the time booting is complete.
403 */
404 final ArrayList<ProcessRecord> mProcessesOnHold
405 = new ArrayList<ProcessRecord>();
406
407 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 * List of persistent applications that are in the process
409 * of being started.
410 */
411 final ArrayList<ProcessRecord> mPersistentStartingProcesses
412 = new ArrayList<ProcessRecord>();
413
414 /**
415 * Processes that are being forcibly torn down.
416 */
417 final ArrayList<ProcessRecord> mRemovedProcesses
418 = new ArrayList<ProcessRecord>();
419
420 /**
421 * List of running applications, sorted by recent usage.
422 * The first entry in the list is the least recently used.
423 * It contains ApplicationRecord objects. This list does NOT include
424 * any persistent application records (since we never want to exit them).
425 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800426 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 = new ArrayList<ProcessRecord>();
428
429 /**
430 * List of processes that should gc as soon as things are idle.
431 */
432 final ArrayList<ProcessRecord> mProcessesToGc
433 = new ArrayList<ProcessRecord>();
434
435 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800436 * This is the process holding what we currently consider to be
437 * the "home" activity.
438 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700439 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800440
441 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700442 * This is the process holding the activity the user last visited that
443 * is in a different process from the one they are currently in.
444 */
445 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800446
447 /**
448 * The time at which the previous process was last visible.
449 */
450 long mPreviousProcessVisibleTime;
451
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700452 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400453 * Packages that the user has asked to have run in screen size
454 * compatibility mode instead of filling the screen.
455 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700456 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400457
458 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 * Set of PendingResultRecord objects that are currently active.
460 */
461 final HashSet mPendingResultRecords = new HashSet();
462
463 /**
464 * Set of IntentSenderRecord objects that are currently active.
465 */
466 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
467 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
468
469 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800470 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700471 * already logged DropBox entries for. Guarded by itself. If
472 * something (rogue user app) forces this over
473 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
474 */
475 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
476 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
477
478 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700479 * Strict Mode background batched logging state.
480 *
481 * The string buffer is guarded by itself, and its lock is also
482 * used to determine if another batched write is already
483 * in-flight.
484 */
485 private final StringBuilder mStrictModeBuffer = new StringBuilder();
486
487 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 * Keeps track of all IIntentReceivers that have been registered for
489 * broadcasts. Hash keys are the receiver IBinder, hash value is
490 * a ReceiverList.
491 */
492 final HashMap mRegisteredReceivers = new HashMap();
493
494 /**
495 * Resolver for broadcast intents to registered receivers.
496 * Holds BroadcastFilter (subclass of IntentFilter).
497 */
498 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
499 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
500 @Override
501 protected boolean allowFilterResult(
502 BroadcastFilter filter, List<BroadcastFilter> dest) {
503 IBinder target = filter.receiverList.receiver.asBinder();
504 for (int i=dest.size()-1; i>=0; i--) {
505 if (dest.get(i).receiverList.receiver.asBinder() == target) {
506 return false;
507 }
508 }
509 return true;
510 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700511
512 @Override
513 protected String packageForFilter(BroadcastFilter filter) {
514 return filter.packageName;
515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 };
517
518 /**
519 * State of all active sticky broadcasts. Keys are the action of the
520 * sticky Intent, values are an ArrayList of all broadcasted intents with
521 * that action (which should usually be one).
522 */
523 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
524 new HashMap<String, ArrayList<Intent>>();
525
Amith Yamasani742a6712011-05-04 14:49:28 -0700526 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527
528 /**
529 * All currently bound service connections. Keys are the IBinder of
530 * the client's IServiceConnection.
531 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700532 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
533 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534
535 /**
536 * List of services that we have been asked to start,
537 * but haven't yet been able to. It is used to hold start requests
538 * while waiting for their corresponding application thread to get
539 * going.
540 */
541 final ArrayList<ServiceRecord> mPendingServices
542 = new ArrayList<ServiceRecord>();
543
544 /**
545 * List of services that are scheduled to restart following a crash.
546 */
547 final ArrayList<ServiceRecord> mRestartingServices
548 = new ArrayList<ServiceRecord>();
549
550 /**
551 * List of services that are in the process of being stopped.
552 */
553 final ArrayList<ServiceRecord> mStoppingServices
554 = new ArrayList<ServiceRecord>();
555
556 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700557 * Backup/restore process management
558 */
559 String mBackupAppName = null;
560 BackupRecord mBackupTarget = null;
561
562 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 * List of PendingThumbnailsRecord objects of clients who are still
564 * waiting to receive all of the thumbnails for a task.
565 */
566 final ArrayList mPendingThumbnails = new ArrayList();
567
568 /**
569 * List of HistoryRecord objects that have been finished and must
570 * still report back to a pending thumbnail receiver.
571 */
572 final ArrayList mCancelledThumbnails = new ArrayList();
573
Amith Yamasani742a6712011-05-04 14:49:28 -0700574 final ProviderMap mProviderMap = new ProviderMap();
575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 /**
577 * List of content providers who have clients waiting for them. The
578 * application is currently being launched and the provider will be
579 * removed from this list once it is published.
580 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700581 final ArrayList<ContentProviderRecord> mLaunchingProviders
582 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583
584 /**
585 * Global set of specific Uri permissions that have been granted.
586 */
587 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
588 = new SparseArray<HashMap<Uri, UriPermission>>();
589
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800590 CoreSettingsObserver mCoreSettingsObserver;
591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 /**
593 * Thread-local storage used to carry caller permissions over through
594 * indirect content-provider access.
595 * @see #ActivityManagerService.openContentUri()
596 */
597 private class Identity {
598 public int pid;
599 public int uid;
600
601 Identity(int _pid, int _uid) {
602 pid = _pid;
603 uid = _uid;
604 }
605 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
608
609 /**
610 * All information we have collected about the runtime performance of
611 * any user id that can impact battery performance.
612 */
613 final BatteryStatsService mBatteryStatsService;
614
615 /**
616 * information about component usage
617 */
618 final UsageStatsService mUsageStatsService;
619
620 /**
621 * Current configuration information. HistoryRecord objects are given
622 * a reference to this object to indicate which configuration they are
623 * currently running in, so this object must be kept immutable.
624 */
625 Configuration mConfiguration = new Configuration();
626
627 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800628 * Current sequencing integer of the configuration, for skipping old
629 * configurations.
630 */
631 int mConfigurationSeq = 0;
632
633 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700634 * Hardware-reported OpenGLES version.
635 */
636 final int GL_ES_VERSION;
637
638 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 * List of initialization arguments to pass to all processes when binding applications to them.
640 * For example, references to the commonly used services.
641 */
642 HashMap<String, IBinder> mAppBindArgs;
643
644 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700645 * Temporary to avoid allocations. Protected by main lock.
646 */
647 final StringBuilder mStringBuilder = new StringBuilder(256);
648
649 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 * Used to control how we initialize the service.
651 */
652 boolean mStartRunning = false;
653 ComponentName mTopComponent;
654 String mTopAction;
655 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700656 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 boolean mSystemReady = false;
658 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700659 boolean mWaitingUpdate = false;
660 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700661 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700662 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663
664 Context mContext;
665
666 int mFactoryTest;
667
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700668 boolean mCheckedForSetup;
669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700671 * The time at which we will allow normal application switches again,
672 * after a call to {@link #stopAppSwitches()}.
673 */
674 long mAppSwitchesAllowedTime;
675
676 /**
677 * This is set to true after the first switch after mAppSwitchesAllowedTime
678 * is set; any switches after that will clear the time.
679 */
680 boolean mDidAppSwitch;
681
682 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700683 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700684 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700685 long mLastPowerCheckRealtime;
686
687 /**
688 * Last time (in uptime) at which we checked for power usage.
689 */
690 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700691
692 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 * Set while we are wanting to sleep, to prevent any
694 * activities from being started/resumed.
695 */
696 boolean mSleeping = false;
697
698 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700699 * Set if we are shutting down the system, similar to sleeping.
700 */
701 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702
703 /**
704 * Task identifier that activities are currently being started
705 * in. Incremented each time a new task is created.
706 * todo: Replace this with a TokenSpace class that generates non-repeating
707 * integers that won't wrap.
708 */
709 int mCurTask = 1;
710
711 /**
712 * Current sequence id for oom_adj computation traversal.
713 */
714 int mAdjSeq = 0;
715
716 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700717 * Current sequence id for process LRU updating.
718 */
719 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720
721 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700722 * Keep track of the number of service processes we last found, to
723 * determine on the next iteration which should be B services.
724 */
725 int mNumServiceProcs = 0;
726 int mNewNumServiceProcs = 0;
727
728 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 * System monitoring: number of processes that died since the last
730 * N procs were started.
731 */
732 int[] mProcDeaths = new int[20];
733
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700734 /**
735 * This is set if we had to do a delayed dexopt of an app before launching
736 * it, to increasing the ANR timeouts in that case.
737 */
738 boolean mDidDexOpt;
739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 String mDebugApp = null;
741 boolean mWaitForDebugger = false;
742 boolean mDebugTransient = false;
743 String mOrigDebugApp = null;
744 boolean mOrigWaitForDebugger = false;
745 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700746 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700747 String mProfileApp = null;
748 ProcessRecord mProfileProc = null;
749 String mProfileFile;
750 ParcelFileDescriptor mProfileFd;
751 int mProfileType = 0;
752 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800753 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754
Jeff Sharkeya4620792011-05-20 15:29:23 -0700755 final RemoteCallbackList<IProcessObserver> mProcessObservers
756 = new RemoteCallbackList<IProcessObserver>();
757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 /**
759 * Callback of last caller to {@link #requestPss}.
760 */
761 Runnable mRequestPssCallback;
762
763 /**
764 * Remaining processes for which we are waiting results from the last
765 * call to {@link #requestPss}.
766 */
767 final ArrayList<ProcessRecord> mRequestPssList
768 = new ArrayList<ProcessRecord>();
769
770 /**
771 * Runtime statistics collection thread. This object's lock is used to
772 * protect all related state.
773 */
774 final Thread mProcessStatsThread;
775
776 /**
777 * Used to collect process stats when showing not responding dialog.
778 * Protected by mProcessStatsThread.
779 */
780 final ProcessStats mProcessStats = new ProcessStats(
781 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700782 final AtomicLong mLastCpuTime = new AtomicLong(0);
783 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 long mLastWriteTime = 0;
786
787 /**
788 * Set to true after the system has finished booting.
789 */
790 boolean mBooted = false;
791
Dianne Hackborn7d608422011-08-07 16:24:18 -0700792 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700793 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794
795 WindowManagerService mWindowManager;
796
797 static ActivityManagerService mSelf;
798 static ActivityThread mSystemThread;
799
800 private final class AppDeathRecipient implements IBinder.DeathRecipient {
801 final ProcessRecord mApp;
802 final int mPid;
803 final IApplicationThread mAppThread;
804
805 AppDeathRecipient(ProcessRecord app, int pid,
806 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800807 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 TAG, "New death recipient " + this
809 + " for thread " + thread.asBinder());
810 mApp = app;
811 mPid = pid;
812 mAppThread = thread;
813 }
814
815 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800816 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 TAG, "Death received in " + this
818 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 synchronized(ActivityManagerService.this) {
820 appDiedLocked(mApp, mPid, mAppThread);
821 }
822 }
823 }
824
825 static final int SHOW_ERROR_MSG = 1;
826 static final int SHOW_NOT_RESPONDING_MSG = 2;
827 static final int SHOW_FACTORY_ERROR_MSG = 3;
828 static final int UPDATE_CONFIGURATION_MSG = 4;
829 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
830 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 static final int SERVICE_TIMEOUT_MSG = 12;
832 static final int UPDATE_TIME_ZONE = 13;
833 static final int SHOW_UID_ERROR_MSG = 14;
834 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700836 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700837 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800838 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700839 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
840 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700841 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700842 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700843 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700844 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700845 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700846 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
847 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700848 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800850 static final int FIRST_ACTIVITY_STACK_MSG = 100;
851 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
852 static final int FIRST_COMPAT_MODE_MSG = 300;
853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700855 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700856 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857
858 final Handler mHandler = new Handler() {
859 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800860 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 //}
862
863 public void handleMessage(Message msg) {
864 switch (msg.what) {
865 case SHOW_ERROR_MSG: {
866 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 synchronized (ActivityManagerService.this) {
868 ProcessRecord proc = (ProcessRecord)data.get("app");
869 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800870 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 return;
872 }
873 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700874 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800875 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 d.show();
877 proc.crashDialog = d;
878 } else {
879 // The device is asleep, so just pretend that the user
880 // saw a crash dialog and hit "force quit".
881 res.set(0);
882 }
883 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700884
885 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 } break;
887 case SHOW_NOT_RESPONDING_MSG: {
888 synchronized (ActivityManagerService.this) {
889 HashMap data = (HashMap) msg.obj;
890 ProcessRecord proc = (ProcessRecord)data.get("app");
891 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800892 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 return;
894 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800895
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700896 Intent intent = new Intent("android.intent.action.ANR");
897 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800898 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
899 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700900 }
901 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800902 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700903 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700906 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 d.show();
908 proc.anrDialog = d;
909 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700910
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700911 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700913 case SHOW_STRICT_MODE_VIOLATION_MSG: {
914 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
915 synchronized (ActivityManagerService.this) {
916 ProcessRecord proc = (ProcessRecord) data.get("app");
917 if (proc == null) {
918 Slog.e(TAG, "App not found when showing strict mode dialog.");
919 break;
920 }
921 if (proc.crashDialog != null) {
922 Slog.e(TAG, "App already has strict mode dialog: " + proc);
923 return;
924 }
925 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700926 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700927 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
928 d.show();
929 proc.crashDialog = d;
930 } else {
931 // The device is asleep, so just pretend that the user
932 // saw a crash dialog and hit "force quit".
933 res.set(0);
934 }
935 }
936 ensureBootCompleted();
937 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 case SHOW_FACTORY_ERROR_MSG: {
939 Dialog d = new FactoryErrorDialog(
940 mContext, msg.getData().getCharSequence("msg"));
941 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700942 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 } break;
944 case UPDATE_CONFIGURATION_MSG: {
945 final ContentResolver resolver = mContext.getContentResolver();
946 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
947 } break;
948 case GC_BACKGROUND_PROCESSES_MSG: {
949 synchronized (ActivityManagerService.this) {
950 performAppGcsIfAppropriateLocked();
951 }
952 } break;
953 case WAIT_FOR_DEBUGGER_MSG: {
954 synchronized (ActivityManagerService.this) {
955 ProcessRecord app = (ProcessRecord)msg.obj;
956 if (msg.arg1 != 0) {
957 if (!app.waitedForDebugger) {
958 Dialog d = new AppWaitingForDebuggerDialog(
959 ActivityManagerService.this,
960 mContext, app);
961 app.waitDialog = d;
962 app.waitedForDebugger = true;
963 d.show();
964 }
965 } else {
966 if (app.waitDialog != null) {
967 app.waitDialog.dismiss();
968 app.waitDialog = null;
969 }
970 }
971 }
972 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700974 if (mDidDexOpt) {
975 mDidDexOpt = false;
976 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
977 nmsg.obj = msg.obj;
978 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
979 return;
980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 serviceTimeout((ProcessRecord)msg.obj);
982 } break;
983 case UPDATE_TIME_ZONE: {
984 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800985 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
986 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 if (r.thread != null) {
988 try {
989 r.thread.updateTimeZone();
990 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800991 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
993 }
994 }
995 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700996 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700997 case CLEAR_DNS_CACHE: {
998 synchronized (ActivityManagerService.this) {
999 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1000 ProcessRecord r = mLruProcesses.get(i);
1001 if (r.thread != null) {
1002 try {
1003 r.thread.clearDnsCache();
1004 } catch (RemoteException ex) {
1005 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1006 }
1007 }
1008 }
1009 }
1010 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001011 case UPDATE_HTTP_PROXY: {
1012 ProxyProperties proxy = (ProxyProperties)msg.obj;
1013 String host = "";
1014 String port = "";
1015 String exclList = "";
1016 if (proxy != null) {
1017 host = proxy.getHost();
1018 port = Integer.toString(proxy.getPort());
1019 exclList = proxy.getExclusionList();
1020 }
1021 synchronized (ActivityManagerService.this) {
1022 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1023 ProcessRecord r = mLruProcesses.get(i);
1024 if (r.thread != null) {
1025 try {
1026 r.thread.setHttpProxy(host, port, exclList);
1027 } catch (RemoteException ex) {
1028 Slog.w(TAG, "Failed to update http proxy for: " +
1029 r.info.processName);
1030 }
1031 }
1032 }
1033 }
1034 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001036 String title = "System UIDs Inconsistent";
1037 String text = "UIDs on the system are inconsistent, you need to wipe your"
1038 + " data partition or your device will be unstable.";
1039 Log.e(TAG, title + ": " + text);
1040 if (mShowDialogs) {
1041 // XXX This is a temporary dialog, no need to localize.
1042 AlertDialog d = new BaseErrorDialog(mContext);
1043 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1044 d.setCancelable(false);
1045 d.setTitle(title);
1046 d.setMessage(text);
1047 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1048 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1049 mUidAlert = d;
1050 d.show();
1051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 } break;
1053 case IM_FEELING_LUCKY_MSG: {
1054 if (mUidAlert != null) {
1055 mUidAlert.dismiss();
1056 mUidAlert = null;
1057 }
1058 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001060 if (mDidDexOpt) {
1061 mDidDexOpt = false;
1062 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1063 nmsg.obj = msg.obj;
1064 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1065 return;
1066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 ProcessRecord app = (ProcessRecord)msg.obj;
1068 synchronized (ActivityManagerService.this) {
1069 processStartTimedOutLocked(app);
1070 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001071 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001072 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1073 synchronized (ActivityManagerService.this) {
1074 doPendingActivityLaunchesLocked(true);
1075 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001076 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001077 case KILL_APPLICATION_MSG: {
1078 synchronized (ActivityManagerService.this) {
1079 int uid = msg.arg1;
1080 boolean restart = (msg.arg2 == 1);
1081 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001082 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1083 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001084 }
1085 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001086 case FINALIZE_PENDING_INTENT_MSG: {
1087 ((PendingIntentRecord)msg.obj).completeFinalize();
1088 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001089 case POST_HEAVY_NOTIFICATION_MSG: {
1090 INotificationManager inm = NotificationManager.getService();
1091 if (inm == null) {
1092 return;
1093 }
1094
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001095 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001096 ProcessRecord process = root.app;
1097 if (process == null) {
1098 return;
1099 }
1100
1101 try {
1102 Context context = mContext.createPackageContext(process.info.packageName, 0);
1103 String text = mContext.getString(R.string.heavy_weight_notification,
1104 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1105 Notification notification = new Notification();
1106 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1107 notification.when = 0;
1108 notification.flags = Notification.FLAG_ONGOING_EVENT;
1109 notification.tickerText = text;
1110 notification.defaults = 0; // please be quiet
1111 notification.sound = null;
1112 notification.vibrate = null;
1113 notification.setLatestEventInfo(context, text,
1114 mContext.getText(R.string.heavy_weight_notification_detail),
1115 PendingIntent.getActivity(mContext, 0, root.intent,
1116 PendingIntent.FLAG_CANCEL_CURRENT));
1117
1118 try {
1119 int[] outId = new int[1];
1120 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1121 notification, outId);
1122 } catch (RuntimeException e) {
1123 Slog.w(ActivityManagerService.TAG,
1124 "Error showing notification for heavy-weight app", e);
1125 } catch (RemoteException e) {
1126 }
1127 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001128 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001129 }
1130 } break;
1131 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1132 INotificationManager inm = NotificationManager.getService();
1133 if (inm == null) {
1134 return;
1135 }
1136 try {
1137 inm.cancelNotification("android",
1138 R.string.heavy_weight_notification);
1139 } catch (RuntimeException e) {
1140 Slog.w(ActivityManagerService.TAG,
1141 "Error canceling notification for service", e);
1142 } catch (RemoteException e) {
1143 }
1144 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001145 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1146 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001147 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001148 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001149 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1150 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001151 }
1152 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001153 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1154 synchronized (ActivityManagerService.this) {
1155 ActivityRecord ar = (ActivityRecord)msg.obj;
1156 if (mCompatModeDialog != null) {
1157 if (mCompatModeDialog.mAppInfo.packageName.equals(
1158 ar.info.applicationInfo.packageName)) {
1159 return;
1160 }
1161 mCompatModeDialog.dismiss();
1162 mCompatModeDialog = null;
1163 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001164 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001165 if (mCompatModePackages.getPackageAskCompatModeLocked(
1166 ar.packageName)) {
1167 int mode = mCompatModePackages.computeCompatModeLocked(
1168 ar.info.applicationInfo);
1169 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1170 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1171 mCompatModeDialog = new CompatModeDialog(
1172 ActivityManagerService.this, mContext,
1173 ar.info.applicationInfo);
1174 mCompatModeDialog.show();
1175 }
1176 }
1177 }
1178 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001179 break;
1180 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001181 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001182 final int pid = msg.arg1;
1183 final int uid = msg.arg2;
1184 final boolean foregroundActivities = (Boolean) msg.obj;
1185 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001186 break;
1187 }
1188 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001189 final int pid = msg.arg1;
1190 final int uid = msg.arg2;
1191 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001192 break;
1193 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001194 case REPORT_MEM_USAGE: {
1195 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1196 if (!isDebuggable) {
1197 return;
1198 }
1199 synchronized (ActivityManagerService.this) {
1200 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001201 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1202 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001203 // avoid spamming.
1204 return;
1205 }
1206 mLastMemUsageReportTime = now;
1207 }
1208 Thread thread = new Thread() {
1209 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001210 StringBuilder dropBuilder = new StringBuilder(1024);
1211 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001212 StringWriter oomSw = new StringWriter();
1213 PrintWriter oomPw = new PrintWriter(oomSw);
1214 StringWriter catSw = new StringWriter();
1215 PrintWriter catPw = new PrintWriter(catSw);
1216 String[] emptyArgs = new String[] { };
1217 StringBuilder tag = new StringBuilder(128);
1218 StringBuilder stack = new StringBuilder(128);
1219 tag.append("Low on memory -- ");
1220 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1221 tag, stack);
1222 dropBuilder.append(stack);
1223 dropBuilder.append('\n');
1224 dropBuilder.append('\n');
1225 String oomString = oomSw.toString();
1226 dropBuilder.append(oomString);
1227 dropBuilder.append('\n');
1228 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001229 try {
1230 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1231 "procrank", });
1232 final InputStreamReader converter = new InputStreamReader(
1233 proc.getInputStream());
1234 BufferedReader in = new BufferedReader(converter);
1235 String line;
1236 while (true) {
1237 line = in.readLine();
1238 if (line == null) {
1239 break;
1240 }
1241 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001242 logBuilder.append(line);
1243 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001244 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001245 dropBuilder.append(line);
1246 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001247 }
1248 converter.close();
1249 } catch (IOException e) {
1250 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001251 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001252 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001253 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001254 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001255 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001256 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001257 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001258 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001259 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001260 addErrorToDropBox("lowmem", null, "system_server", null,
1261 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001262 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001263 synchronized (ActivityManagerService.this) {
1264 long now = SystemClock.uptimeMillis();
1265 if (mLastMemUsageReportTime < now) {
1266 mLastMemUsageReportTime = now;
1267 }
1268 }
1269 }
1270 };
1271 thread.start();
1272 break;
1273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 }
1275 }
1276 };
1277
1278 public static void setSystemProcess() {
1279 try {
1280 ActivityManagerService m = mSelf;
1281
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001282 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001284 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001285 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 if (MONITOR_CPU_USAGE) {
1287 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 ServiceManager.addService("permission", new PermissionController(m));
1290
1291 ApplicationInfo info =
1292 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001293 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001294 mSystemThread.installSystemApplicationInfo(info);
1295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 synchronized (mSelf) {
1297 ProcessRecord app = mSelf.newProcessRecordLocked(
1298 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001299 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001301 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001302 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001303 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 synchronized (mSelf.mPidsSelfLocked) {
1305 mSelf.mPidsSelfLocked.put(app.pid, app);
1306 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001307 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 }
1309 } catch (PackageManager.NameNotFoundException e) {
1310 throw new RuntimeException(
1311 "Unable to find android system package", e);
1312 }
1313 }
1314
1315 public void setWindowManager(WindowManagerService wm) {
1316 mWindowManager = wm;
1317 }
1318
1319 public static final Context main(int factoryTest) {
1320 AThread thr = new AThread();
1321 thr.start();
1322
1323 synchronized (thr) {
1324 while (thr.mService == null) {
1325 try {
1326 thr.wait();
1327 } catch (InterruptedException e) {
1328 }
1329 }
1330 }
1331
1332 ActivityManagerService m = thr.mService;
1333 mSelf = m;
1334 ActivityThread at = ActivityThread.systemMain();
1335 mSystemThread = at;
1336 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001337 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 m.mContext = context;
1339 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001340 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341
1342 m.mBatteryStatsService.publish(context);
1343 m.mUsageStatsService.publish(context);
1344
1345 synchronized (thr) {
1346 thr.mReady = true;
1347 thr.notifyAll();
1348 }
1349
1350 m.startRunning(null, null, null, null);
1351
1352 return context;
1353 }
1354
1355 public static ActivityManagerService self() {
1356 return mSelf;
1357 }
1358
1359 static class AThread extends Thread {
1360 ActivityManagerService mService;
1361 boolean mReady = false;
1362
1363 public AThread() {
1364 super("ActivityManager");
1365 }
1366
1367 public void run() {
1368 Looper.prepare();
1369
1370 android.os.Process.setThreadPriority(
1371 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001372 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373
1374 ActivityManagerService m = new ActivityManagerService();
1375
1376 synchronized (this) {
1377 mService = m;
1378 notifyAll();
1379 }
1380
1381 synchronized (this) {
1382 while (!mReady) {
1383 try {
1384 wait();
1385 } catch (InterruptedException e) {
1386 }
1387 }
1388 }
1389
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001390 // For debug builds, log event loop stalls to dropbox for analysis.
1391 if (StrictMode.conditionallyEnableDebugLogging()) {
1392 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1393 }
1394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 Looper.loop();
1396 }
1397 }
1398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 static class MemBinder extends Binder {
1400 ActivityManagerService mActivityManagerService;
1401 MemBinder(ActivityManagerService activityManagerService) {
1402 mActivityManagerService = activityManagerService;
1403 }
1404
1405 @Override
1406 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001407 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1408 != PackageManager.PERMISSION_GRANTED) {
1409 pw.println("Permission Denial: can't dump meminfo from from pid="
1410 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1411 + " without permission " + android.Manifest.permission.DUMP);
1412 return;
1413 }
1414
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001415 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001416 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418 }
1419
Chet Haase9c1e23b2011-03-24 10:51:31 -07001420 static class GraphicsBinder extends Binder {
1421 ActivityManagerService mActivityManagerService;
1422 GraphicsBinder(ActivityManagerService activityManagerService) {
1423 mActivityManagerService = activityManagerService;
1424 }
1425
1426 @Override
1427 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001428 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1429 != PackageManager.PERMISSION_GRANTED) {
1430 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1431 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1432 + " without permission " + android.Manifest.permission.DUMP);
1433 return;
1434 }
1435
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001436 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001437 }
1438 }
1439
Jeff Brown6754ba22011-12-14 20:20:01 -08001440 static class DbBinder extends Binder {
1441 ActivityManagerService mActivityManagerService;
1442 DbBinder(ActivityManagerService activityManagerService) {
1443 mActivityManagerService = activityManagerService;
1444 }
1445
1446 @Override
1447 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1448 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1449 != PackageManager.PERMISSION_GRANTED) {
1450 pw.println("Permission Denial: can't dump dbinfo from from pid="
1451 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1452 + " without permission " + android.Manifest.permission.DUMP);
1453 return;
1454 }
1455
1456 mActivityManagerService.dumpDbInfo(fd, pw, args);
1457 }
1458 }
1459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 static class CpuBinder extends Binder {
1461 ActivityManagerService mActivityManagerService;
1462 CpuBinder(ActivityManagerService activityManagerService) {
1463 mActivityManagerService = activityManagerService;
1464 }
1465
1466 @Override
1467 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001468 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1469 != PackageManager.PERMISSION_GRANTED) {
1470 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1471 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1472 + " without permission " + android.Manifest.permission.DUMP);
1473 return;
1474 }
1475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001477 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1478 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1479 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 }
1481 }
1482 }
1483
1484 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001485 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001486
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001487 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1488 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1489 mBroadcastQueues[0] = mFgBroadcastQueue;
1490 mBroadcastQueues[1] = mBgBroadcastQueue;
1491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 File dataDir = Environment.getDataDirectory();
1493 File systemDir = new File(dataDir, "system");
1494 systemDir.mkdirs();
1495 mBatteryStatsService = new BatteryStatsService(new File(
1496 systemDir, "batterystats.bin").toString());
1497 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001498 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001499 mOnBattery = DEBUG_POWER ? true
1500 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001501 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001503 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001504 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001505 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506
Jack Palevichb90d28c2009-07-22 15:35:24 -07001507 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1508 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1509
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001510 mConfiguration.setToDefaults();
1511 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001512 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 mProcessStats.init();
1514
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001515 mCompatModePackages = new CompatModePackages(this, systemDir);
1516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 // Add ourself to the Watchdog monitors.
1518 Watchdog.getInstance().addMonitor(this);
1519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 mProcessStatsThread = new Thread("ProcessStats") {
1521 public void run() {
1522 while (true) {
1523 try {
1524 try {
1525 synchronized(this) {
1526 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001527 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001529 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 // + ", write delay=" + nextWriteDelay);
1531 if (nextWriteDelay < nextCpuDelay) {
1532 nextCpuDelay = nextWriteDelay;
1533 }
1534 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001535 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 this.wait(nextCpuDelay);
1537 }
1538 }
1539 } catch (InterruptedException e) {
1540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 updateCpuStatsNow();
1542 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001543 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
1545 }
1546 }
1547 };
1548 mProcessStatsThread.start();
1549 }
1550
1551 @Override
1552 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1553 throws RemoteException {
1554 try {
1555 return super.onTransact(code, data, reply, flags);
1556 } catch (RuntimeException e) {
1557 // The activity manager only throws security exceptions, so let's
1558 // log all others.
1559 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001560 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 }
1562 throw e;
1563 }
1564 }
1565
1566 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001567 final long now = SystemClock.uptimeMillis();
1568 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1569 return;
1570 }
1571 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1572 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 mProcessStatsThread.notify();
1574 }
1575 }
1576 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 void updateCpuStatsNow() {
1579 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001580 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 final long now = SystemClock.uptimeMillis();
1582 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001585 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1586 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 haveNewCpuStats = true;
1588 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001589 //Slog.i(TAG, mProcessStats.printCurrentState());
1590 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 // + mProcessStats.getTotalCpuPercent() + "%");
1592
Joe Onorato8a9b2202010-02-26 18:56:32 -08001593 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 if ("true".equals(SystemProperties.get("events.cpu"))) {
1595 int user = mProcessStats.getLastUserTime();
1596 int system = mProcessStats.getLastSystemTime();
1597 int iowait = mProcessStats.getLastIoWaitTime();
1598 int irq = mProcessStats.getLastIrqTime();
1599 int softIrq = mProcessStats.getLastSoftIrqTime();
1600 int idle = mProcessStats.getLastIdleTime();
1601
1602 int total = user + system + iowait + irq + softIrq + idle;
1603 if (total == 0) total = 1;
1604
Doug Zongker2bec3d42009-12-04 12:52:44 -08001605 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 ((user+system+iowait+irq+softIrq) * 100) / total,
1607 (user * 100) / total,
1608 (system * 100) / total,
1609 (iowait * 100) / total,
1610 (irq * 100) / total,
1611 (softIrq * 100) / total);
1612 }
1613 }
1614
Amith Yamasanie43530a2009-08-21 13:11:37 -07001615 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001616 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001617 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 synchronized(mPidsSelfLocked) {
1619 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001620 if (mOnBattery) {
1621 int perc = bstats.startAddingCpuLocked();
1622 int totalUTime = 0;
1623 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001624 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001626 ProcessStats.Stats st = mProcessStats.getStats(i);
1627 if (!st.working) {
1628 continue;
1629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001631 int otherUTime = (st.rel_utime*perc)/100;
1632 int otherSTime = (st.rel_stime*perc)/100;
1633 totalUTime += otherUTime;
1634 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 if (pr != null) {
1636 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001637 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1638 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001639 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001640 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001641 } else {
1642 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001643 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001644 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001645 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1646 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001647 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 }
1650 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001651 bstats.finishAddingCpuLocked(perc, totalUTime,
1652 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 }
1654 }
1655 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1658 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001659 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 }
1662 }
1663 }
1664
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001665 @Override
1666 public void batteryNeedsCpuUpdate() {
1667 updateCpuStatsNow();
1668 }
1669
1670 @Override
1671 public void batteryPowerChanged(boolean onBattery) {
1672 // When plugging in, update the CPU stats first before changing
1673 // the plug state.
1674 updateCpuStatsNow();
1675 synchronized (this) {
1676 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001677 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001678 }
1679 }
1680 }
1681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 /**
1683 * Initialize the application bind args. These are passed to each
1684 * process when the bindApplication() IPC is sent to the process. They're
1685 * lazily setup to make sure the services are running when they're asked for.
1686 */
1687 private HashMap<String, IBinder> getCommonServicesLocked() {
1688 if (mAppBindArgs == null) {
1689 mAppBindArgs = new HashMap<String, IBinder>();
1690
1691 // Setup the application init args
1692 mAppBindArgs.put("package", ServiceManager.getService("package"));
1693 mAppBindArgs.put("window", ServiceManager.getService("window"));
1694 mAppBindArgs.put(Context.ALARM_SERVICE,
1695 ServiceManager.getService(Context.ALARM_SERVICE));
1696 }
1697 return mAppBindArgs;
1698 }
1699
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001700 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 if (mFocusedActivity != r) {
1702 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001703 if (r != null) {
1704 mWindowManager.setFocusedApp(r.appToken, true);
1705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 }
1707 }
1708
Dianne Hackborn906497c2010-05-10 15:57:38 -07001709 private final void updateLruProcessInternalLocked(ProcessRecord app,
1710 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001712 int lrui = mLruProcesses.indexOf(app);
1713 if (lrui >= 0) mLruProcesses.remove(lrui);
1714
1715 int i = mLruProcesses.size()-1;
1716 int skipTop = 0;
1717
Dianne Hackborn906497c2010-05-10 15:57:38 -07001718 app.lruSeq = mLruSeq;
1719
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001720 // compute the new weight for this process.
1721 if (updateActivityTime) {
1722 app.lastActivityTime = SystemClock.uptimeMillis();
1723 }
1724 if (app.activities.size() > 0) {
1725 // If this process has activities, we more strongly want to keep
1726 // it around.
1727 app.lruWeight = app.lastActivityTime;
1728 } else if (app.pubProviders.size() > 0) {
1729 // If this process contains content providers, we want to keep
1730 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001731 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001732 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001733 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001734 } else {
1735 // If this process doesn't have activities, we less strongly
1736 // want to keep it around, and generally want to avoid getting
1737 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001738 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001739 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001740 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001741 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001742
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001743 while (i >= 0) {
1744 ProcessRecord p = mLruProcesses.get(i);
1745 // If this app shouldn't be in front of the first N background
1746 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001747 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001748 skipTop--;
1749 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001750 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001751 mLruProcesses.add(i+1, app);
1752 break;
1753 }
1754 i--;
1755 }
1756 if (i < 0) {
1757 mLruProcesses.add(0, app);
1758 }
1759
Dianne Hackborn906497c2010-05-10 15:57:38 -07001760 // If the app is currently using a content provider or service,
1761 // bump those processes as well.
1762 if (app.connections.size() > 0) {
1763 for (ConnectionRecord cr : app.connections) {
1764 if (cr.binding != null && cr.binding.service != null
1765 && cr.binding.service.app != null
1766 && cr.binding.service.app.lruSeq != mLruSeq) {
1767 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1768 updateActivityTime, i+1);
1769 }
1770 }
1771 }
1772 if (app.conProviders.size() > 0) {
1773 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001774 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1775 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001776 updateActivityTime, i+1);
1777 }
1778 }
1779 }
1780
Joe Onorato8a9b2202010-02-26 18:56:32 -08001781 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 if (oomAdj) {
1783 updateOomAdjLocked();
1784 }
1785 }
1786
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001787 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001788 boolean oomAdj, boolean updateActivityTime) {
1789 mLruSeq++;
1790 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1791 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001792
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001793 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 String processName, int uid) {
1795 if (uid == Process.SYSTEM_UID) {
1796 // The system gets to run in any process. If there are multiple
1797 // processes with the same uid, just pick the first (this
1798 // should never happen).
1799 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1800 processName);
1801 return procs != null ? procs.valueAt(0) : null;
1802 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001803 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 ProcessRecord proc = mProcessNames.get(processName, uid);
1805 return proc;
1806 }
1807
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001808 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001809 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001810 try {
1811 if (pm.performDexOpt(packageName)) {
1812 mDidDexOpt = true;
1813 }
1814 } catch (RemoteException e) {
1815 }
1816 }
1817
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001818 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 int transit = mWindowManager.getPendingAppTransition();
1820 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1821 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1822 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1823 }
1824
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001825 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001827 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1828 boolean isolated) {
1829 ProcessRecord app;
1830 if (!isolated) {
1831 app = getProcessRecordLocked(processName, info.uid);
1832 } else {
1833 // If this is an isolated process, it can't re-use an existing process.
1834 app = null;
1835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 // We don't have to do anything more if:
1837 // (1) There is an existing application record; and
1838 // (2) The caller doesn't think it is dead, OR there is no thread
1839 // object attached to it so we know it couldn't have crashed; and
1840 // (3) There is a pid assigned to it, so it is either starting or
1841 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001842 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 + " app=" + app + " knownToBeDead=" + knownToBeDead
1844 + " thread=" + (app != null ? app.thread : null)
1845 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001846 if (app != null && app.pid > 0) {
1847 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001848 // We already have the app running, or are waiting for it to
1849 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001850 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001851 // If this is a new package in the process, add the package to the list
1852 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001853 return app;
1854 } else {
1855 // An application record is attached to a previous process,
1856 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001857 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001858 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 String hostingNameStr = hostingName != null
1863 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001864
1865 if (!isolated) {
1866 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1867 // If we are in the background, then check to see if this process
1868 // is bad. If so, we will just silently fail.
1869 if (mBadProcesses.get(info.processName, info.uid) != null) {
1870 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1871 + "/" + info.processName);
1872 return null;
1873 }
1874 } else {
1875 // When the user is explicitly starting a process, then clear its
1876 // crash count so that we won't make it bad until they see at
1877 // least one crash dialog again, and make the process good again
1878 // if it had been bad.
1879 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001880 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001881 mProcessCrashTimes.remove(info.processName, info.uid);
1882 if (mBadProcesses.get(info.processName, info.uid) != null) {
1883 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1884 info.processName);
1885 mBadProcesses.remove(info.processName, info.uid);
1886 if (app != null) {
1887 app.bad = false;
1888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 }
1890 }
1891 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001894 app = newProcessRecordLocked(null, info, processName, isolated);
1895 if (app == null) {
1896 Slog.w(TAG, "Failed making new process record for "
1897 + processName + "/" + info.uid + " isolated=" + isolated);
1898 return null;
1899 }
1900 mProcessNames.put(processName, app.uid, app);
1901 if (isolated) {
1902 mIsolatedProcesses.put(app.uid, app);
1903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 } else {
1905 // If this is a new package in the process, add the package to the list
1906 app.addPackage(info.packageName);
1907 }
1908
1909 // If the system is not ready yet, then hold off on starting this
1910 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001911 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001912 && !isAllowedWhileBooting(info)
1913 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 if (!mProcessesOnHold.contains(app)) {
1915 mProcessesOnHold.add(app);
1916 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001917 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 return app;
1919 }
1920
1921 startProcessLocked(app, hostingType, hostingNameStr);
1922 return (app.pid != 0) ? app : null;
1923 }
1924
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001925 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1926 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1927 }
1928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 private final void startProcessLocked(ProcessRecord app,
1930 String hostingType, String hostingNameStr) {
1931 if (app.pid > 0 && app.pid != MY_PID) {
1932 synchronized (mPidsSelfLocked) {
1933 mPidsSelfLocked.remove(app.pid);
1934 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1935 }
1936 app.pid = 0;
1937 }
1938
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001939 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1940 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 mProcessesOnHold.remove(app);
1942
1943 updateCpuStats();
1944
1945 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1946 mProcDeaths[0] = 0;
1947
1948 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001949 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001952 if (!app.isolated) {
1953 try {
1954 gids = mContext.getPackageManager().getPackageGids(
1955 app.info.packageName);
1956 } catch (PackageManager.NameNotFoundException e) {
1957 Slog.w(TAG, "Unable to retrieve gids", e);
1958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 }
1960 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1961 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1962 && mTopComponent != null
1963 && app.processName.equals(mTopComponent.getPackageName())) {
1964 uid = 0;
1965 }
1966 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1967 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1968 uid = 0;
1969 }
1970 }
1971 int debugFlags = 0;
1972 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1973 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001974 // Also turn on CheckJNI for debuggable apps. It's quite
1975 // awkward to turn on otherwise.
1976 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001978 // Run the app in safe mode if its manifest requests so or the
1979 // system is booted in safe mode.
1980 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1981 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001982 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1985 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1986 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001987 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1988 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 if ("1".equals(SystemProperties.get("debug.assert"))) {
1991 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1992 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001993
1994 // Start the process. It will either succeed and return a result containing
1995 // the PID of the new process, or else throw a RuntimeException.
1996 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001997 app.processName, uid, uid, gids, debugFlags,
1998 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07001999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2001 synchronized (bs) {
2002 if (bs.isOnBattery()) {
2003 app.batteryStats.incStartsLocked();
2004 }
2005 }
2006
Jeff Brown3f9dd282011-07-08 20:02:19 -07002007 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 app.processName, hostingType,
2009 hostingNameStr != null ? hostingNameStr : "");
2010
2011 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002012 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 }
2014
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002015 StringBuilder buf = mStringBuilder;
2016 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 buf.append("Start proc ");
2018 buf.append(app.processName);
2019 buf.append(" for ");
2020 buf.append(hostingType);
2021 if (hostingNameStr != null) {
2022 buf.append(" ");
2023 buf.append(hostingNameStr);
2024 }
2025 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002026 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 buf.append(" uid=");
2028 buf.append(uid);
2029 buf.append(" gids={");
2030 if (gids != null) {
2031 for (int gi=0; gi<gids.length; gi++) {
2032 if (gi != 0) buf.append(", ");
2033 buf.append(gids[gi]);
2034
2035 }
2036 }
2037 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002038 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002039 app.pid = startResult.pid;
2040 app.usingWrapper = startResult.usingWrapper;
2041 app.removed = false;
2042 synchronized (mPidsSelfLocked) {
2043 this.mPidsSelfLocked.put(startResult.pid, app);
2044 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2045 msg.obj = app;
2046 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2047 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 }
2049 } catch (RuntimeException e) {
2050 // XXX do better error recovery.
2051 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002052 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
2054 }
2055
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002056 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 if (resumed) {
2058 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2059 } else {
2060 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2061 }
2062 }
2063
Amith Yamasani742a6712011-05-04 14:49:28 -07002064 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002065 if (mHeadless) {
2066 // Added because none of the other calls to ensureBootCompleted seem to fire
2067 // when running headless.
2068 ensureBootCompleted();
2069 return false;
2070 }
2071
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002072 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2073 && mTopAction == null) {
2074 // We are running in factory test mode, but unable to find
2075 // the factory test app, so just sit around displaying the
2076 // error message and don't try to start anything.
2077 return false;
2078 }
2079 Intent intent = new Intent(
2080 mTopAction,
2081 mTopData != null ? Uri.parse(mTopData) : null);
2082 intent.setComponent(mTopComponent);
2083 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2084 intent.addCategory(Intent.CATEGORY_HOME);
2085 }
2086 ActivityInfo aInfo =
2087 intent.resolveActivityInfo(mContext.getPackageManager(),
2088 STOCK_PM_FLAGS);
2089 if (aInfo != null) {
2090 intent.setComponent(new ComponentName(
2091 aInfo.applicationInfo.packageName, aInfo.name));
2092 // Don't do this if the home app is currently being
2093 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002094 aInfo = new ActivityInfo(aInfo);
2095 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002096 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2097 aInfo.applicationInfo.uid);
2098 if (app == null || app.instrumentationClass == null) {
2099 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002100 mMainStack.startActivityLocked(null, intent, null, aInfo,
2101 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002102 }
2103 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002104
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002105 return true;
2106 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002107
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002108 /**
2109 * Starts the "new version setup screen" if appropriate.
2110 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002111 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002112 // Only do this once per boot.
2113 if (mCheckedForSetup) {
2114 return;
2115 }
2116
2117 // We will show this screen if the current one is a different
2118 // version than the last one shown, and we are not running in
2119 // low-level factory test mode.
2120 final ContentResolver resolver = mContext.getContentResolver();
2121 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2122 Settings.Secure.getInt(resolver,
2123 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2124 mCheckedForSetup = true;
2125
2126 // See if we should be showing the platform update setup UI.
2127 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2128 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2129 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2130
2131 // We don't allow third party apps to replace this.
2132 ResolveInfo ri = null;
2133 for (int i=0; ris != null && i<ris.size(); i++) {
2134 if ((ris.get(i).activityInfo.applicationInfo.flags
2135 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2136 ri = ris.get(i);
2137 break;
2138 }
2139 }
2140
2141 if (ri != null) {
2142 String vers = ri.activityInfo.metaData != null
2143 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2144 : null;
2145 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2146 vers = ri.activityInfo.applicationInfo.metaData.getString(
2147 Intent.METADATA_SETUP_VERSION);
2148 }
2149 String lastVers = Settings.Secure.getString(
2150 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2151 if (vers != null && !vers.equals(lastVers)) {
2152 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2153 intent.setComponent(new ComponentName(
2154 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002155 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2156 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002157 }
2158 }
2159 }
2160 }
2161
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002162 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002163 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002164 }
2165
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002166 void enforceNotIsolatedCaller(String caller) {
2167 if (UserId.isIsolated(Binder.getCallingUid())) {
2168 throw new SecurityException("Isolated process not allowed to call " + caller);
2169 }
2170 }
2171
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002172 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002173 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002174 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002175 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2176 }
2177 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002178
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002179 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002180 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2181 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002182 synchronized (this) {
2183 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2184 }
2185 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002186
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002187 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002188 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002189 synchronized (this) {
2190 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2191 }
2192 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002193
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002194 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002195 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2196 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002197 synchronized (this) {
2198 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002199 }
2200 }
2201
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002202 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002203 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002204 synchronized (this) {
2205 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2206 }
2207 }
2208
2209 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002210 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2211 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002212 synchronized (this) {
2213 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2214 }
2215 }
2216
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002217 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002218 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002219
2220 final int identHash = System.identityHashCode(r);
2221 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223
Jeff Sharkeya4620792011-05-20 15:29:23 -07002224 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2225 int i = mProcessObservers.beginBroadcast();
2226 while (i > 0) {
2227 i--;
2228 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2229 if (observer != null) {
2230 try {
2231 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2232 } catch (RemoteException e) {
2233 }
2234 }
2235 }
2236 mProcessObservers.finishBroadcast();
2237 }
2238
2239 private void dispatchProcessDied(int pid, int uid) {
2240 int i = mProcessObservers.beginBroadcast();
2241 while (i > 0) {
2242 i--;
2243 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2244 if (observer != null) {
2245 try {
2246 observer.onProcessDied(pid, uid);
2247 } catch (RemoteException e) {
2248 }
2249 }
2250 }
2251 mProcessObservers.finishBroadcast();
2252 }
2253
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002254 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002255 final int N = mPendingActivityLaunches.size();
2256 if (N <= 0) {
2257 return;
2258 }
2259 for (int i=0; i<N; i++) {
2260 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002261 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002262 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002263 }
2264 mPendingActivityLaunches.clear();
2265 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002266
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002267 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002268 Intent intent, String resolvedType, IBinder resultTo,
2269 String resultWho, int requestCode, int startFlags,
2270 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002271 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002272 int userId = 0;
2273 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2274 // Requesting home, set the identity to the current user
2275 // HACK!
2276 userId = mCurrentUserId;
2277 } else {
2278 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2279 // the current user's userId
2280 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2281 userId = 0;
2282 } else {
2283 userId = Binder.getOrigCallingUser();
2284 }
2285 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002286 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002287 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2288 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002289 }
2290
2291 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002292 Intent intent, String resolvedType, IBinder resultTo,
2293 String resultWho, int requestCode, int startFlags, String profileFile,
2294 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002295 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002296 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002297 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002298 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002299 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2300 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002301 return res;
2302 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002303
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002304 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002305 Intent intent, String resolvedType, IBinder resultTo,
2306 String resultWho, int requestCode, int startFlags, Configuration config,
2307 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002308 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002309 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002310 resultTo, resultWho, requestCode, startFlags,
2311 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002312 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002313 }
2314
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002315 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002316 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002317 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002318 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002319 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002320 // Refuse possible leaked file descriptors
2321 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2322 throw new IllegalArgumentException("File descriptors passed in Intent");
2323 }
2324
2325 IIntentSender sender = intent.getTarget();
2326 if (!(sender instanceof PendingIntentRecord)) {
2327 throw new IllegalArgumentException("Bad PendingIntent object");
2328 }
2329
2330 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002331
2332 synchronized (this) {
2333 // If this is coming from the currently resumed activity, it is
2334 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002335 if (mMainStack.mResumedActivity != null
2336 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002337 Binder.getCallingUid()) {
2338 mAppSwitchesAllowedTime = 0;
2339 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002340 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002341 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2342 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002343 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002344 }
2345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002347 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 // Refuse possible leaked file descriptors
2349 if (intent != null && intent.hasFileDescriptors() == true) {
2350 throw new IllegalArgumentException("File descriptors passed in Intent");
2351 }
2352
2353 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002354 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2355 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 return false;
2357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 if (r.app == null || r.app.thread == null) {
2359 // The caller is not running... d'oh!
2360 return false;
2361 }
2362 intent = new Intent(intent);
2363 // The caller is not allowed to change the data.
2364 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2365 // And we are resetting to find the next component...
2366 intent.setComponent(null);
2367
2368 ActivityInfo aInfo = null;
2369 try {
2370 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002371 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002373 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2374 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375
2376 // Look for the original activity in the list...
2377 final int N = resolves != null ? resolves.size() : 0;
2378 for (int i=0; i<N; i++) {
2379 ResolveInfo rInfo = resolves.get(i);
2380 if (rInfo.activityInfo.packageName.equals(r.packageName)
2381 && rInfo.activityInfo.name.equals(r.info.name)) {
2382 // We found the current one... the next matching is
2383 // after it.
2384 i++;
2385 if (i<N) {
2386 aInfo = resolves.get(i).activityInfo;
2387 }
2388 break;
2389 }
2390 }
2391 } catch (RemoteException e) {
2392 }
2393
2394 if (aInfo == null) {
2395 // Nobody who is next!
2396 return false;
2397 }
2398
2399 intent.setComponent(new ComponentName(
2400 aInfo.applicationInfo.packageName, aInfo.name));
2401 intent.setFlags(intent.getFlags()&~(
2402 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2403 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2404 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2405 Intent.FLAG_ACTIVITY_NEW_TASK));
2406
2407 // Okay now we need to start the new activity, replacing the
2408 // currently running activity. This is a little tricky because
2409 // we want to start the new one as if the current one is finished,
2410 // but not finish the current one first so that there is no flicker.
2411 // And thus...
2412 final boolean wasFinishing = r.finishing;
2413 r.finishing = true;
2414
2415 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002416 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 final String resultWho = r.resultWho;
2418 final int requestCode = r.requestCode;
2419 r.resultTo = null;
2420 if (resultTo != null) {
2421 resultTo.removeResultsLocked(r, resultWho, requestCode);
2422 }
2423
2424 final long origId = Binder.clearCallingIdentity();
2425 // XXX we are not dealing with propagating grantedUriPermissions...
2426 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002427 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002428 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2429 resultWho, requestCode, -1, r.launchedFromUid, 0,
2430 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 Binder.restoreCallingIdentity(origId);
2432
2433 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002434 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 return false;
2436 }
2437 return true;
2438 }
2439 }
2440
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002441 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002443 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002444
2445 // This is so super not safe, that only the system (or okay root)
2446 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002447 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002448 final int callingUid = Binder.getCallingUid();
2449 if (callingUid != 0 && callingUid != Process.myUid()) {
2450 throw new SecurityException(
2451 "startActivityInPackage only available to the system");
2452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453
Amith Yamasani742a6712011-05-04 14:49:28 -07002454 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002455 resultTo, resultWho, requestCode, startFlags,
2456 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002457 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002458 }
2459
2460 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002461 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002462 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002463 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002464 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002465 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002466 }
2467
2468 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002469 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2470 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002471
2472 // This is so super not safe, that only the system (or okay root)
2473 // can do it.
2474 final int callingUid = Binder.getCallingUid();
2475 if (callingUid != 0 && callingUid != Process.myUid()) {
2476 throw new SecurityException(
2477 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002479 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002480 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002481 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 }
2483
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002484 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002486 // Quick case: check if the top-most recent task is the same.
2487 if (N > 0 && mRecentTasks.get(0) == task) {
2488 return;
2489 }
2490 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 for (int i=0; i<N; i++) {
2492 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002493 if (task.userId == tr.userId
2494 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2495 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 mRecentTasks.remove(i);
2497 i--;
2498 N--;
2499 if (task.intent == null) {
2500 // If the new recent task we are adding is not fully
2501 // specified, then replace it with the existing recent task.
2502 task = tr;
2503 }
2504 }
2505 }
2506 if (N >= MAX_RECENT_TASKS) {
2507 mRecentTasks.remove(N-1);
2508 }
2509 mRecentTasks.add(0, task);
2510 }
2511
2512 public void setRequestedOrientation(IBinder token,
2513 int requestedOrientation) {
2514 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002515 ActivityRecord r = mMainStack.isInStackLocked(token);
2516 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 return;
2518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002520 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002522 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002523 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 if (config != null) {
2525 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002526 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002527 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 }
2529 }
2530 Binder.restoreCallingIdentity(origId);
2531 }
2532 }
2533
2534 public int getRequestedOrientation(IBinder token) {
2535 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002536 ActivityRecord r = mMainStack.isInStackLocked(token);
2537 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2539 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002540 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 }
2542 }
2543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 /**
2545 * This is the internal entry point for handling Activity.finish().
2546 *
2547 * @param token The Binder token referencing the Activity we want to finish.
2548 * @param resultCode Result code, if any, from this Activity.
2549 * @param resultData Result data (Intent), if any, from this Activity.
2550 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002551 * @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 -08002552 */
2553 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2554 // Refuse possible leaked file descriptors
2555 if (resultData != null && resultData.hasFileDescriptors() == true) {
2556 throw new IllegalArgumentException("File descriptors passed in Intent");
2557 }
2558
2559 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002560 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002562 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 if (next != null) {
2564 // ask watcher if this is allowed
2565 boolean resumeOK = true;
2566 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002567 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002569 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 }
2571
2572 if (!resumeOK) {
2573 return false;
2574 }
2575 }
2576 }
2577 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002578 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 resultData, "app-request");
2580 Binder.restoreCallingIdentity(origId);
2581 return res;
2582 }
2583 }
2584
Dianne Hackborn860755f2010-06-03 18:47:52 -07002585 public final void finishHeavyWeightApp() {
2586 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2587 != PackageManager.PERMISSION_GRANTED) {
2588 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2589 + Binder.getCallingPid()
2590 + ", uid=" + Binder.getCallingUid()
2591 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2592 Slog.w(TAG, msg);
2593 throw new SecurityException(msg);
2594 }
2595
2596 synchronized(this) {
2597 if (mHeavyWeightProcess == null) {
2598 return;
2599 }
2600
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002601 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002602 mHeavyWeightProcess.activities);
2603 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002604 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002605 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002606 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002607 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002608 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002609 null, "finish-heavy");
2610 }
2611 }
2612 }
2613
2614 mHeavyWeightProcess = null;
2615 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2616 }
2617 }
2618
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002619 public void crashApplication(int uid, int initialPid, String packageName,
2620 String message) {
2621 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2622 != PackageManager.PERMISSION_GRANTED) {
2623 String msg = "Permission Denial: crashApplication() from pid="
2624 + Binder.getCallingPid()
2625 + ", uid=" + Binder.getCallingUid()
2626 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2627 Slog.w(TAG, msg);
2628 throw new SecurityException(msg);
2629 }
2630
2631 synchronized(this) {
2632 ProcessRecord proc = null;
2633
2634 // Figure out which process to kill. We don't trust that initialPid
2635 // still has any relation to current pids, so must scan through the
2636 // list.
2637 synchronized (mPidsSelfLocked) {
2638 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2639 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002640 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002641 continue;
2642 }
2643 if (p.pid == initialPid) {
2644 proc = p;
2645 break;
2646 }
2647 for (String str : p.pkgList) {
2648 if (str.equals(packageName)) {
2649 proc = p;
2650 }
2651 }
2652 }
2653 }
2654
2655 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002656 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002657 + " initialPid=" + initialPid
2658 + " packageName=" + packageName);
2659 return;
2660 }
2661
2662 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002663 if (proc.pid == Process.myPid()) {
2664 Log.w(TAG, "crashApplication: trying to crash self!");
2665 return;
2666 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002667 long ident = Binder.clearCallingIdentity();
2668 try {
2669 proc.thread.scheduleCrash(message);
2670 } catch (RemoteException e) {
2671 }
2672 Binder.restoreCallingIdentity(ident);
2673 }
2674 }
2675 }
2676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 public final void finishSubActivity(IBinder token, String resultWho,
2678 int requestCode) {
2679 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002680 ActivityRecord self = mMainStack.isInStackLocked(token);
2681 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 return;
2683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684
2685 final long origId = Binder.clearCallingIdentity();
2686
2687 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002688 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2689 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 if (r.resultTo == self && r.requestCode == requestCode) {
2691 if ((r.resultWho == null && resultWho == null) ||
2692 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002693 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 Activity.RESULT_CANCELED, null, "request-sub");
2695 }
2696 }
2697 }
2698
2699 Binder.restoreCallingIdentity(origId);
2700 }
2701 }
2702
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002703 public boolean willActivityBeVisible(IBinder token) {
2704 synchronized(this) {
2705 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002706 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2707 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002708 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002709 return true;
2710 }
2711 if (r.fullscreen && !r.finishing) {
2712 return false;
2713 }
2714 }
2715 return true;
2716 }
2717 }
2718
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002719 public void overridePendingTransition(IBinder token, String packageName,
2720 int enterAnim, int exitAnim) {
2721 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002722 ActivityRecord self = mMainStack.isInStackLocked(token);
2723 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002724 return;
2725 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002726
2727 final long origId = Binder.clearCallingIdentity();
2728
2729 if (self.state == ActivityState.RESUMED
2730 || self.state == ActivityState.PAUSING) {
2731 mWindowManager.overridePendingAppTransition(packageName,
2732 enterAnim, exitAnim);
2733 }
2734
2735 Binder.restoreCallingIdentity(origId);
2736 }
2737 }
2738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 * Main function for removing an existing process from the activity manager
2741 * as a result of that process going away. Clears out all connections
2742 * to the process.
2743 */
2744 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002745 boolean restarting, boolean allowRestart) {
2746 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002748 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 }
2750
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002751 if (mProfileProc == app) {
2752 clearProfilerLocked();
2753 }
2754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002756 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2757 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2758 mMainStack.mPausingActivity = null;
2759 }
2760 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2761 mMainStack.mLastPausedActivity = null;
2762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763
2764 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002765 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766
2767 boolean atTop = true;
2768 boolean hasVisibleActivities = false;
2769
2770 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002771 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002772 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 TAG, "Removing app " + app + " from history with " + i + " entries");
2774 while (i > 0) {
2775 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002776 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002777 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2779 if (r.app == app) {
2780 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002781 if (ActivityStack.DEBUG_ADD_REMOVE) {
2782 RuntimeException here = new RuntimeException("here");
2783 here.fillInStackTrace();
2784 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2785 + ": haveState=" + r.haveState
2786 + " stateNotNeeded=" + r.stateNotNeeded
2787 + " finishing=" + r.finishing
2788 + " state=" + r.state, here);
2789 }
2790 if (!r.finishing) {
2791 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002792 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2793 System.identityHashCode(r),
2794 r.task.taskId, r.shortComponentName,
2795 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002796 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002797 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798
2799 } else {
2800 // We have the current state for this activity, so
2801 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002802 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 TAG, "Keeping entry, setting app to null");
2804 if (r.visible) {
2805 hasVisibleActivities = true;
2806 }
2807 r.app = null;
2808 r.nowVisible = false;
2809 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002810 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2811 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 r.icicle = null;
2813 }
2814 }
2815
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002816 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 }
2818 atTop = false;
2819 }
2820
2821 app.activities.clear();
2822
2823 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002824 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 + " running instrumentation " + app.instrumentationClass);
2826 Bundle info = new Bundle();
2827 info.putString("shortMsg", "Process crashed.");
2828 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2829 }
2830
2831 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002832 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 // If there was nothing to resume, and we are not already
2834 // restarting this process, but there is a visible activity that
2835 // is hosted by the process... then make sure all visible
2836 // activities are running, taking care of restarting this
2837 // process.
2838 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002839 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 }
2841 }
2842 }
2843 }
2844
2845 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2846 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002848 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2849 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2851 return i;
2852 }
2853 }
2854 return -1;
2855 }
2856
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002857 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 IApplicationThread thread) {
2859 if (thread == null) {
2860 return null;
2861 }
2862
2863 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002864 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 }
2866
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002867 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 IApplicationThread thread) {
2869
2870 mProcDeaths[0]++;
2871
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002872 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2873 synchronized (stats) {
2874 stats.noteProcessDiedLocked(app.info.uid, pid);
2875 }
2876
Magnus Edlund7bb25812010-02-24 15:45:06 +01002877 // Clean up already done if the process has been re-started.
2878 if (app.pid == pid && app.thread != null &&
2879 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002880 if (!app.killedBackground) {
2881 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2882 + ") has died.");
2883 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002884 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002885 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 TAG, "Dying app: " + app + ", pid: " + pid
2887 + ", thread: " + thread.asBinder());
2888 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002889 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890
2891 if (doLowMem) {
2892 // If there are no longer any background processes running,
2893 // and the app that died was not running instrumentation,
2894 // then tell everyone we are now low on memory.
2895 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002896 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2897 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002898 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 haveBg = true;
2900 break;
2901 }
2902 }
2903
2904 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002905 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002906 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002907 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2908 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002909 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002910 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2911 // The low memory report is overriding any current
2912 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002913 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002914 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002915 rec.lastRequestedGc = 0;
2916 } else {
2917 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002919 rec.reportLowMemory = true;
2920 rec.lastLowMemory = now;
2921 mProcessesToGc.remove(rec);
2922 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 }
2924 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002925 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002926 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 }
2928 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002929 } else if (app.pid != pid) {
2930 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002931 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002932 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002933 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002934 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002935 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 + thread.asBinder());
2937 }
2938 }
2939
Dan Egnor42471dd2010-01-07 17:25:22 -08002940 /**
2941 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002942 * @param clearTraces causes the dump file to be erased prior to the new
2943 * traces being written, if true; when false, the new traces will be
2944 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002945 * @param firstPids of dalvik VM processes to dump stack traces for first
2946 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002947 * @return file containing stack traces, or null if no dump file is configured
2948 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002949 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2950 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002951 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2952 if (tracesPath == null || tracesPath.length() == 0) {
2953 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002955
2956 File tracesFile = new File(tracesPath);
2957 try {
2958 File tracesDir = tracesFile.getParentFile();
2959 if (!tracesDir.exists()) tracesFile.mkdirs();
2960 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2961
Christopher Tate6ee412d2010-05-28 12:01:56 -07002962 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002963 tracesFile.createNewFile();
2964 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2965 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002966 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002967 return null;
2968 }
2969
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002970 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2971 return tracesFile;
2972 }
2973
2974 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2975 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002976 // Use a FileObserver to detect when traces finish writing.
2977 // The order of traces is considered important to maintain for legibility.
2978 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2979 public synchronized void onEvent(int event, String path) { notify(); }
2980 };
2981
2982 try {
2983 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002984
2985 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002986 if (firstPids != null) {
2987 try {
2988 int num = firstPids.size();
2989 for (int i = 0; i < num; i++) {
2990 synchronized (observer) {
2991 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2992 observer.wait(200); // Wait for write-close, give up after 200msec
2993 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002994 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002995 } catch (InterruptedException e) {
2996 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002997 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002998 }
2999
3000 // Next measure CPU usage.
3001 if (processStats != null) {
3002 processStats.init();
3003 System.gc();
3004 processStats.update();
3005 try {
3006 synchronized (processStats) {
3007 processStats.wait(500); // measure over 1/2 second.
3008 }
3009 } catch (InterruptedException e) {
3010 }
3011 processStats.update();
3012
3013 // We'll take the stack crawls of just the top apps using CPU.
3014 final int N = processStats.countWorkingStats();
3015 int numProcs = 0;
3016 for (int i=0; i<N && numProcs<5; i++) {
3017 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3018 if (lastPids.indexOfKey(stats.pid) >= 0) {
3019 numProcs++;
3020 try {
3021 synchronized (observer) {
3022 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3023 observer.wait(200); // Wait for write-close, give up after 200msec
3024 }
3025 } catch (InterruptedException e) {
3026 Log.wtf(TAG, e);
3027 }
3028
3029 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003030 }
3031 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003032
Dan Egnor42471dd2010-01-07 17:25:22 -08003033 } finally {
3034 observer.stopWatching();
3035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 }
3037
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003038 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
3039 if (IS_USER_BUILD) {
3040 return;
3041 }
3042 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3043 if (tracesPath == null || tracesPath.length() == 0) {
3044 return;
3045 }
3046
3047 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3048 StrictMode.allowThreadDiskWrites();
3049 try {
3050 final File tracesFile = new File(tracesPath);
3051 final File tracesDir = tracesFile.getParentFile();
3052 final File tracesTmp = new File(tracesDir, "__tmp__");
3053 try {
3054 if (!tracesDir.exists()) tracesFile.mkdirs();
3055 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3056
3057 if (tracesFile.exists()) {
3058 tracesTmp.delete();
3059 tracesFile.renameTo(tracesTmp);
3060 }
3061 StringBuilder sb = new StringBuilder();
3062 Time tobj = new Time();
3063 tobj.set(System.currentTimeMillis());
3064 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3065 sb.append(": ");
3066 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3067 sb.append(" since ");
3068 sb.append(msg);
3069 FileOutputStream fos = new FileOutputStream(tracesFile);
3070 fos.write(sb.toString().getBytes());
3071 if (app == null) {
3072 fos.write("\n*** No application process!".getBytes());
3073 }
3074 fos.close();
3075 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3076 } catch (IOException e) {
3077 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3078 return;
3079 }
3080
3081 if (app != null) {
3082 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3083 firstPids.add(app.pid);
3084 dumpStackTraces(tracesPath, firstPids, null, null);
3085 }
3086
3087 File lastTracesFile = null;
3088 File curTracesFile = null;
3089 for (int i=9; i>=0; i--) {
3090 String name = String.format("slow%02d.txt", i);
3091 curTracesFile = new File(tracesDir, name);
3092 if (curTracesFile.exists()) {
3093 if (lastTracesFile != null) {
3094 curTracesFile.renameTo(lastTracesFile);
3095 } else {
3096 curTracesFile.delete();
3097 }
3098 }
3099 lastTracesFile = curTracesFile;
3100 }
3101 tracesFile.renameTo(curTracesFile);
3102 if (tracesTmp.exists()) {
3103 tracesTmp.renameTo(tracesFile);
3104 }
3105 } finally {
3106 StrictMode.setThreadPolicy(oldPolicy);
3107 }
3108 }
3109
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003110 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3111 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003112 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3113 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3114
Dianne Hackborn287952c2010-09-22 22:34:31 -07003115 if (mController != null) {
3116 try {
3117 // 0 == continue, -1 = kill process immediately
3118 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3119 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3120 } catch (RemoteException e) {
3121 mController = null;
3122 }
3123 }
3124
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003125 long anrTime = SystemClock.uptimeMillis();
3126 if (MONITOR_CPU_USAGE) {
3127 updateCpuStatsNow();
3128 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003129
3130 synchronized (this) {
3131 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3132 if (mShuttingDown) {
3133 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3134 return;
3135 } else if (app.notResponding) {
3136 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3137 return;
3138 } else if (app.crashing) {
3139 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3140 return;
3141 }
3142
3143 // In case we come through here for the same app before completing
3144 // this one, mark as anring now so we will bail out.
3145 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003146
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003147 // Log the ANR to the event log.
3148 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3149 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003150
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003151 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003152 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003153
3154 int parentPid = app.pid;
3155 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003156 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003157
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003158 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003159
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003160 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3161 ProcessRecord r = mLruProcesses.get(i);
3162 if (r != null && r.thread != null) {
3163 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003164 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3165 if (r.persistent) {
3166 firstPids.add(pid);
3167 } else {
3168 lastPids.put(pid, Boolean.TRUE);
3169 }
3170 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 }
3173 }
3174
Dan Egnor42471dd2010-01-07 17:25:22 -08003175 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003176 StringBuilder info = mStringBuilder;
3177 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003178 info.append("ANR in ").append(app.processName);
3179 if (activity != null && activity.shortComponentName != null) {
3180 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003181 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003182 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003183 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003184 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003186 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003187 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189
Dianne Hackborn287952c2010-09-22 22:34:31 -07003190 final ProcessStats processStats = new ProcessStats(true);
3191
3192 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3193
Dan Egnor42471dd2010-01-07 17:25:22 -08003194 String cpuInfo = null;
3195 if (MONITOR_CPU_USAGE) {
3196 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003197 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003198 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003199 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003200 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003201 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 }
3203
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003204 info.append(processStats.printCurrentState(anrTime));
3205
Joe Onorato8a9b2202010-02-26 18:56:32 -08003206 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003207 if (tracesFile == null) {
3208 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3209 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3210 }
3211
Jeff Sharkeya353d262011-10-28 11:12:06 -07003212 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3213 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003214
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003215 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003217 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3218 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003220 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3221 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 }
3223 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003224 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 }
3226 }
3227
Dan Egnor42471dd2010-01-07 17:25:22 -08003228 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3229 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3230 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003231
3232 synchronized (this) {
3233 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003234 Slog.w(TAG, "Killing " + app + ": background ANR");
3235 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3236 app.processName, app.setAdj, "background ANR");
3237 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003238 return;
3239 }
3240
3241 // Set the app's notResponding state, and look up the errorReportReceiver
3242 makeAppNotRespondingLocked(app,
3243 activity != null ? activity.shortComponentName : null,
3244 annotation != null ? "ANR " + annotation : "ANR",
3245 info.toString());
3246
3247 // Bring up the infamous App Not Responding dialog
3248 Message msg = Message.obtain();
3249 HashMap map = new HashMap();
3250 msg.what = SHOW_NOT_RESPONDING_MSG;
3251 msg.obj = map;
3252 map.put("app", app);
3253 if (activity != null) {
3254 map.put("activity", activity);
3255 }
3256
3257 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 }
3260
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003261 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3262 if (!mLaunchWarningShown) {
3263 mLaunchWarningShown = true;
3264 mHandler.post(new Runnable() {
3265 @Override
3266 public void run() {
3267 synchronized (ActivityManagerService.this) {
3268 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3269 d.show();
3270 mHandler.postDelayed(new Runnable() {
3271 @Override
3272 public void run() {
3273 synchronized (ActivityManagerService.this) {
3274 d.dismiss();
3275 mLaunchWarningShown = false;
3276 }
3277 }
3278 }, 4000);
3279 }
3280 }
3281 });
3282 }
3283 }
3284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003286 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003287 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 int uid = Binder.getCallingUid();
3289 int pid = Binder.getCallingPid();
3290 long callingId = Binder.clearCallingIdentity();
3291 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003292 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 int pkgUid = -1;
3294 synchronized(this) {
3295 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003296 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 } catch (RemoteException e) {
3298 }
3299 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003300 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 return false;
3302 }
3303 if (uid == pkgUid || checkComponentPermission(
3304 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003305 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003307 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 } else {
3309 throw new SecurityException(pid+" does not have permission:"+
3310 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3311 "for process:"+packageName);
3312 }
3313 }
3314
3315 try {
3316 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003317 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3319 Uri.fromParts("package", packageName, null));
3320 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003321 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003322 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 } catch (RemoteException e) {
3324 }
3325 } finally {
3326 Binder.restoreCallingIdentity(callingId);
3327 }
3328 return true;
3329 }
3330
Dianne Hackborn03abb812010-01-04 18:43:19 -08003331 public void killBackgroundProcesses(final String packageName) {
3332 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3333 != PackageManager.PERMISSION_GRANTED &&
3334 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3335 != PackageManager.PERMISSION_GRANTED) {
3336 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 + Binder.getCallingPid()
3338 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003339 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003340 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 throw new SecurityException(msg);
3342 }
3343
Amith Yamasani483f3b02012-03-13 16:08:00 -07003344 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 long callingId = Binder.clearCallingIdentity();
3346 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003347 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 int pkgUid = -1;
3349 synchronized(this) {
3350 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003351 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 } catch (RemoteException e) {
3353 }
3354 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003355 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 return;
3357 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003358 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003359 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3360 }
3361 } finally {
3362 Binder.restoreCallingIdentity(callingId);
3363 }
3364 }
3365
3366 public void killAllBackgroundProcesses() {
3367 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3368 != PackageManager.PERMISSION_GRANTED) {
3369 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3370 + Binder.getCallingPid()
3371 + ", uid=" + Binder.getCallingUid()
3372 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3373 Slog.w(TAG, msg);
3374 throw new SecurityException(msg);
3375 }
3376
3377 long callingId = Binder.clearCallingIdentity();
3378 try {
3379 synchronized(this) {
3380 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3381 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3382 final int NA = apps.size();
3383 for (int ia=0; ia<NA; ia++) {
3384 ProcessRecord app = apps.valueAt(ia);
3385 if (app.persistent) {
3386 // we don't kill persistent processes
3387 continue;
3388 }
3389 if (app.removed) {
3390 procs.add(app);
3391 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3392 app.removed = true;
3393 procs.add(app);
3394 }
3395 }
3396 }
3397
3398 int N = procs.size();
3399 for (int i=0; i<N; i++) {
3400 removeProcessLocked(procs.get(i), false, true, "kill all background");
3401 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003402 }
3403 } finally {
3404 Binder.restoreCallingIdentity(callingId);
3405 }
3406 }
3407
3408 public void forceStopPackage(final String packageName) {
3409 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3410 != PackageManager.PERMISSION_GRANTED) {
3411 String msg = "Permission Denial: forceStopPackage() from pid="
3412 + Binder.getCallingPid()
3413 + ", uid=" + Binder.getCallingUid()
3414 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003415 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003416 throw new SecurityException(msg);
3417 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003418 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003419 long callingId = Binder.clearCallingIdentity();
3420 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003421 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003422 int pkgUid = -1;
3423 synchronized(this) {
3424 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003425 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003426 } catch (RemoteException e) {
3427 }
3428 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003429 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003430 return;
3431 }
3432 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003433 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003434 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003435 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003436 } catch (IllegalArgumentException e) {
3437 Slog.w(TAG, "Failed trying to unstop package "
3438 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 }
3441 } finally {
3442 Binder.restoreCallingIdentity(callingId);
3443 }
3444 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003445
3446 /*
3447 * The pkg name and uid have to be specified.
3448 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3449 */
3450 public void killApplicationWithUid(String pkg, int uid) {
3451 if (pkg == null) {
3452 return;
3453 }
3454 // Make sure the uid is valid.
3455 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003456 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003457 return;
3458 }
3459 int callerUid = Binder.getCallingUid();
3460 // Only the system server can kill an application
3461 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003462 // Post an aysnc message to kill the application
3463 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3464 msg.arg1 = uid;
3465 msg.arg2 = 0;
3466 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003467 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003468 } else {
3469 throw new SecurityException(callerUid + " cannot kill pkg: " +
3470 pkg);
3471 }
3472 }
3473
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003474 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003475 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003476 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003477 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003478 if (reason != null) {
3479 intent.putExtra("reason", reason);
3480 }
3481
3482 final int uid = Binder.getCallingUid();
3483 final long origId = Binder.clearCallingIdentity();
3484 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003485 mWindowManager.closeSystemDialogs(reason);
3486
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003487 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003488 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003489 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003490 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003491 Activity.RESULT_CANCELED, null, "close-sys");
3492 }
3493 }
3494
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003495 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003496 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003497 }
3498 Binder.restoreCallingIdentity(origId);
3499 }
3500
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003501 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003502 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003503 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003504 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3505 for (int i=pids.length-1; i>=0; i--) {
3506 infos[i] = new Debug.MemoryInfo();
3507 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003508 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003509 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003510 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003511
Dianne Hackbornb437e092011-08-05 17:50:29 -07003512 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003513 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003514 long[] pss = new long[pids.length];
3515 for (int i=pids.length-1; i>=0; i--) {
3516 pss[i] = Debug.getPss(pids[i]);
3517 }
3518 return pss;
3519 }
3520
Christopher Tate5e1ab332009-09-01 20:32:49 -07003521 public void killApplicationProcess(String processName, int uid) {
3522 if (processName == null) {
3523 return;
3524 }
3525
3526 int callerUid = Binder.getCallingUid();
3527 // Only the system server can kill an application
3528 if (callerUid == Process.SYSTEM_UID) {
3529 synchronized (this) {
3530 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003531 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003532 try {
3533 app.thread.scheduleSuicide();
3534 } catch (RemoteException e) {
3535 // If the other end already died, then our work here is done.
3536 }
3537 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003538 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003539 + processName + " / " + uid);
3540 }
3541 }
3542 } else {
3543 throw new SecurityException(callerUid + " cannot kill app process: " +
3544 processName);
3545 }
3546 }
3547
Dianne Hackborn03abb812010-01-04 18:43:19 -08003548 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003549 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3551 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003552 if (!mProcessesReady) {
3553 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003555 intent.putExtra(Intent.EXTRA_UID, uid);
3556 broadcastIntentLocked(null, null, intent,
3557 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003558 false, false,
3559 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003560 }
3561
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003562 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003563 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003564 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003565 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566
Dianne Hackborn03abb812010-01-04 18:43:19 -08003567 // Remove all processes this package may have touched: all with the
3568 // same UID (except for the system or root user), and all whose name
3569 // matches the package name.
3570 final String procNamePrefix = packageName + ":";
3571 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3572 final int NA = apps.size();
3573 for (int ia=0; ia<NA; ia++) {
3574 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003575 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003576 // we don't kill persistent processes
3577 continue;
3578 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003579 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003580 if (doit) {
3581 procs.add(app);
3582 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003583 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3584 || app.processName.equals(packageName)
3585 || app.processName.startsWith(procNamePrefix)) {
3586 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003587 if (!doit) {
3588 return true;
3589 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003590 app.removed = true;
3591 procs.add(app);
3592 }
3593 }
3594 }
3595 }
3596
3597 int N = procs.size();
3598 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003599 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003600 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003601 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003602 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003603
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003604 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003605 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003606 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003607 int i;
3608 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 if (uid < 0) {
3611 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003612 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 } catch (RemoteException e) {
3614 }
3615 }
3616
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003617 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003618 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003619
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003620 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3621 while (badApps.hasNext()) {
3622 SparseArray<Long> ba = badApps.next();
3623 if (ba.get(uid) != null) {
3624 badApps.remove();
3625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 }
3627 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003628
3629 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003630 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003632 TaskRecord lastTask = null;
3633 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003634 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003635 final boolean samePackage = r.packageName.equals(name);
3636 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003637 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003638 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003639 if (r.finishing) {
3640 // If this activity is just finishing, then it is not
3641 // interesting as far as something to stop.
3642 continue;
3643 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003644 return true;
3645 }
3646 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003647 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003648 if (samePackage) {
3649 if (r.app != null) {
3650 r.app.removed = true;
3651 }
3652 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003654 lastTask = r.task;
3655 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3656 null, "force-stop")) {
3657 i--;
3658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 }
3660 }
3661
3662 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003663 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003664 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003665 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003666 if (!doit) {
3667 return true;
3668 }
3669 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003670 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 if (service.app != null) {
3672 service.app.removed = true;
3673 }
3674 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003675 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 services.add(service);
3677 }
3678 }
3679
3680 N = services.size();
3681 for (i=0; i<N; i++) {
3682 bringDownServiceLocked(services.get(i), true);
3683 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003684
3685 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani37ce3a82012-02-06 12:04:42 -08003686 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(-1).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003687 if (provider.info.packageName.equals(name)
3688 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3689 if (!doit) {
3690 return true;
3691 }
3692 didSomething = true;
3693 providers.add(provider);
3694 }
3695 }
3696
3697 N = providers.size();
3698 for (i=0; i<N; i++) {
3699 removeDyingProviderLocked(null, providers.get(i));
3700 }
3701
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003702 if (doit) {
3703 if (purgeCache) {
3704 AttributeCache ac = AttributeCache.instance();
3705 if (ac != null) {
3706 ac.removePackage(name);
3707 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003708 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003709 if (mBooted) {
3710 mMainStack.resumeTopActivityLocked(null);
3711 mMainStack.scheduleIdleLocked();
3712 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003713 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003714
3715 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 }
3717
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003718 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003719 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003721 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003722 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003723 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 + "/" + uid + ")");
3725
3726 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003727 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003728 if (mHeavyWeightProcess == app) {
3729 mHeavyWeightProcess = null;
3730 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 boolean needRestart = false;
3733 if (app.pid > 0 && app.pid != MY_PID) {
3734 int pid = app.pid;
3735 synchronized (mPidsSelfLocked) {
3736 mPidsSelfLocked.remove(pid);
3737 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3738 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003739 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003740 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003741 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003742 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003744 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003746 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747 } else {
3748 needRestart = true;
3749 }
3750 }
3751 } else {
3752 mRemovedProcesses.add(app);
3753 }
3754
3755 return needRestart;
3756 }
3757
3758 private final void processStartTimedOutLocked(ProcessRecord app) {
3759 final int pid = app.pid;
3760 boolean gone = false;
3761 synchronized (mPidsSelfLocked) {
3762 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3763 if (knownApp != null && knownApp.thread == null) {
3764 mPidsSelfLocked.remove(pid);
3765 gone = true;
3766 }
3767 }
3768
3769 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003770 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003771 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003772 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003773 mProcessNames.remove(app.processName, app.uid);
3774 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003775 if (mHeavyWeightProcess == app) {
3776 mHeavyWeightProcess = null;
3777 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3778 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003779 // Take care of any launching providers waiting for this process.
3780 checkAppInLaunchingProvidersLocked(app, true);
3781 // Take care of any services that are waiting for the process.
3782 for (int i=0; i<mPendingServices.size(); i++) {
3783 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003784 if ((app.uid == sr.appInfo.uid
3785 && app.processName.equals(sr.processName))
3786 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003787 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003788 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003789 mPendingServices.remove(i);
3790 i--;
3791 bringDownServiceLocked(sr, true);
3792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003794 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3795 app.processName, app.setAdj, "start timeout");
3796 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003797 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003798 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003799 try {
3800 IBackupManager bm = IBackupManager.Stub.asInterface(
3801 ServiceManager.getService(Context.BACKUP_SERVICE));
3802 bm.agentDisconnected(app.info.packageName);
3803 } catch (RemoteException e) {
3804 // Can't happen; the backup manager is local
3805 }
3806 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003807 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003808 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003809 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003812 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 }
3814 }
3815
3816 private final boolean attachApplicationLocked(IApplicationThread thread,
3817 int pid) {
3818
3819 // Find the application record that is being attached... either via
3820 // the pid if we are running in multiple processes, or just pull the
3821 // next app record if we are emulating process with anonymous threads.
3822 ProcessRecord app;
3823 if (pid != MY_PID && pid >= 0) {
3824 synchronized (mPidsSelfLocked) {
3825 app = mPidsSelfLocked.get(pid);
3826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 } else {
3828 app = null;
3829 }
3830
3831 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003832 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003834 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003836 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 } else {
3838 try {
3839 thread.scheduleExit();
3840 } catch (Exception e) {
3841 // Ignore exceptions.
3842 }
3843 }
3844 return false;
3845 }
3846
3847 // If this application record is still attached to a previous
3848 // process, clean it up now.
3849 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003850 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 }
3852
3853 // Tell the process all about itself.
3854
Joe Onorato8a9b2202010-02-26 18:56:32 -08003855 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 TAG, "Binding process pid " + pid + " to record " + app);
3857
3858 String processName = app.processName;
3859 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003860 AppDeathRecipient adr = new AppDeathRecipient(
3861 app, pid, thread);
3862 thread.asBinder().linkToDeath(adr, 0);
3863 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 } catch (RemoteException e) {
3865 app.resetPackageList();
3866 startProcessLocked(app, "link fail", processName);
3867 return false;
3868 }
3869
Doug Zongker2bec3d42009-12-04 12:52:44 -08003870 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871
3872 app.thread = thread;
3873 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003874 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3875 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 app.forcingToForeground = null;
3877 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003878 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 app.debugging = false;
3880
3881 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3882
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003883 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003884 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003886 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003887 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003888 }
3889
Joe Onorato8a9b2202010-02-26 18:56:32 -08003890 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 TAG, "New app record " + app
3892 + " thread=" + thread.asBinder() + " pid=" + pid);
3893 try {
3894 int testMode = IApplicationThread.DEBUG_OFF;
3895 if (mDebugApp != null && mDebugApp.equals(processName)) {
3896 testMode = mWaitForDebugger
3897 ? IApplicationThread.DEBUG_WAIT
3898 : IApplicationThread.DEBUG_ON;
3899 app.debugging = true;
3900 if (mDebugTransient) {
3901 mDebugApp = mOrigDebugApp;
3902 mWaitForDebugger = mOrigWaitForDebugger;
3903 }
3904 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003905 String profileFile = app.instrumentationProfileFile;
3906 ParcelFileDescriptor profileFd = null;
3907 boolean profileAutoStop = false;
3908 if (mProfileApp != null && mProfileApp.equals(processName)) {
3909 mProfileProc = app;
3910 profileFile = mProfileFile;
3911 profileFd = mProfileFd;
3912 profileAutoStop = mAutoStopProfiler;
3913 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003914 boolean enableOpenGlTrace = false;
3915 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3916 enableOpenGlTrace = true;
3917 mOpenGlTraceApp = null;
3918 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003919
Christopher Tate181fafa2009-05-14 11:12:14 -07003920 // If the app is being launched for restore or full backup, set it up specially
3921 boolean isRestrictedBackupMode = false;
3922 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3923 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003924 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003925 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3926 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003927
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003928 ensurePackageDexOpt(app.instrumentationInfo != null
3929 ? app.instrumentationInfo.packageName
3930 : app.info.packageName);
3931 if (app.instrumentationClass != null) {
3932 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003933 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003934 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003935 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003936 ApplicationInfo appInfo = app.instrumentationInfo != null
3937 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003938 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003939 if (profileFd != null) {
3940 profileFd = profileFd.dup();
3941 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003942 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003943 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003944 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3945 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003946 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003947 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003948 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003949 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 } catch (Exception e) {
3951 // todo: Yikes! What should we do? For now we will try to
3952 // start another process, but that could easily get us in
3953 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003954 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955
3956 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003957 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 startProcessLocked(app, "bind fail", processName);
3959 return false;
3960 }
3961
3962 // Remove this record from the list of starting applications.
3963 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003964 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3965 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 mProcessesOnHold.remove(app);
3967
3968 boolean badApp = false;
3969 boolean didSomething = false;
3970
3971 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003972 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003973 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003974 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 && processName.equals(hr.processName)) {
3976 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003977 if (mHeadless) {
3978 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3979 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 didSomething = true;
3981 }
3982 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003983 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 + hr.intent.getComponent().flattenToShortString(), e);
3985 badApp = true;
3986 }
3987 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003988 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 }
3990 }
3991
3992 // Find any services that should be running in this process...
3993 if (!badApp && mPendingServices.size() > 0) {
3994 ServiceRecord sr = null;
3995 try {
3996 for (int i=0; i<mPendingServices.size(); i++) {
3997 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003998 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
3999 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 continue;
4001 }
4002
4003 mPendingServices.remove(i);
4004 i--;
4005 realStartServiceLocked(sr, app);
4006 didSomething = true;
4007 }
4008 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004009 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 + sr.shortName, e);
4011 badApp = true;
4012 }
4013 }
4014
Christopher Tatef46723b2012-01-26 14:19:24 -08004015 // Check if a next-broadcast receiver is in this process...
4016 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004018 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004020 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 }
4023 }
4024
Christopher Tate181fafa2009-05-14 11:12:14 -07004025 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004026 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004027 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004028 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004029 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004030 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4031 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4032 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004033 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004034 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004035 e.printStackTrace();
4036 }
4037 }
4038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 if (badApp) {
4040 // todo: Also need to kill application to deal with all
4041 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004042 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 return false;
4044 }
4045
4046 if (!didSomething) {
4047 updateOomAdjLocked();
4048 }
4049
4050 return true;
4051 }
4052
4053 public final void attachApplication(IApplicationThread thread) {
4054 synchronized (this) {
4055 int callingPid = Binder.getCallingPid();
4056 final long origId = Binder.clearCallingIdentity();
4057 attachApplicationLocked(thread, callingPid);
4058 Binder.restoreCallingIdentity(origId);
4059 }
4060 }
4061
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004062 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004064 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4065 if (stopProfiling) {
4066 synchronized (this) {
4067 if (mProfileProc == r.app) {
4068 if (mProfileFd != null) {
4069 try {
4070 mProfileFd.close();
4071 } catch (IOException e) {
4072 }
4073 clearProfilerLocked();
4074 }
4075 }
4076 }
4077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 Binder.restoreCallingIdentity(origId);
4079 }
4080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004081 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004082 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004083 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 mWindowManager.enableScreenAfterBoot();
4085 }
4086
Dianne Hackborn661cd522011-08-22 00:26:20 -07004087 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004088 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004089 mWindowManager.showBootMessage(msg, always);
4090 }
4091
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004092 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004093 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004094 synchronized (this) {
4095 mMainStack.dismissKeyguardOnNextActivityLocked();
4096 }
4097 }
4098
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004099 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004100 IntentFilter pkgFilter = new IntentFilter();
4101 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4102 pkgFilter.addDataScheme("package");
4103 mContext.registerReceiver(new BroadcastReceiver() {
4104 @Override
4105 public void onReceive(Context context, Intent intent) {
4106 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4107 if (pkgs != null) {
4108 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004109 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004110 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4111 setResultCode(Activity.RESULT_OK);
4112 return;
4113 }
4114 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004115 }
4116 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004117 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004118 }, pkgFilter);
4119
4120 synchronized (this) {
4121 // Ensure that any processes we had put on hold are now started
4122 // up.
4123 final int NP = mProcessesOnHold.size();
4124 if (NP > 0) {
4125 ArrayList<ProcessRecord> procs =
4126 new ArrayList<ProcessRecord>(mProcessesOnHold);
4127 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004128 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4129 + procs.get(ip));
4130 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004131 }
4132 }
4133
4134 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004135 // Start looking for apps that are abusing wake locks.
4136 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004137 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004138 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004139 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004140 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004141 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004142 broadcastIntentLocked(null, null,
4143 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4144 null, null, 0, null, null,
4145 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004146 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004147 }
4148 }
4149 }
4150
4151 final void ensureBootCompleted() {
4152 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004153 boolean enableScreen;
4154 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004155 booting = mBooting;
4156 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004157 enableScreen = !mBooted;
4158 mBooted = true;
4159 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004160
4161 if (booting) {
4162 finishBooting();
4163 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004164
4165 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004166 enableScreenAfterBoot();
4167 }
4168 }
4169
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004170 public final void activityPaused(IBinder token) {
4171 final long origId = Binder.clearCallingIdentity();
4172 mMainStack.activityPaused(token, false);
4173 Binder.restoreCallingIdentity(origId);
4174 }
4175
4176 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4177 CharSequence description) {
4178 if (localLOGV) Slog.v(
4179 TAG, "Activity stopped: token=" + token);
4180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181 // Refuse possible leaked file descriptors
4182 if (icicle != null && icicle.hasFileDescriptors()) {
4183 throw new IllegalArgumentException("File descriptors passed in Bundle");
4184 }
4185
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004186 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187
4188 final long origId = Binder.clearCallingIdentity();
4189
4190 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004191 r = mMainStack.isInStackLocked(token);
4192 if (r != null) {
4193 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 }
4195 }
4196
4197 if (r != null) {
4198 sendPendingThumbnail(r, null, null, null, false);
4199 }
4200
4201 trimApplications();
4202
4203 Binder.restoreCallingIdentity(origId);
4204 }
4205
4206 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004207 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004208 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 }
4210
4211 public String getCallingPackage(IBinder token) {
4212 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004213 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004214 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 }
4216 }
4217
4218 public ComponentName getCallingActivity(IBinder token) {
4219 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004220 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 return r != null ? r.intent.getComponent() : null;
4222 }
4223 }
4224
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004225 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004226 ActivityRecord r = mMainStack.isInStackLocked(token);
4227 if (r == null) {
4228 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004230 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004231 }
4232
4233 public ComponentName getActivityClassForToken(IBinder token) {
4234 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004235 ActivityRecord r = mMainStack.isInStackLocked(token);
4236 if (r == null) {
4237 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004239 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 }
4241 }
4242
4243 public String getPackageForToken(IBinder token) {
4244 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004245 ActivityRecord r = mMainStack.isInStackLocked(token);
4246 if (r == null) {
4247 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004249 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 }
4251 }
4252
4253 public IIntentSender getIntentSender(int type,
4254 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004255 int requestCode, Intent[] intents, String[] resolvedTypes,
4256 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004257 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004259 if (intents != null) {
4260 if (intents.length < 1) {
4261 throw new IllegalArgumentException("Intents array length must be >= 1");
4262 }
4263 for (int i=0; i<intents.length; i++) {
4264 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004265 if (intent != null) {
4266 if (intent.hasFileDescriptors()) {
4267 throw new IllegalArgumentException("File descriptors passed in Intent");
4268 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004269 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004270 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4271 throw new IllegalArgumentException(
4272 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4273 }
4274 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004275 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004276 }
4277 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004278 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004279 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004280 }
4281 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004282 if (options != null) {
4283 if (options.hasFileDescriptors()) {
4284 throw new IllegalArgumentException("File descriptors passed in options");
4285 }
4286 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 synchronized(this) {
4289 int callingUid = Binder.getCallingUid();
4290 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004291 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004292 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004293 .getPackageUid(packageName, UserId.getUserId(callingUid));
4294 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 String msg = "Permission Denial: getIntentSender() from pid="
4296 + Binder.getCallingPid()
4297 + ", uid=" + Binder.getCallingUid()
4298 + ", (need uid=" + uid + ")"
4299 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004300 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 throw new SecurityException(msg);
4302 }
4303 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004304
Amith Yamasani742a6712011-05-04 14:49:28 -07004305 if (DEBUG_MU)
4306 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4307 + Binder.getOrigCallingUid());
4308 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004309 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 } catch (RemoteException e) {
4312 throw new SecurityException(e);
4313 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004314 }
4315 }
4316
4317 IIntentSender getIntentSenderLocked(int type,
4318 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004319 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4320 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004321 if (DEBUG_MU)
4322 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004323 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004324 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004325 activity = mMainStack.isInStackLocked(token);
4326 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004327 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004329 if (activity.finishing) {
4330 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004331 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004332 }
4333
4334 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4335 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4336 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4337 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4338 |PendingIntent.FLAG_UPDATE_CURRENT);
4339
4340 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4341 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004342 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004343 WeakReference<PendingIntentRecord> ref;
4344 ref = mIntentSenderRecords.get(key);
4345 PendingIntentRecord rec = ref != null ? ref.get() : null;
4346 if (rec != null) {
4347 if (!cancelCurrent) {
4348 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004349 if (rec.key.requestIntent != null) {
4350 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4351 }
4352 if (intents != null) {
4353 intents[intents.length-1] = rec.key.requestIntent;
4354 rec.key.allIntents = intents;
4355 rec.key.allResolvedTypes = resolvedTypes;
4356 } else {
4357 rec.key.allIntents = null;
4358 rec.key.allResolvedTypes = null;
4359 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 return rec;
4362 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004363 rec.canceled = true;
4364 mIntentSenderRecords.remove(key);
4365 }
4366 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 return rec;
4368 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004369 rec = new PendingIntentRecord(this, key, callingUid);
4370 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004371 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004372 if (activity.pendingResults == null) {
4373 activity.pendingResults
4374 = new HashSet<WeakReference<PendingIntentRecord>>();
4375 }
4376 activity.pendingResults.add(rec.ref);
4377 }
4378 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 }
4380
4381 public void cancelIntentSender(IIntentSender sender) {
4382 if (!(sender instanceof PendingIntentRecord)) {
4383 return;
4384 }
4385 synchronized(this) {
4386 PendingIntentRecord rec = (PendingIntentRecord)sender;
4387 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004388 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004389 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004390 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 String msg = "Permission Denial: cancelIntentSender() from pid="
4392 + Binder.getCallingPid()
4393 + ", uid=" + Binder.getCallingUid()
4394 + " is not allowed to cancel packges "
4395 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004396 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 throw new SecurityException(msg);
4398 }
4399 } catch (RemoteException e) {
4400 throw new SecurityException(e);
4401 }
4402 cancelIntentSenderLocked(rec, true);
4403 }
4404 }
4405
4406 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4407 rec.canceled = true;
4408 mIntentSenderRecords.remove(rec.key);
4409 if (cleanActivity && rec.key.activity != null) {
4410 rec.key.activity.pendingResults.remove(rec.ref);
4411 }
4412 }
4413
4414 public String getPackageForIntentSender(IIntentSender pendingResult) {
4415 if (!(pendingResult instanceof PendingIntentRecord)) {
4416 return null;
4417 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004418 try {
4419 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4420 return res.key.packageName;
4421 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 }
4423 return null;
4424 }
4425
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004426 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4427 if (!(pendingResult instanceof PendingIntentRecord)) {
4428 return false;
4429 }
4430 try {
4431 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4432 if (res.key.allIntents == null) {
4433 return false;
4434 }
4435 for (int i=0; i<res.key.allIntents.length; i++) {
4436 Intent intent = res.key.allIntents[i];
4437 if (intent.getPackage() != null && intent.getComponent() != null) {
4438 return false;
4439 }
4440 }
4441 return true;
4442 } catch (ClassCastException e) {
4443 }
4444 return false;
4445 }
4446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 public void setProcessLimit(int max) {
4448 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4449 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004450 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004451 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004452 mProcessLimitOverride = max;
4453 }
4454 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 }
4456
4457 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004458 synchronized (this) {
4459 return mProcessLimitOverride;
4460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 }
4462
4463 void foregroundTokenDied(ForegroundToken token) {
4464 synchronized (ActivityManagerService.this) {
4465 synchronized (mPidsSelfLocked) {
4466 ForegroundToken cur
4467 = mForegroundProcesses.get(token.pid);
4468 if (cur != token) {
4469 return;
4470 }
4471 mForegroundProcesses.remove(token.pid);
4472 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4473 if (pr == null) {
4474 return;
4475 }
4476 pr.forcingToForeground = null;
4477 pr.foregroundServices = false;
4478 }
4479 updateOomAdjLocked();
4480 }
4481 }
4482
4483 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4484 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4485 "setProcessForeground()");
4486 synchronized(this) {
4487 boolean changed = false;
4488
4489 synchronized (mPidsSelfLocked) {
4490 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004491 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004492 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 return;
4494 }
4495 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4496 if (oldToken != null) {
4497 oldToken.token.unlinkToDeath(oldToken, 0);
4498 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004499 if (pr != null) {
4500 pr.forcingToForeground = null;
4501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 changed = true;
4503 }
4504 if (isForeground && token != null) {
4505 ForegroundToken newToken = new ForegroundToken() {
4506 public void binderDied() {
4507 foregroundTokenDied(this);
4508 }
4509 };
4510 newToken.pid = pid;
4511 newToken.token = token;
4512 try {
4513 token.linkToDeath(newToken, 0);
4514 mForegroundProcesses.put(pid, newToken);
4515 pr.forcingToForeground = token;
4516 changed = true;
4517 } catch (RemoteException e) {
4518 // If the process died while doing this, we will later
4519 // do the cleanup with the process death link.
4520 }
4521 }
4522 }
4523
4524 if (changed) {
4525 updateOomAdjLocked();
4526 }
4527 }
4528 }
4529
4530 // =========================================================
4531 // PERMISSIONS
4532 // =========================================================
4533
4534 static class PermissionController extends IPermissionController.Stub {
4535 ActivityManagerService mActivityManagerService;
4536 PermissionController(ActivityManagerService activityManagerService) {
4537 mActivityManagerService = activityManagerService;
4538 }
4539
4540 public boolean checkPermission(String permission, int pid, int uid) {
4541 return mActivityManagerService.checkPermission(permission, pid,
4542 uid) == PackageManager.PERMISSION_GRANTED;
4543 }
4544 }
4545
4546 /**
4547 * This can be called with or without the global lock held.
4548 */
4549 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004550 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 // We might be performing an operation on behalf of an indirect binder
4552 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4553 // client identity accordingly before proceeding.
4554 Identity tlsIdentity = sCallerIdentity.get();
4555 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004556 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004557 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4558 uid = tlsIdentity.uid;
4559 pid = tlsIdentity.pid;
4560 }
4561
4562 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004563 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004564 return PackageManager.PERMISSION_GRANTED;
4565 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004566 // Isolated processes don't get any permissions.
4567 if (UserId.isIsolated(uid)) {
4568 return PackageManager.PERMISSION_DENIED;
4569 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004570 // If there is a uid that owns whatever is being accessed, it has
4571 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004572 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004573 return PackageManager.PERMISSION_GRANTED;
4574 }
4575 // If the target is not exported, then nobody else can get to it.
4576 if (!exported) {
4577 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004578 return PackageManager.PERMISSION_DENIED;
4579 }
4580 if (permission == null) {
4581 return PackageManager.PERMISSION_GRANTED;
4582 }
4583 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004584 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004585 .checkUidPermission(permission, uid);
4586 } catch (RemoteException e) {
4587 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004588 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004589 }
4590 return PackageManager.PERMISSION_DENIED;
4591 }
4592
4593 /**
4594 * As the only public entry point for permissions checking, this method
4595 * can enforce the semantic that requesting a check on a null global
4596 * permission is automatically denied. (Internally a null permission
4597 * string is used when calling {@link #checkComponentPermission} in cases
4598 * when only uid-based security is needed.)
4599 *
4600 * This can be called with or without the global lock held.
4601 */
4602 public int checkPermission(String permission, int pid, int uid) {
4603 if (permission == null) {
4604 return PackageManager.PERMISSION_DENIED;
4605 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004606 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 }
4608
4609 /**
4610 * Binder IPC calls go through the public entry point.
4611 * This can be called with or without the global lock held.
4612 */
4613 int checkCallingPermission(String permission) {
4614 return checkPermission(permission,
4615 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004616 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617 }
4618
4619 /**
4620 * This can be called with or without the global lock held.
4621 */
4622 void enforceCallingPermission(String permission, String func) {
4623 if (checkCallingPermission(permission)
4624 == PackageManager.PERMISSION_GRANTED) {
4625 return;
4626 }
4627
4628 String msg = "Permission Denial: " + func + " from pid="
4629 + Binder.getCallingPid()
4630 + ", uid=" + Binder.getCallingUid()
4631 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004632 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004633 throw new SecurityException(msg);
4634 }
4635
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004636 /**
4637 * Determine if UID is holding permissions required to access {@link Uri} in
4638 * the given {@link ProviderInfo}. Final permission checking is always done
4639 * in {@link ContentProvider}.
4640 */
4641 private final boolean checkHoldingPermissionsLocked(
4642 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004643 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4644 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004645
4646 if (pi.applicationInfo.uid == uid) {
4647 return true;
4648 } else if (!pi.exported) {
4649 return false;
4650 }
4651
4652 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4653 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004655 // check if target holds top-level <provider> permissions
4656 if (!readMet && pi.readPermission != null
4657 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4658 readMet = true;
4659 }
4660 if (!writeMet && pi.writePermission != null
4661 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4662 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004663 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004664
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004665 // track if unprotected read/write is allowed; any denied
4666 // <path-permission> below removes this ability
4667 boolean allowDefaultRead = pi.readPermission == null;
4668 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004669
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004670 // check if target holds any <path-permission> that match uri
4671 final PathPermission[] pps = pi.pathPermissions;
4672 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004673 final String path = uri.getPath();
4674 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004675 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004676 i--;
4677 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004678 if (pp.match(path)) {
4679 if (!readMet) {
4680 final String pprperm = pp.getReadPermission();
4681 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4682 + pprperm + " for " + pp.getPath()
4683 + ": match=" + pp.match(path)
4684 + " check=" + pm.checkUidPermission(pprperm, uid));
4685 if (pprperm != null) {
4686 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4687 readMet = true;
4688 } else {
4689 allowDefaultRead = false;
4690 }
4691 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004692 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004693 if (!writeMet) {
4694 final String ppwperm = pp.getWritePermission();
4695 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4696 + ppwperm + " for " + pp.getPath()
4697 + ": match=" + pp.match(path)
4698 + " check=" + pm.checkUidPermission(ppwperm, uid));
4699 if (ppwperm != null) {
4700 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4701 writeMet = true;
4702 } else {
4703 allowDefaultWrite = false;
4704 }
4705 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004706 }
4707 }
4708 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004709 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004710
4711 // grant unprotected <provider> read/write, if not blocked by
4712 // <path-permission> above
4713 if (allowDefaultRead) readMet = true;
4714 if (allowDefaultWrite) writeMet = true;
4715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004716 } catch (RemoteException e) {
4717 return false;
4718 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004719
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004720 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004721 }
4722
4723 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4724 int modeFlags) {
4725 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004726 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004727 return true;
4728 }
4729 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4730 if (perms == null) return false;
4731 UriPermission perm = perms.get(uri);
4732 if (perm == null) return false;
4733 return (modeFlags&perm.modeFlags) == modeFlags;
4734 }
4735
4736 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004737 enforceNotIsolatedCaller("checkUriPermission");
4738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004739 // Another redirected-binder-call permissions check as in
4740 // {@link checkComponentPermission}.
4741 Identity tlsIdentity = sCallerIdentity.get();
4742 if (tlsIdentity != null) {
4743 uid = tlsIdentity.uid;
4744 pid = tlsIdentity.pid;
4745 }
4746
Amith Yamasani742a6712011-05-04 14:49:28 -07004747 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 // Our own process gets to do everything.
4749 if (pid == MY_PID) {
4750 return PackageManager.PERMISSION_GRANTED;
4751 }
4752 synchronized(this) {
4753 return checkUriPermissionLocked(uri, uid, modeFlags)
4754 ? PackageManager.PERMISSION_GRANTED
4755 : PackageManager.PERMISSION_DENIED;
4756 }
4757 }
4758
Dianne Hackborn39792d22010-08-19 18:01:52 -07004759 /**
4760 * Check if the targetPkg can be granted permission to access uri by
4761 * the callingUid using the given modeFlags. Throws a security exception
4762 * if callingUid is not allowed to do this. Returns the uid of the target
4763 * if the URI permission grant should be performed; returns -1 if it is not
4764 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004765 * If you already know the uid of the target, you can supply it in
4766 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004767 */
4768 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004769 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004770 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4771 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4772 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004773 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004774 }
4775
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004776 if (targetPkg != null) {
4777 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4778 "Checking grant " + targetPkg + " permission to " + uri);
4779 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004780
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004781 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004782
4783 // If this is not a content: uri, we can't do anything with it.
4784 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004785 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004786 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004787 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004788 }
4789
4790 String name = uri.getAuthority();
4791 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004792 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4793 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004794 if (cpr != null) {
4795 pi = cpr.info;
4796 } else {
4797 try {
4798 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004799 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004800 } catch (RemoteException ex) {
4801 }
4802 }
4803 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004804 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004805 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004806 }
4807
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004808 int targetUid = lastTargetUid;
4809 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004810 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004811 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004812 if (targetUid < 0) {
4813 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4814 "Can't grant URI permission no uid for: " + targetPkg);
4815 return -1;
4816 }
4817 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004818 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004820 }
4821
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004822 if (targetUid >= 0) {
4823 // First... does the target actually need this permission?
4824 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4825 // No need to grant the target this permission.
4826 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4827 "Target " + targetPkg + " already has full permission to " + uri);
4828 return -1;
4829 }
4830 } else {
4831 // First... there is no target package, so can anyone access it?
4832 boolean allowed = pi.exported;
4833 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4834 if (pi.readPermission != null) {
4835 allowed = false;
4836 }
4837 }
4838 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4839 if (pi.writePermission != null) {
4840 allowed = false;
4841 }
4842 }
4843 if (allowed) {
4844 return -1;
4845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004846 }
4847
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004848 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004849 if (!pi.grantUriPermissions) {
4850 throw new SecurityException("Provider " + pi.packageName
4851 + "/" + pi.name
4852 + " does not allow granting of Uri permissions (uri "
4853 + uri + ")");
4854 }
4855 if (pi.uriPermissionPatterns != null) {
4856 final int N = pi.uriPermissionPatterns.length;
4857 boolean allowed = false;
4858 for (int i=0; i<N; i++) {
4859 if (pi.uriPermissionPatterns[i] != null
4860 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4861 allowed = true;
4862 break;
4863 }
4864 }
4865 if (!allowed) {
4866 throw new SecurityException("Provider " + pi.packageName
4867 + "/" + pi.name
4868 + " does not allow granting of permission to path of Uri "
4869 + uri);
4870 }
4871 }
4872
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004873 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004874 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004875 if (callingUid != Process.myUid()) {
4876 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4877 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4878 throw new SecurityException("Uid " + callingUid
4879 + " does not have permission to uri " + uri);
4880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004881 }
4882 }
4883
Dianne Hackborn39792d22010-08-19 18:01:52 -07004884 return targetUid;
4885 }
4886
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004887 public int checkGrantUriPermission(int callingUid, String targetPkg,
4888 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004889 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004890 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004891 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004892 }
4893 }
4894
Dianne Hackborn39792d22010-08-19 18:01:52 -07004895 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4896 Uri uri, int modeFlags, UriPermissionOwner owner) {
4897 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4898 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4899 if (modeFlags == 0) {
4900 return;
4901 }
4902
4903 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004904 // to the uri, and the target doesn't. Let's now give this to
4905 // the target.
4906
Joe Onorato8a9b2202010-02-26 18:56:32 -08004907 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004908 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004910 HashMap<Uri, UriPermission> targetUris
4911 = mGrantedUriPermissions.get(targetUid);
4912 if (targetUris == null) {
4913 targetUris = new HashMap<Uri, UriPermission>();
4914 mGrantedUriPermissions.put(targetUid, targetUris);
4915 }
4916
4917 UriPermission perm = targetUris.get(uri);
4918 if (perm == null) {
4919 perm = new UriPermission(targetUid, uri);
4920 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004921 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004923 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004924 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004926 } else {
4927 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4928 perm.readOwners.add(owner);
4929 owner.addReadPermission(perm);
4930 }
4931 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4932 perm.writeOwners.add(owner);
4933 owner.addWritePermission(perm);
4934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004935 }
4936 }
4937
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004938 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4939 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004940 if (targetPkg == null) {
4941 throw new NullPointerException("targetPkg");
4942 }
4943
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004944 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004945 if (targetUid < 0) {
4946 return;
4947 }
4948
4949 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4950 }
4951
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004952 static class NeededUriGrants extends ArrayList<Uri> {
4953 final String targetPkg;
4954 final int targetUid;
4955 final int flags;
4956
4957 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4958 targetPkg = _targetPkg;
4959 targetUid = _targetUid;
4960 flags = _flags;
4961 }
4962 }
4963
Dianne Hackborn39792d22010-08-19 18:01:52 -07004964 /**
4965 * Like checkGrantUriPermissionLocked, but takes an Intent.
4966 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004967 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
4968 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004969 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004970 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
4971 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004972 + " from " + intent + "; flags=0x"
4973 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4974
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004975 if (targetPkg == null) {
4976 throw new NullPointerException("targetPkg");
4977 }
4978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004979 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004980 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004981 }
4982 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004983 ClipData clip = intent.getClipData();
4984 if (data == null && clip == null) {
4985 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004986 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004987 if (data != null) {
4988 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4989 mode, needed != null ? needed.targetUid : -1);
4990 if (target > 0) {
4991 if (needed == null) {
4992 needed = new NeededUriGrants(targetPkg, target, mode);
4993 }
4994 needed.add(data);
4995 }
4996 }
4997 if (clip != null) {
4998 for (int i=0; i<clip.getItemCount(); i++) {
4999 Uri uri = clip.getItemAt(i).getUri();
5000 if (uri != null) {
5001 int target = -1;
5002 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5003 mode, needed != null ? needed.targetUid : -1);
5004 if (target > 0) {
5005 if (needed == null) {
5006 needed = new NeededUriGrants(targetPkg, target, mode);
5007 }
5008 needed.add(uri);
5009 }
5010 } else {
5011 Intent clipIntent = clip.getItemAt(i).getIntent();
5012 if (clipIntent != null) {
5013 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5014 callingUid, targetPkg, clipIntent, mode, needed);
5015 if (newNeeded != null) {
5016 needed = newNeeded;
5017 }
5018 }
5019 }
5020 }
5021 }
5022
5023 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005024 }
5025
5026 /**
5027 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5028 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005029 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5030 UriPermissionOwner owner) {
5031 if (needed != null) {
5032 for (int i=0; i<needed.size(); i++) {
5033 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5034 needed.get(i), needed.flags, owner);
5035 }
5036 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005037 }
5038
5039 void grantUriPermissionFromIntentLocked(int callingUid,
5040 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005041 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005042 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005043 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005044 return;
5045 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005046
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005047 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005048 }
5049
5050 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5051 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005052 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005053 synchronized(this) {
5054 final ProcessRecord r = getRecordForAppLocked(caller);
5055 if (r == null) {
5056 throw new SecurityException("Unable to find app for caller "
5057 + caller
5058 + " when granting permission to uri " + uri);
5059 }
5060 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005061 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 }
5063 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005064 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 }
5066
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005067 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005068 null);
5069 }
5070 }
5071
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005072 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005073 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5074 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5075 HashMap<Uri, UriPermission> perms
5076 = mGrantedUriPermissions.get(perm.uid);
5077 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005078 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005079 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 perms.remove(perm.uri);
5081 if (perms.size() == 0) {
5082 mGrantedUriPermissions.remove(perm.uid);
5083 }
5084 }
5085 }
5086 }
5087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5089 int modeFlags) {
5090 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5091 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5092 if (modeFlags == 0) {
5093 return;
5094 }
5095
Joe Onorato8a9b2202010-02-26 18:56:32 -08005096 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005097 "Revoking all granted permissions to " + uri);
5098
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005099 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005100
5101 final String authority = uri.getAuthority();
5102 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005103 int userId = UserId.getUserId(callingUid);
5104 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005105 if (cpr != null) {
5106 pi = cpr.info;
5107 } else {
5108 try {
5109 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005110 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 } catch (RemoteException ex) {
5112 }
5113 }
5114 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005115 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 return;
5117 }
5118
5119 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005120 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005121 // Right now, if you are not the original owner of the permission,
5122 // you are not allowed to revoke it.
5123 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5124 throw new SecurityException("Uid " + callingUid
5125 + " does not have permission to uri " + uri);
5126 //}
5127 }
5128
5129 // Go through all of the permissions and remove any that match.
5130 final List<String> SEGMENTS = uri.getPathSegments();
5131 if (SEGMENTS != null) {
5132 final int NS = SEGMENTS.size();
5133 int N = mGrantedUriPermissions.size();
5134 for (int i=0; i<N; i++) {
5135 HashMap<Uri, UriPermission> perms
5136 = mGrantedUriPermissions.valueAt(i);
5137 Iterator<UriPermission> it = perms.values().iterator();
5138 toploop:
5139 while (it.hasNext()) {
5140 UriPermission perm = it.next();
5141 Uri targetUri = perm.uri;
5142 if (!authority.equals(targetUri.getAuthority())) {
5143 continue;
5144 }
5145 List<String> targetSegments = targetUri.getPathSegments();
5146 if (targetSegments == null) {
5147 continue;
5148 }
5149 if (targetSegments.size() < NS) {
5150 continue;
5151 }
5152 for (int j=0; j<NS; j++) {
5153 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5154 continue toploop;
5155 }
5156 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005157 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005158 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005159 perm.clearModes(modeFlags);
5160 if (perm.modeFlags == 0) {
5161 it.remove();
5162 }
5163 }
5164 if (perms.size() == 0) {
5165 mGrantedUriPermissions.remove(
5166 mGrantedUriPermissions.keyAt(i));
5167 N--;
5168 i--;
5169 }
5170 }
5171 }
5172 }
5173
5174 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5175 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005176 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005177 synchronized(this) {
5178 final ProcessRecord r = getRecordForAppLocked(caller);
5179 if (r == null) {
5180 throw new SecurityException("Unable to find app for caller "
5181 + caller
5182 + " when revoking permission to uri " + uri);
5183 }
5184 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005185 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 return;
5187 }
5188
5189 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5190 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5191 if (modeFlags == 0) {
5192 return;
5193 }
5194
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005195 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196
5197 final String authority = uri.getAuthority();
5198 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005199 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 if (cpr != null) {
5201 pi = cpr.info;
5202 } else {
5203 try {
5204 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005205 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005206 } catch (RemoteException ex) {
5207 }
5208 }
5209 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005210 Slog.w(TAG, "No content provider found for permission revoke: "
5211 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005212 return;
5213 }
5214
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005215 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005216 }
5217 }
5218
Dianne Hackborn7e269642010-08-25 19:50:20 -07005219 @Override
5220 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005221 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005222 synchronized(this) {
5223 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5224 return owner.getExternalTokenLocked();
5225 }
5226 }
5227
5228 @Override
5229 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5230 Uri uri, int modeFlags) {
5231 synchronized(this) {
5232 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5233 if (owner == null) {
5234 throw new IllegalArgumentException("Unknown owner: " + token);
5235 }
5236 if (fromUid != Binder.getCallingUid()) {
5237 if (Binder.getCallingUid() != Process.myUid()) {
5238 // Only system code can grant URI permissions on behalf
5239 // of other users.
5240 throw new SecurityException("nice try");
5241 }
5242 }
5243 if (targetPkg == null) {
5244 throw new IllegalArgumentException("null target");
5245 }
5246 if (uri == null) {
5247 throw new IllegalArgumentException("null uri");
5248 }
5249
5250 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5251 }
5252 }
5253
5254 @Override
5255 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5256 synchronized(this) {
5257 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5258 if (owner == null) {
5259 throw new IllegalArgumentException("Unknown owner: " + token);
5260 }
5261
5262 if (uri == null) {
5263 owner.removeUriPermissionsLocked(mode);
5264 } else {
5265 owner.removeUriPermissionLocked(uri, mode);
5266 }
5267 }
5268 }
5269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5271 synchronized (this) {
5272 ProcessRecord app =
5273 who != null ? getRecordForAppLocked(who) : null;
5274 if (app == null) return;
5275
5276 Message msg = Message.obtain();
5277 msg.what = WAIT_FOR_DEBUGGER_MSG;
5278 msg.obj = app;
5279 msg.arg1 = waiting ? 1 : 0;
5280 mHandler.sendMessage(msg);
5281 }
5282 }
5283
5284 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005285 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5286 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005288 outInfo.threshold = homeAppMem;
5289 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5290 outInfo.hiddenAppThreshold = hiddenAppMem;
5291 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005292 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005293 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5294 ProcessList.VISIBLE_APP_ADJ);
5295 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5296 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005297 }
5298
5299 // =========================================================
5300 // TASK MANAGEMENT
5301 // =========================================================
5302
5303 public List getTasks(int maxNum, int flags,
5304 IThumbnailReceiver receiver) {
5305 ArrayList list = new ArrayList();
5306
5307 PendingThumbnailsRecord pending = null;
5308 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005309 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005310
5311 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005312 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005313 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5314 + ", receiver=" + receiver);
5315
5316 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5317 != PackageManager.PERMISSION_GRANTED) {
5318 if (receiver != null) {
5319 // If the caller wants to wait for pending thumbnails,
5320 // it ain't gonna get them.
5321 try {
5322 receiver.finished();
5323 } catch (RemoteException ex) {
5324 }
5325 }
5326 String msg = "Permission Denial: getTasks() from pid="
5327 + Binder.getCallingPid()
5328 + ", uid=" + Binder.getCallingUid()
5329 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005330 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 throw new SecurityException(msg);
5332 }
5333
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005334 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005335 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005336 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005337 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005338 TaskRecord curTask = null;
5339 int numActivities = 0;
5340 int numRunning = 0;
5341 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005342 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005343 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005344 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345
5346 // Initialize state for next task if needed.
5347 if (top == null ||
5348 (top.state == ActivityState.INITIALIZING
5349 && top.task == r.task)) {
5350 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005351 curTask = r.task;
5352 numActivities = numRunning = 0;
5353 }
5354
5355 // Add 'r' into the current task.
5356 numActivities++;
5357 if (r.app != null && r.app.thread != null) {
5358 numRunning++;
5359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005360
Joe Onorato8a9b2202010-02-26 18:56:32 -08005361 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 TAG, r.intent.getComponent().flattenToShortString()
5363 + ": task=" + r.task);
5364
5365 // If the next one is a different task, generate a new
5366 // TaskInfo entry for what we have.
5367 if (next == null || next.task != curTask) {
5368 ActivityManager.RunningTaskInfo ci
5369 = new ActivityManager.RunningTaskInfo();
5370 ci.id = curTask.taskId;
5371 ci.baseActivity = r.intent.getComponent();
5372 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005373 if (top.thumbHolder != null) {
5374 ci.description = top.thumbHolder.lastDescription;
5375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005376 ci.numActivities = numActivities;
5377 ci.numRunning = numRunning;
5378 //System.out.println(
5379 // "#" + maxNum + ": " + " descr=" + ci.description);
5380 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005381 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005382 TAG, "State=" + top.state + "Idle=" + top.idle
5383 + " app=" + top.app
5384 + " thr=" + (top.app != null ? top.app.thread : null));
5385 if (top.state == ActivityState.RESUMED
5386 || top.state == ActivityState.PAUSING) {
5387 if (top.idle && top.app != null
5388 && top.app.thread != null) {
5389 topRecord = top;
5390 topThumbnail = top.app.thread;
5391 } else {
5392 top.thumbnailNeeded = true;
5393 }
5394 }
5395 if (pending == null) {
5396 pending = new PendingThumbnailsRecord(receiver);
5397 }
5398 pending.pendingRecords.add(top);
5399 }
5400 list.add(ci);
5401 maxNum--;
5402 top = null;
5403 }
5404 }
5405
5406 if (pending != null) {
5407 mPendingThumbnails.add(pending);
5408 }
5409 }
5410
Joe Onorato8a9b2202010-02-26 18:56:32 -08005411 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005412
5413 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005414 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005416 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005417 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005418 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005419 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 }
5421 }
5422
5423 if (pending == null && receiver != null) {
5424 // In this case all thumbnails were available and the client
5425 // is being asked to be told when the remaining ones come in...
5426 // which is unusually, since the top-most currently running
5427 // activity should never have a canned thumbnail! Oh well.
5428 try {
5429 receiver.finished();
5430 } catch (RemoteException ex) {
5431 }
5432 }
5433
5434 return list;
5435 }
5436
5437 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5438 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005439 final int callingUid = Binder.getCallingUid();
5440 // If it's the system uid asking, then use the current user id.
5441 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5442 // require the entire list.
5443 final int callingUserId = callingUid == Process.SYSTEM_UID
5444 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 synchronized (this) {
5446 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5447 "getRecentTasks()");
5448
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005449 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 final int N = mRecentTasks.size();
5452 ArrayList<ActivityManager.RecentTaskInfo> res
5453 = new ArrayList<ActivityManager.RecentTaskInfo>(
5454 maxNum < N ? maxNum : N);
5455 for (int i=0; i<N && maxNum > 0; i++) {
5456 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005457 // Only add calling user's recent tasks
5458 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005459 // Return the entry if desired by the caller. We always return
5460 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005461 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005462 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5463 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005464
Dianne Hackborn905577f2011-09-07 18:31:28 -07005465 if (i == 0
5466 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005467 || (tr.intent == null)
5468 || ((tr.intent.getFlags()
5469 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5470 ActivityManager.RecentTaskInfo rti
5471 = new ActivityManager.RecentTaskInfo();
5472 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005473 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 rti.baseIntent = new Intent(
5475 tr.intent != null ? tr.intent : tr.affinityIntent);
5476 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005477 rti.description = tr.lastDescription;
5478
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005479 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5480 // Check whether this activity is currently available.
5481 try {
5482 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005483 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5484 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005485 continue;
5486 }
5487 } else if (rti.baseIntent != null) {
5488 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005489 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005490 continue;
5491 }
5492 }
5493 } catch (RemoteException e) {
5494 // Will never happen.
5495 }
5496 }
5497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 res.add(rti);
5499 maxNum--;
5500 }
5501 }
5502 return res;
5503 }
5504 }
5505
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005506 private TaskRecord taskForIdLocked(int id) {
5507 final int N = mRecentTasks.size();
5508 for (int i=0; i<N; i++) {
5509 TaskRecord tr = mRecentTasks.get(i);
5510 if (tr.taskId == id) {
5511 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005512 }
5513 }
5514 return null;
5515 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005516
5517 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5518 synchronized (this) {
5519 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5520 "getTaskThumbnails()");
5521 TaskRecord tr = taskForIdLocked(id);
5522 if (tr != null) {
5523 return mMainStack.getTaskThumbnailsLocked(tr);
5524 }
5525 }
5526 return null;
5527 }
5528
5529 public boolean removeSubTask(int taskId, int subTaskIndex) {
5530 synchronized (this) {
5531 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5532 "removeSubTask()");
5533 long ident = Binder.clearCallingIdentity();
5534 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005535 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5536 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005537 } finally {
5538 Binder.restoreCallingIdentity(ident);
5539 }
5540 }
5541 }
5542
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005543 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5544 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005545 Intent baseIntent = new Intent(
5546 tr.intent != null ? tr.intent : tr.affinityIntent);
5547 ComponentName component = baseIntent.getComponent();
5548 if (component == null) {
5549 Slog.w(TAG, "Now component for base intent of task: " + tr);
5550 return;
5551 }
5552
5553 // Find any running services associated with this app.
5554 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005555 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005556 if (sr.packageName.equals(component.getPackageName())) {
5557 services.add(sr);
5558 }
5559 }
5560
5561 // Take care of any running services associated with the app.
5562 for (int i=0; i<services.size(); i++) {
5563 ServiceRecord sr = services.get(i);
5564 if (sr.startRequested) {
5565 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005566 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005567 stopServiceLocked(sr);
5568 } else {
5569 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005570 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005571 if (sr.app != null && sr.app.thread != null) {
5572 sendServiceArgsLocked(sr, false);
5573 }
5574 }
5575 }
5576 }
5577
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005578 if (killProcesses) {
5579 // Find any running processes associated with this app.
5580 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5581 SparseArray<ProcessRecord> appProcs
5582 = mProcessNames.getMap().get(component.getPackageName());
5583 if (appProcs != null) {
5584 for (int i=0; i<appProcs.size(); i++) {
5585 procs.add(appProcs.valueAt(i));
5586 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005587 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005588
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005589 // Kill the running processes.
5590 for (int i=0; i<procs.size(); i++) {
5591 ProcessRecord pr = procs.get(i);
5592 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5593 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5594 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5595 pr.processName, pr.setAdj, "remove task");
5596 Process.killProcessQuiet(pr.pid);
5597 } else {
5598 pr.waitingToKill = "remove task";
5599 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005600 }
5601 }
5602 }
5603
5604 public boolean removeTask(int taskId, int flags) {
5605 synchronized (this) {
5606 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5607 "removeTask()");
5608 long ident = Binder.clearCallingIdentity();
5609 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005610 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5611 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005612 if (r != null) {
5613 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005614 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005615 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005616 } else {
5617 TaskRecord tr = null;
5618 int i=0;
5619 while (i < mRecentTasks.size()) {
5620 TaskRecord t = mRecentTasks.get(i);
5621 if (t.taskId == taskId) {
5622 tr = t;
5623 break;
5624 }
5625 i++;
5626 }
5627 if (tr != null) {
5628 if (tr.numActivities <= 0) {
5629 // Caller is just removing a recent task that is
5630 // not actively running. That is easy!
5631 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005632 cleanUpRemovedTaskLocked(tr, flags);
5633 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005634 } else {
5635 Slog.w(TAG, "removeTask: task " + taskId
5636 + " does not have activities to remove, "
5637 + " but numActivities=" + tr.numActivities
5638 + ": " + tr);
5639 }
5640 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005641 }
5642 } finally {
5643 Binder.restoreCallingIdentity(ident);
5644 }
5645 }
5646 return false;
5647 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5650 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005651 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005652 TaskRecord jt = startTask;
5653
5654 // First look backwards
5655 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005656 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 if (r.task != jt) {
5658 jt = r.task;
5659 if (affinity.equals(jt.affinity)) {
5660 return j;
5661 }
5662 }
5663 }
5664
5665 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005666 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 jt = startTask;
5668 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005669 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 if (r.task != jt) {
5671 if (affinity.equals(jt.affinity)) {
5672 return j;
5673 }
5674 jt = r.task;
5675 }
5676 }
5677
5678 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005679 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 return N-1;
5681 }
5682
5683 return -1;
5684 }
5685
5686 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005687 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005689 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005690 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5691 "moveTaskToFront()");
5692
5693 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005694 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5695 Binder.getCallingUid(), "Task to front")) {
5696 return;
5697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005698 final long origId = Binder.clearCallingIdentity();
5699 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005700 TaskRecord tr = taskForIdLocked(task);
5701 if (tr != null) {
5702 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5703 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005704 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005705 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5706 // Caller wants the home activity moved with it. To accomplish this,
5707 // we'll just move the home task to the top first.
5708 mMainStack.moveHomeToFrontLocked();
5709 }
5710 mMainStack.moveTaskToFrontLocked(tr, null);
5711 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005712 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005713 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5714 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005716 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5717 mMainStack.mUserLeaving = true;
5718 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005719 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5720 // Caller wants the home activity moved with it. To accomplish this,
5721 // we'll just move the home task to the top first.
5722 mMainStack.moveHomeToFrontLocked();
5723 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005724 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 return;
5726 }
5727 }
5728 } finally {
5729 Binder.restoreCallingIdentity(origId);
5730 }
5731 }
5732 }
5733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 public void moveTaskToBack(int task) {
5735 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5736 "moveTaskToBack()");
5737
5738 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005739 if (mMainStack.mResumedActivity != null
5740 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005741 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5742 Binder.getCallingUid(), "Task to back")) {
5743 return;
5744 }
5745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005746 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005747 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 Binder.restoreCallingIdentity(origId);
5749 }
5750 }
5751
5752 /**
5753 * Moves an activity, and all of the other activities within the same task, to the bottom
5754 * of the history stack. The activity's order within the task is unchanged.
5755 *
5756 * @param token A reference to the activity we wish to move
5757 * @param nonRoot If false then this only works if the activity is the root
5758 * of a task; if true it will work for any activity in a task.
5759 * @return Returns true if the move completed, false if not.
5760 */
5761 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005762 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 synchronized(this) {
5764 final long origId = Binder.clearCallingIdentity();
5765 int taskId = getTaskForActivityLocked(token, !nonRoot);
5766 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005767 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 }
5769 Binder.restoreCallingIdentity(origId);
5770 }
5771 return false;
5772 }
5773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774 public void moveTaskBackwards(int task) {
5775 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5776 "moveTaskBackwards()");
5777
5778 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005779 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5780 Binder.getCallingUid(), "Task backwards")) {
5781 return;
5782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 final long origId = Binder.clearCallingIdentity();
5784 moveTaskBackwardsLocked(task);
5785 Binder.restoreCallingIdentity(origId);
5786 }
5787 }
5788
5789 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005790 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 }
5792
5793 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5794 synchronized(this) {
5795 return getTaskForActivityLocked(token, onlyRoot);
5796 }
5797 }
5798
5799 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005800 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801 TaskRecord lastTask = null;
5802 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005803 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005804 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005805 if (!onlyRoot || lastTask != r.task) {
5806 return r.task.taskId;
5807 }
5808 return -1;
5809 }
5810 lastTask = r.task;
5811 }
5812
5813 return -1;
5814 }
5815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 // =========================================================
5817 // THUMBNAILS
5818 // =========================================================
5819
5820 public void reportThumbnail(IBinder token,
5821 Bitmap thumbnail, CharSequence description) {
5822 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5823 final long origId = Binder.clearCallingIdentity();
5824 sendPendingThumbnail(null, token, thumbnail, description, true);
5825 Binder.restoreCallingIdentity(origId);
5826 }
5827
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005828 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 Bitmap thumbnail, CharSequence description, boolean always) {
5830 TaskRecord task = null;
5831 ArrayList receivers = null;
5832
5833 //System.out.println("Send pending thumbnail: " + r);
5834
5835 synchronized(this) {
5836 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005837 r = mMainStack.isInStackLocked(token);
5838 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 return;
5840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005842 if (thumbnail == null && r.thumbHolder != null) {
5843 thumbnail = r.thumbHolder.lastThumbnail;
5844 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 }
5846 if (thumbnail == null && !always) {
5847 // If there is no thumbnail, and this entry is not actually
5848 // going away, then abort for now and pick up the next
5849 // thumbnail we get.
5850 return;
5851 }
5852 task = r.task;
5853
5854 int N = mPendingThumbnails.size();
5855 int i=0;
5856 while (i<N) {
5857 PendingThumbnailsRecord pr =
5858 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5859 //System.out.println("Looking in " + pr.pendingRecords);
5860 if (pr.pendingRecords.remove(r)) {
5861 if (receivers == null) {
5862 receivers = new ArrayList();
5863 }
5864 receivers.add(pr);
5865 if (pr.pendingRecords.size() == 0) {
5866 pr.finished = true;
5867 mPendingThumbnails.remove(i);
5868 N--;
5869 continue;
5870 }
5871 }
5872 i++;
5873 }
5874 }
5875
5876 if (receivers != null) {
5877 final int N = receivers.size();
5878 for (int i=0; i<N; i++) {
5879 try {
5880 PendingThumbnailsRecord pr =
5881 (PendingThumbnailsRecord)receivers.get(i);
5882 pr.receiver.newThumbnail(
5883 task != null ? task.taskId : -1, thumbnail, description);
5884 if (pr.finished) {
5885 pr.receiver.finished();
5886 }
5887 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005888 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 }
5890 }
5891 }
5892 }
5893
5894 // =========================================================
5895 // CONTENT PROVIDERS
5896 // =========================================================
5897
Jeff Brown10e89712011-07-08 18:52:57 -07005898 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5899 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005901 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005902 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005903 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005904 } catch (RemoteException ex) {
5905 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005906 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005907 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5908 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 if (providers != null) {
5910 final int N = providers.size();
5911 for (int i=0; i<N; i++) {
5912 ProviderInfo cpi =
5913 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005914
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005915 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005916 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005918 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005919 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005920 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005921 if (DEBUG_MU)
5922 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 app.pubProviders.put(cpi.name, cpr);
5924 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005925 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005926 }
5927 }
5928 return providers;
5929 }
5930
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005931 /**
5932 * Check if {@link ProcessRecord} has a possible chance at accessing the
5933 * given {@link ProviderInfo}. Final permission checking is always done
5934 * in {@link ContentProvider}.
5935 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005936 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005937 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005938 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005939 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005941 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005942 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 return null;
5944 }
5945 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005946 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 == PackageManager.PERMISSION_GRANTED) {
5948 return null;
5949 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005950
5951 PathPermission[] pps = cpi.pathPermissions;
5952 if (pps != null) {
5953 int i = pps.length;
5954 while (i > 0) {
5955 i--;
5956 PathPermission pp = pps[i];
5957 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005958 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005959 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005960 return null;
5961 }
5962 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005963 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005964 == PackageManager.PERMISSION_GRANTED) {
5965 return null;
5966 }
5967 }
5968 }
5969
Dianne Hackbornb424b632010-08-18 15:59:05 -07005970 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5971 if (perms != null) {
5972 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5973 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5974 return null;
5975 }
5976 }
5977 }
5978
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005979 String msg;
5980 if (!cpi.exported) {
5981 msg = "Permission Denial: opening provider " + cpi.name
5982 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5983 + ", uid=" + callingUid + ") that is not exported from uid "
5984 + cpi.applicationInfo.uid;
5985 } else {
5986 msg = "Permission Denial: opening provider " + cpi.name
5987 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5988 + ", uid=" + callingUid + ") requires "
5989 + cpi.readPermission + " or " + cpi.writePermission;
5990 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005991 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005992 return msg;
5993 }
5994
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005995 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5996 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005997 if (r != null) {
5998 Integer cnt = r.conProviders.get(cpr);
5999 if (DEBUG_PROVIDER) Slog.v(TAG,
6000 "Adding provider requested by "
6001 + r.processName + " from process "
6002 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6003 + " cnt=" + (cnt == null ? 1 : cnt));
6004 if (cnt == null) {
6005 cpr.clients.add(r);
6006 r.conProviders.put(cpr, new Integer(1));
6007 return true;
6008 } else {
6009 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6010 }
6011 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006012 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006013 }
6014 return false;
6015 }
6016
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006017 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6018 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006019 if (r != null) {
6020 Integer cnt = r.conProviders.get(cpr);
6021 if (DEBUG_PROVIDER) Slog.v(TAG,
6022 "Removing provider requested by "
6023 + r.processName + " from process "
6024 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6025 + " cnt=" + cnt);
6026 if (cnt == null || cnt.intValue() <= 1) {
6027 cpr.clients.remove(r);
6028 r.conProviders.remove(cpr);
6029 return true;
6030 } else {
6031 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6032 }
6033 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006034 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006035 }
6036 return false;
6037 }
6038
Amith Yamasani742a6712011-05-04 14:49:28 -07006039 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006040 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 ContentProviderRecord cpr;
6042 ProviderInfo cpi = null;
6043
6044 synchronized(this) {
6045 ProcessRecord r = null;
6046 if (caller != null) {
6047 r = getRecordForAppLocked(caller);
6048 if (r == null) {
6049 throw new SecurityException(
6050 "Unable to find app for caller " + caller
6051 + " (pid=" + Binder.getCallingPid()
6052 + ") when getting content provider " + name);
6053 }
6054 }
6055
6056 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006057 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006058 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006059 boolean providerRunning = cpr != null;
6060 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006062 String msg;
6063 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6064 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006065 }
6066
6067 if (r != null && cpr.canRunHere(r)) {
6068 // This provider has been published or is in the process
6069 // of being published... but it is also allowed to run
6070 // in the caller's process, so don't make a connection
6071 // and just let the caller instantiate its own instance.
6072 if (cpr.provider != null) {
6073 // don't give caller the provider object, it needs
6074 // to make its own.
6075 cpr = new ContentProviderRecord(cpr);
6076 }
6077 return cpr;
6078 }
6079
6080 final long origId = Binder.clearCallingIdentity();
6081
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006082 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006084 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006085 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006086 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006087 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006088 // make sure to count it as being accessed and thus
6089 // back up on the LRU list. This is good because
6090 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006091 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006092 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006093 }
6094
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006095 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006096 if (false) {
6097 if (cpr.name.flattenToShortString().equals(
6098 "com.android.providers.calendar/.CalendarProvider2")) {
6099 Slog.v(TAG, "****************** KILLING "
6100 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006101 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006102 }
6103 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006104 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006105 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6106 // NOTE: there is still a race here where a signal could be
6107 // pending on the process even though we managed to update its
6108 // adj level. Not sure what to do about this, but at least
6109 // the race is now smaller.
6110 if (!success) {
6111 // Uh oh... it looks like the provider's process
6112 // has been killed on us. We need to wait for a new
6113 // process to be started, and make sure its death
6114 // doesn't kill our process.
6115 Slog.i(TAG,
6116 "Existing provider " + cpr.name.flattenToShortString()
6117 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006118 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006119 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006120 if (!lastRef) {
6121 // This wasn't the last ref our process had on
6122 // the provider... we have now been killed, bail.
6123 return null;
6124 }
6125 providerRunning = false;
6126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 }
6128
6129 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006132 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006134 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006135 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006136 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 } catch (RemoteException ex) {
6138 }
6139 if (cpi == null) {
6140 return null;
6141 }
6142
Amith Yamasani483f3b02012-03-13 16:08:00 -07006143 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006144
Dianne Hackbornb424b632010-08-18 15:59:05 -07006145 String msg;
6146 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6147 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 }
6149
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006150 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006151 && !cpi.processName.equals("system")) {
6152 // If this content provider does not run in the system
6153 // process, and the system is not yet ready to run other
6154 // processes, then fail fast instead of hanging.
6155 throw new IllegalArgumentException(
6156 "Attempt to launch content provider before system ready");
6157 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006158
6159 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006160 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 final boolean firstClass = cpr == null;
6162 if (firstClass) {
6163 try {
6164 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006165 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 getApplicationInfo(
6167 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006168 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006170 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 + cpi.name);
6172 return null;
6173 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006174 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006175 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 } catch (RemoteException ex) {
6177 // pm is in same process, this will never happen.
6178 }
6179 }
6180
6181 if (r != null && cpr.canRunHere(r)) {
6182 // If this is a multiprocess provider, then just return its
6183 // info and allow the caller to instantiate it. Only do
6184 // this if the provider is the same user as the caller's
6185 // process, or can run as root (so can be in any process).
6186 return cpr;
6187 }
6188
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006189 if (DEBUG_PROVIDER) {
6190 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006191 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006192 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 }
6194
6195 // This is single process, and our app is now connecting to it.
6196 // See if we are already in the process of launching this
6197 // provider.
6198 final int N = mLaunchingProviders.size();
6199 int i;
6200 for (i=0; i<N; i++) {
6201 if (mLaunchingProviders.get(i) == cpr) {
6202 break;
6203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 }
6205
6206 // If the provider is not already being launched, then get it
6207 // started.
6208 if (i >= N) {
6209 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006210
6211 try {
6212 // Content provider is now in use, its package can't be stopped.
6213 try {
6214 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006215 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006216 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006217 } catch (IllegalArgumentException e) {
6218 Slog.w(TAG, "Failed trying to unstop package "
6219 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006220 }
6221
6222 ProcessRecord proc = startProcessLocked(cpi.processName,
6223 cpr.appInfo, false, 0, "content provider",
6224 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006225 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006226 if (proc == null) {
6227 Slog.w(TAG, "Unable to launch app "
6228 + cpi.applicationInfo.packageName + "/"
6229 + cpi.applicationInfo.uid + " for provider "
6230 + name + ": process is bad");
6231 return null;
6232 }
6233 cpr.launchingApp = proc;
6234 mLaunchingProviders.add(cpr);
6235 } finally {
6236 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 }
6239
6240 // Make sure the provider is published (the same provider class
6241 // may be published under multiple names).
6242 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006243 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006245
Amith Yamasani742a6712011-05-04 14:49:28 -07006246 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006247 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 }
6249 }
6250
6251 // Wait for the provider to be published...
6252 synchronized (cpr) {
6253 while (cpr.provider == null) {
6254 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006255 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 + cpi.applicationInfo.packageName + "/"
6257 + cpi.applicationInfo.uid + " for provider "
6258 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006259 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 cpi.applicationInfo.packageName,
6261 cpi.applicationInfo.uid, name);
6262 return null;
6263 }
6264 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006265 if (DEBUG_MU) {
6266 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6267 + cpr.launchingApp);
6268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 cpr.wait();
6270 } catch (InterruptedException ex) {
6271 }
6272 }
6273 }
6274 return cpr;
6275 }
6276
6277 public final ContentProviderHolder getContentProvider(
6278 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006279 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 if (caller == null) {
6281 String msg = "null IApplicationThread when getting content provider "
6282 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006283 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 throw new SecurityException(msg);
6285 }
6286
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006287 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 }
6289
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006290 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6291 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6292 "Do not have permission in call getContentProviderExternal()");
6293 return getContentProviderExternalUnchecked(name, token);
6294 }
6295
6296 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6297 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006298 }
6299
6300 /**
6301 * Drop a content provider from a ProcessRecord's bookkeeping
6302 * @param cpr
6303 */
6304 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006305 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006307 int userId = UserId.getUserId(Binder.getCallingUid());
6308 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006310 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006311 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006312 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 return;
6314 }
6315 final ProcessRecord r = getRecordForAppLocked(caller);
6316 if (r == null) {
6317 throw new SecurityException(
6318 "Unable to find app for caller " + caller +
6319 " when removing content provider " + name);
6320 }
6321 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006322 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006323 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6324 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6325 + r.info.processName + " from process "
6326 + localCpr.appInfo.processName);
6327 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006329 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006330 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 return;
6332 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006333 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006334 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 }
6338 }
6339
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006340 public void removeContentProviderExternal(String name, IBinder token) {
6341 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6342 "Do not have permission in call removeContentProviderExternal()");
6343 removeContentProviderExternalUnchecked(name, token);
6344 }
6345
6346 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006348 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6349 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006350 if(cpr == null) {
6351 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006352 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 return;
6354 }
6355
6356 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006357 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006358 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6359 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006360 if (localCpr.hasExternalProcessHandles()) {
6361 if (localCpr.removeExternalProcessHandleLocked(token)) {
6362 updateOomAdjLocked();
6363 } else {
6364 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6365 + " with no external reference for token: "
6366 + token + ".");
6367 }
6368 } else {
6369 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6370 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 }
6373 }
6374
6375 public final void publishContentProviders(IApplicationThread caller,
6376 List<ContentProviderHolder> providers) {
6377 if (providers == null) {
6378 return;
6379 }
6380
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006381 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 synchronized(this) {
6383 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006384 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006385 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 if (r == null) {
6387 throw new SecurityException(
6388 "Unable to find app for caller " + caller
6389 + " (pid=" + Binder.getCallingPid()
6390 + ") when publishing content providers");
6391 }
6392
6393 final long origId = Binder.clearCallingIdentity();
6394
6395 final int N = providers.size();
6396 for (int i=0; i<N; i++) {
6397 ContentProviderHolder src = providers.get(i);
6398 if (src == null || src.info == null || src.provider == null) {
6399 continue;
6400 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006401 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006402 if (DEBUG_MU)
6403 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006405 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006406 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 String names[] = dst.info.authority.split(";");
6408 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006409 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 }
6411
6412 int NL = mLaunchingProviders.size();
6413 int j;
6414 for (j=0; j<NL; j++) {
6415 if (mLaunchingProviders.get(j) == dst) {
6416 mLaunchingProviders.remove(j);
6417 j--;
6418 NL--;
6419 }
6420 }
6421 synchronized (dst) {
6422 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006423 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424 dst.notifyAll();
6425 }
6426 updateOomAdjLocked(r);
6427 }
6428 }
6429
6430 Binder.restoreCallingIdentity(origId);
6431 }
6432 }
6433
6434 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006435 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006436 synchronized (mSelf) {
6437 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6438 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006439 if (providers != null) {
6440 for (int i=providers.size()-1; i>=0; i--) {
6441 ProviderInfo pi = (ProviderInfo)providers.get(i);
6442 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6443 Slog.w(TAG, "Not installing system proc provider " + pi.name
6444 + ": not system .apk");
6445 providers.remove(i);
6446 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006447 }
6448 }
6449 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006450 if (providers != null) {
6451 mSystemThread.installSystemProviders(providers);
6452 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006453
6454 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006455
6456 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 }
6458
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006459 /**
6460 * Allows app to retrieve the MIME type of a URI without having permission
6461 * to access its content provider.
6462 *
6463 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6464 *
6465 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6466 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6467 */
6468 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006469 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006470 final String name = uri.getAuthority();
6471 final long ident = Binder.clearCallingIdentity();
6472 ContentProviderHolder holder = null;
6473
6474 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006475 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006476 if (holder != null) {
6477 return holder.provider.getType(uri);
6478 }
6479 } catch (RemoteException e) {
6480 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6481 return null;
6482 } finally {
6483 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006484 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006485 }
6486 Binder.restoreCallingIdentity(ident);
6487 }
6488
6489 return null;
6490 }
6491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 // =========================================================
6493 // GLOBAL MANAGEMENT
6494 // =========================================================
6495
6496 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006497 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 String proc = customProcess != null ? customProcess : info.processName;
6499 BatteryStatsImpl.Uid.Proc ps = null;
6500 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006501 int uid = info.uid;
6502 if (isolated) {
6503 int userId = UserId.getUserId(uid);
6504 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6505 uid = 0;
6506 while (true) {
6507 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6508 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6509 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6510 }
6511 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6512 mNextIsolatedProcessUid++;
6513 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6514 // No process for this uid, use it.
6515 break;
6516 }
6517 stepsLeft--;
6518 if (stepsLeft <= 0) {
6519 return null;
6520 }
6521 }
6522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006523 synchronized (stats) {
6524 ps = stats.getProcessStatsLocked(info.uid, proc);
6525 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006526 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 }
6528
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006529 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6530 ProcessRecord app;
6531 if (!isolated) {
6532 app = getProcessRecordLocked(info.processName, info.uid);
6533 } else {
6534 app = null;
6535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536
6537 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006538 app = newProcessRecordLocked(null, info, null, isolated);
6539 mProcessNames.put(info.processName, app.uid, app);
6540 if (isolated) {
6541 mIsolatedProcesses.put(app.uid, app);
6542 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006543 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 }
6545
Dianne Hackborne7f97212011-02-24 14:40:20 -08006546 // This package really, really can not be stopped.
6547 try {
6548 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006549 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006550 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006551 } catch (IllegalArgumentException e) {
6552 Slog.w(TAG, "Failed trying to unstop package "
6553 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006554 }
6555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006556 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6557 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6558 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006559 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 }
6561 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6562 mPersistentStartingProcesses.add(app);
6563 startProcessLocked(app, "added application", app.processName);
6564 }
6565
6566 return app;
6567 }
6568
6569 public void unhandledBack() {
6570 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6571 "unhandledBack()");
6572
6573 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006574 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006575 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006576 TAG, "Performing unhandledBack(): stack size = " + count);
6577 if (count > 1) {
6578 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006579 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6581 Binder.restoreCallingIdentity(origId);
6582 }
6583 }
6584 }
6585
6586 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006587 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006589 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 ParcelFileDescriptor pfd = null;
6591 if (cph != null) {
6592 // We record the binder invoker's uid in thread-local storage before
6593 // going to the content provider to open the file. Later, in the code
6594 // that handles all permissions checks, we look for this uid and use
6595 // that rather than the Activity Manager's own uid. The effect is that
6596 // we do the check against the caller's permissions even though it looks
6597 // to the content provider like the Activity Manager itself is making
6598 // the request.
6599 sCallerIdentity.set(new Identity(
6600 Binder.getCallingPid(), Binder.getCallingUid()));
6601 try {
6602 pfd = cph.provider.openFile(uri, "r");
6603 } catch (FileNotFoundException e) {
6604 // do nothing; pfd will be returned null
6605 } finally {
6606 // Ensure that whatever happens, we clean up the identity state
6607 sCallerIdentity.remove();
6608 }
6609
6610 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006611 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006613 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 }
6615 return pfd;
6616 }
6617
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006618 // Actually is sleeping or shutting down or whatever else in the future
6619 // is an inactive state.
6620 public boolean isSleeping() {
6621 return mSleeping || mShuttingDown;
6622 }
6623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 public void goingToSleep() {
6625 synchronized(this) {
6626 mSleeping = true;
6627 mWindowManager.setEventDispatching(false);
6628
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006629 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006630
6631 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006632 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006633 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6634 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006635 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 }
6637 }
6638
Dianne Hackborn55280a92009-05-07 15:53:46 -07006639 public boolean shutdown(int timeout) {
6640 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6641 != PackageManager.PERMISSION_GRANTED) {
6642 throw new SecurityException("Requires permission "
6643 + android.Manifest.permission.SHUTDOWN);
6644 }
6645
6646 boolean timedout = false;
6647
6648 synchronized(this) {
6649 mShuttingDown = true;
6650 mWindowManager.setEventDispatching(false);
6651
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006652 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006653 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006654 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006655 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006656 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006657 long delay = endTime - System.currentTimeMillis();
6658 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006659 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006660 timedout = true;
6661 break;
6662 }
6663 try {
6664 this.wait();
6665 } catch (InterruptedException e) {
6666 }
6667 }
6668 }
6669 }
6670
6671 mUsageStatsService.shutdown();
6672 mBatteryStatsService.shutdown();
6673
6674 return timedout;
6675 }
6676
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006677 public final void activitySlept(IBinder token) {
6678 if (localLOGV) Slog.v(
6679 TAG, "Activity slept: token=" + token);
6680
6681 ActivityRecord r = null;
6682
6683 final long origId = Binder.clearCallingIdentity();
6684
6685 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006686 r = mMainStack.isInStackLocked(token);
6687 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006688 mMainStack.activitySleptLocked(r);
6689 }
6690 }
6691
6692 Binder.restoreCallingIdentity(origId);
6693 }
6694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 public void wakingUp() {
6696 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 mWindowManager.setEventDispatching(true);
6698 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006699 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006700 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 }
6702 }
6703
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006704 public void stopAppSwitches() {
6705 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6706 != PackageManager.PERMISSION_GRANTED) {
6707 throw new SecurityException("Requires permission "
6708 + android.Manifest.permission.STOP_APP_SWITCHES);
6709 }
6710
6711 synchronized(this) {
6712 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6713 + APP_SWITCH_DELAY_TIME;
6714 mDidAppSwitch = false;
6715 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6716 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6717 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6718 }
6719 }
6720
6721 public void resumeAppSwitches() {
6722 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6723 != PackageManager.PERMISSION_GRANTED) {
6724 throw new SecurityException("Requires permission "
6725 + android.Manifest.permission.STOP_APP_SWITCHES);
6726 }
6727
6728 synchronized(this) {
6729 // Note that we don't execute any pending app switches... we will
6730 // let those wait until either the timeout, or the next start
6731 // activity request.
6732 mAppSwitchesAllowedTime = 0;
6733 }
6734 }
6735
6736 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6737 String name) {
6738 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6739 return true;
6740 }
6741
6742 final int perm = checkComponentPermission(
6743 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006744 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006745 if (perm == PackageManager.PERMISSION_GRANTED) {
6746 return true;
6747 }
6748
Joe Onorato8a9b2202010-02-26 18:56:32 -08006749 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006750 return false;
6751 }
6752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006753 public void setDebugApp(String packageName, boolean waitForDebugger,
6754 boolean persistent) {
6755 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6756 "setDebugApp()");
6757
6758 // Note that this is not really thread safe if there are multiple
6759 // callers into it at the same time, but that's not a situation we
6760 // care about.
6761 if (persistent) {
6762 final ContentResolver resolver = mContext.getContentResolver();
6763 Settings.System.putString(
6764 resolver, Settings.System.DEBUG_APP,
6765 packageName);
6766 Settings.System.putInt(
6767 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6768 waitForDebugger ? 1 : 0);
6769 }
6770
6771 synchronized (this) {
6772 if (!persistent) {
6773 mOrigDebugApp = mDebugApp;
6774 mOrigWaitForDebugger = mWaitForDebugger;
6775 }
6776 mDebugApp = packageName;
6777 mWaitForDebugger = waitForDebugger;
6778 mDebugTransient = !persistent;
6779 if (packageName != null) {
6780 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006781 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006782 Binder.restoreCallingIdentity(origId);
6783 }
6784 }
6785 }
6786
Siva Velusamy92a8b222012-03-09 16:24:04 -08006787 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6788 synchronized (this) {
6789 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6790 if (!isDebuggable) {
6791 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6792 throw new SecurityException("Process not debuggable: " + app.packageName);
6793 }
6794 }
6795
6796 mOpenGlTraceApp = processName;
6797 }
6798 }
6799
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006800 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6801 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6802 synchronized (this) {
6803 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6804 if (!isDebuggable) {
6805 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6806 throw new SecurityException("Process not debuggable: " + app.packageName);
6807 }
6808 }
6809 mProfileApp = processName;
6810 mProfileFile = profileFile;
6811 if (mProfileFd != null) {
6812 try {
6813 mProfileFd.close();
6814 } catch (IOException e) {
6815 }
6816 mProfileFd = null;
6817 }
6818 mProfileFd = profileFd;
6819 mProfileType = 0;
6820 mAutoStopProfiler = autoStopProfiler;
6821 }
6822 }
6823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006824 public void setAlwaysFinish(boolean enabled) {
6825 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6826 "setAlwaysFinish()");
6827
6828 Settings.System.putInt(
6829 mContext.getContentResolver(),
6830 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6831
6832 synchronized (this) {
6833 mAlwaysFinishActivities = enabled;
6834 }
6835 }
6836
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006837 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006839 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006841 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006842 }
6843 }
6844
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006845 public boolean isUserAMonkey() {
6846 // For now the fact that there is a controller implies
6847 // we have a monkey.
6848 synchronized (this) {
6849 return mController != null;
6850 }
6851 }
6852
Jeff Sharkeya4620792011-05-20 15:29:23 -07006853 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006854 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6855 "registerProcessObserver()");
6856 synchronized (this) {
6857 mProcessObservers.register(observer);
6858 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006859 }
6860
6861 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006862 synchronized (this) {
6863 mProcessObservers.unregister(observer);
6864 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006865 }
6866
Daniel Sandler69a48172010-06-23 16:29:36 -04006867 public void setImmersive(IBinder token, boolean immersive) {
6868 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006869 ActivityRecord r = mMainStack.isInStackLocked(token);
6870 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006871 throw new IllegalArgumentException();
6872 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006873 r.immersive = immersive;
6874 }
6875 }
6876
6877 public boolean isImmersive(IBinder token) {
6878 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006879 ActivityRecord r = mMainStack.isInStackLocked(token);
6880 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006881 throw new IllegalArgumentException();
6882 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006883 return r.immersive;
6884 }
6885 }
6886
6887 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006888 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006889 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006890 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006891 return (r != null) ? r.immersive : false;
6892 }
6893 }
6894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006895 public final void enterSafeMode() {
6896 synchronized(this) {
6897 // It only makes sense to do this before the system is ready
6898 // and started launching other packages.
6899 if (!mSystemReady) {
6900 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006901 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006902 } catch (RemoteException e) {
6903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006904 }
6905 }
6906 }
6907
Jeff Brownb09abc12011-01-13 21:08:27 -08006908 public final void showSafeModeOverlay() {
6909 View v = LayoutInflater.from(mContext).inflate(
6910 com.android.internal.R.layout.safe_mode, null);
6911 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6912 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6913 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6914 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6915 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6916 lp.format = v.getBackground().getOpacity();
6917 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6918 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6919 ((WindowManager)mContext.getSystemService(
6920 Context.WINDOW_SERVICE)).addView(v, lp);
6921 }
6922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006923 public void noteWakeupAlarm(IIntentSender sender) {
6924 if (!(sender instanceof PendingIntentRecord)) {
6925 return;
6926 }
6927 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6928 synchronized (stats) {
6929 if (mBatteryStatsService.isOnBattery()) {
6930 mBatteryStatsService.enforceCallingPermission();
6931 PendingIntentRecord rec = (PendingIntentRecord)sender;
6932 int MY_UID = Binder.getCallingUid();
6933 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6934 BatteryStatsImpl.Uid.Pkg pkg =
6935 stats.getPackageStatsLocked(uid, rec.key.packageName);
6936 pkg.incWakeupsLocked();
6937 }
6938 }
6939 }
6940
Dianne Hackborn64825172011-03-02 21:32:58 -08006941 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006942 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006943 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006945 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 // XXX Note: don't acquire main activity lock here, because the window
6947 // manager calls in with its locks held.
6948
6949 boolean killed = false;
6950 synchronized (mPidsSelfLocked) {
6951 int[] types = new int[pids.length];
6952 int worstType = 0;
6953 for (int i=0; i<pids.length; i++) {
6954 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6955 if (proc != null) {
6956 int type = proc.setAdj;
6957 types[i] = type;
6958 if (type > worstType) {
6959 worstType = type;
6960 }
6961 }
6962 }
6963
Dianne Hackborn64825172011-03-02 21:32:58 -08006964 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006966 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6967 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006968 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006970
6971 // If this is not a secure call, don't let it kill processes that
6972 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006973 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6974 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006975 }
6976
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006977 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 for (int i=0; i<pids.length; i++) {
6979 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6980 if (proc == null) {
6981 continue;
6982 }
6983 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006984 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006985 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006986 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6987 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006989 proc.killedBackground = true;
6990 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006991 }
6992 }
6993 }
6994 return killed;
6995 }
6996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006997 public final void startRunning(String pkg, String cls, String action,
6998 String data) {
6999 synchronized(this) {
7000 if (mStartRunning) {
7001 return;
7002 }
7003 mStartRunning = true;
7004 mTopComponent = pkg != null && cls != null
7005 ? new ComponentName(pkg, cls) : null;
7006 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7007 mTopData = data;
7008 if (!mSystemReady) {
7009 return;
7010 }
7011 }
7012
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007013 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014 }
7015
7016 private void retrieveSettings() {
7017 final ContentResolver resolver = mContext.getContentResolver();
7018 String debugApp = Settings.System.getString(
7019 resolver, Settings.System.DEBUG_APP);
7020 boolean waitForDebugger = Settings.System.getInt(
7021 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7022 boolean alwaysFinishActivities = Settings.System.getInt(
7023 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7024
7025 Configuration configuration = new Configuration();
7026 Settings.System.getConfiguration(resolver, configuration);
7027
7028 synchronized (this) {
7029 mDebugApp = mOrigDebugApp = debugApp;
7030 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7031 mAlwaysFinishActivities = alwaysFinishActivities;
7032 // This happens before any activities are started, so we can
7033 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007034 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007035 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007036 }
7037 }
7038
7039 public boolean testIsSystemReady() {
7040 // no need to synchronize(this) just to read & return the value
7041 return mSystemReady;
7042 }
7043
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007044 private static File getCalledPreBootReceiversFile() {
7045 File dataDir = Environment.getDataDirectory();
7046 File systemDir = new File(dataDir, "system");
7047 File fname = new File(systemDir, "called_pre_boots.dat");
7048 return fname;
7049 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007050
7051 static final int LAST_DONE_VERSION = 10000;
7052
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007053 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7054 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7055 File file = getCalledPreBootReceiversFile();
7056 FileInputStream fis = null;
7057 try {
7058 fis = new FileInputStream(file);
7059 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007060 int fvers = dis.readInt();
7061 if (fvers == LAST_DONE_VERSION) {
7062 String vers = dis.readUTF();
7063 String codename = dis.readUTF();
7064 String build = dis.readUTF();
7065 if (android.os.Build.VERSION.RELEASE.equals(vers)
7066 && android.os.Build.VERSION.CODENAME.equals(codename)
7067 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7068 int num = dis.readInt();
7069 while (num > 0) {
7070 num--;
7071 String pkg = dis.readUTF();
7072 String cls = dis.readUTF();
7073 lastDoneReceivers.add(new ComponentName(pkg, cls));
7074 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007075 }
7076 }
7077 } catch (FileNotFoundException e) {
7078 } catch (IOException e) {
7079 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7080 } finally {
7081 if (fis != null) {
7082 try {
7083 fis.close();
7084 } catch (IOException e) {
7085 }
7086 }
7087 }
7088 return lastDoneReceivers;
7089 }
7090
7091 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7092 File file = getCalledPreBootReceiversFile();
7093 FileOutputStream fos = null;
7094 DataOutputStream dos = null;
7095 try {
7096 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7097 fos = new FileOutputStream(file);
7098 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007099 dos.writeInt(LAST_DONE_VERSION);
7100 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007101 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007102 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007103 dos.writeInt(list.size());
7104 for (int i=0; i<list.size(); i++) {
7105 dos.writeUTF(list.get(i).getPackageName());
7106 dos.writeUTF(list.get(i).getClassName());
7107 }
7108 } catch (IOException e) {
7109 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7110 file.delete();
7111 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007112 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007113 if (dos != null) {
7114 try {
7115 dos.close();
7116 } catch (IOException e) {
7117 // TODO Auto-generated catch block
7118 e.printStackTrace();
7119 }
7120 }
7121 }
7122 }
7123
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007124 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007125 synchronized(this) {
7126 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007127 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007128 return;
7129 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007130
7131 // Check to see if there are any update receivers to run.
7132 if (!mDidUpdate) {
7133 if (mWaitingUpdate) {
7134 return;
7135 }
7136 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7137 List<ResolveInfo> ris = null;
7138 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007139 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007140 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007141 } catch (RemoteException e) {
7142 }
7143 if (ris != null) {
7144 for (int i=ris.size()-1; i>=0; i--) {
7145 if ((ris.get(i).activityInfo.applicationInfo.flags
7146 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7147 ris.remove(i);
7148 }
7149 }
7150 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007151
7152 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7153
7154 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007155 for (int i=0; i<ris.size(); i++) {
7156 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007157 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7158 if (lastDoneReceivers.contains(comp)) {
7159 ris.remove(i);
7160 i--;
7161 }
7162 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007163
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007164 for (int i=0; i<ris.size(); i++) {
7165 ActivityInfo ai = ris.get(i).activityInfo;
7166 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7167 doneReceivers.add(comp);
7168 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007169 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007170 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007171 finisher = new IIntentReceiver.Stub() {
7172 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007173 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007174 boolean sticky) {
7175 // The raw IIntentReceiver interface is called
7176 // with the AM lock held, so redispatch to
7177 // execute our code without the lock.
7178 mHandler.post(new Runnable() {
7179 public void run() {
7180 synchronized (ActivityManagerService.this) {
7181 mDidUpdate = true;
7182 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007183 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007184 showBootMessage(mContext.getText(
7185 R.string.android_upgrading_complete),
7186 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007187 systemReady(goingCallback);
7188 }
7189 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007190 }
7191 };
7192 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007193 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007194 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007195 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007196 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007197 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007198 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007199 mWaitingUpdate = true;
7200 }
7201 }
7202 }
7203 if (mWaitingUpdate) {
7204 return;
7205 }
7206 mDidUpdate = true;
7207 }
7208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007209 mSystemReady = true;
7210 if (!mStartRunning) {
7211 return;
7212 }
7213 }
7214
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007215 ArrayList<ProcessRecord> procsToKill = null;
7216 synchronized(mPidsSelfLocked) {
7217 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7218 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7219 if (!isAllowedWhileBooting(proc.info)){
7220 if (procsToKill == null) {
7221 procsToKill = new ArrayList<ProcessRecord>();
7222 }
7223 procsToKill.add(proc);
7224 }
7225 }
7226 }
7227
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007228 synchronized(this) {
7229 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007230 for (int i=procsToKill.size()-1; i>=0; i--) {
7231 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007232 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007233 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007234 }
7235 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007236
7237 // Now that we have cleaned up any update processes, we
7238 // are ready to start launching real processes and know that
7239 // we won't trample on them any more.
7240 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007241 }
7242
Joe Onorato8a9b2202010-02-26 18:56:32 -08007243 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007244 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007245 SystemClock.uptimeMillis());
7246
7247 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007248 // Make sure we have no pre-ready processes sitting around.
7249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007250 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7251 ResolveInfo ri = mContext.getPackageManager()
7252 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007253 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007254 CharSequence errorMsg = null;
7255 if (ri != null) {
7256 ActivityInfo ai = ri.activityInfo;
7257 ApplicationInfo app = ai.applicationInfo;
7258 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7259 mTopAction = Intent.ACTION_FACTORY_TEST;
7260 mTopData = null;
7261 mTopComponent = new ComponentName(app.packageName,
7262 ai.name);
7263 } else {
7264 errorMsg = mContext.getResources().getText(
7265 com.android.internal.R.string.factorytest_not_system);
7266 }
7267 } else {
7268 errorMsg = mContext.getResources().getText(
7269 com.android.internal.R.string.factorytest_no_action);
7270 }
7271 if (errorMsg != null) {
7272 mTopAction = null;
7273 mTopData = null;
7274 mTopComponent = null;
7275 Message msg = Message.obtain();
7276 msg.what = SHOW_FACTORY_ERROR_MSG;
7277 msg.getData().putCharSequence("msg", errorMsg);
7278 mHandler.sendMessage(msg);
7279 }
7280 }
7281 }
7282
7283 retrieveSettings();
7284
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007285 if (goingCallback != null) goingCallback.run();
7286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007287 synchronized (this) {
7288 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7289 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007290 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007291 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007292 if (apps != null) {
7293 int N = apps.size();
7294 int i;
7295 for (i=0; i<N; i++) {
7296 ApplicationInfo info
7297 = (ApplicationInfo)apps.get(i);
7298 if (info != null &&
7299 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007300 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007301 }
7302 }
7303 }
7304 } catch (RemoteException ex) {
7305 // pm is in same process, this will never happen.
7306 }
7307 }
7308
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007309 // Start up initial activity.
7310 mBooting = true;
7311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007312 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007313 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 Message msg = Message.obtain();
7315 msg.what = SHOW_UID_ERROR_MSG;
7316 mHandler.sendMessage(msg);
7317 }
7318 } catch (RemoteException e) {
7319 }
7320
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007321 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007322 }
7323 }
7324
Dan Egnorb7f03672009-12-09 16:22:32 -08007325 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007326 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007327 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007328 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007329 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 startAppProblemLocked(app);
7331 app.stopFreezingAllLocked();
7332 return handleAppCrashLocked(app);
7333 }
7334
Dan Egnorb7f03672009-12-09 16:22:32 -08007335 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007336 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007338 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007339 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7340 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007341 startAppProblemLocked(app);
7342 app.stopFreezingAllLocked();
7343 }
7344
7345 /**
7346 * Generate a process error record, suitable for attachment to a ProcessRecord.
7347 *
7348 * @param app The ProcessRecord in which the error occurred.
7349 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7350 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007351 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007352 * @param shortMsg Short message describing the crash.
7353 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007354 * @param stackTrace Full crash stack trace, may be null.
7355 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007356 * @return Returns a fully-formed AppErrorStateInfo record.
7357 */
7358 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007359 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007360 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007362 report.condition = condition;
7363 report.processName = app.processName;
7364 report.pid = app.pid;
7365 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007366 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007367 report.shortMsg = shortMsg;
7368 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007369 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007370
7371 return report;
7372 }
7373
Dan Egnor42471dd2010-01-07 17:25:22 -08007374 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007375 synchronized (this) {
7376 app.crashing = false;
7377 app.crashingReport = null;
7378 app.notResponding = false;
7379 app.notRespondingReport = null;
7380 if (app.anrDialog == fromDialog) {
7381 app.anrDialog = null;
7382 }
7383 if (app.waitDialog == fromDialog) {
7384 app.waitDialog = null;
7385 }
7386 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007387 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007388 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007389 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7390 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007391 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007393 }
7394 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007395
Dan Egnorb7f03672009-12-09 16:22:32 -08007396 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 long now = SystemClock.uptimeMillis();
7398
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007399 Long crashTime;
7400 if (!app.isolated) {
7401 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7402 } else {
7403 crashTime = null;
7404 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007405 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007407 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007408 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007409 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007410 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007411 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7412 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007414 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007416 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007417 }
7418 }
7419 if (!app.persistent) {
7420 // We don't want to start this process again until the user
7421 // explicitly does so... but for persistent process, we really
7422 // need to keep it running. If a persistent process is actually
7423 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007424 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007425 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007426 if (!app.isolated) {
7427 // XXX We don't have a way to mark isolated processes
7428 // as bad, since they don't have a peristent identity.
7429 mBadProcesses.put(app.info.processName, app.uid, now);
7430 mProcessCrashTimes.remove(app.info.processName, app.uid);
7431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007432 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007433 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007434 // Don't let services in this process be restarted and potentially
7435 // annoy the user repeatedly. Unless it is persistent, since those
7436 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007437 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007438 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007439 return false;
7440 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007441 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007442 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007443 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007444 if (r.app == app) {
7445 // If the top running activity is from this crashing
7446 // process, then terminate it to avoid getting in a loop.
7447 Slog.w(TAG, " Force finishing activity "
7448 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007449 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007450 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007451 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007452 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007453 // stopped, to avoid a situation where one will get
7454 // re-start our crashing activity once it gets resumed again.
7455 index--;
7456 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007457 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007458 if (r.state == ActivityState.RESUMED
7459 || r.state == ActivityState.PAUSING
7460 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007461 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007462 Slog.w(TAG, " Force finishing activity "
7463 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007464 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007465 Activity.RESULT_CANCELED, null, "crashed");
7466 }
7467 }
7468 }
7469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007470 }
7471
7472 // Bump up the crash count of any services currently running in the proc.
7473 if (app.services.size() != 0) {
7474 // Any services running in the application need to be placed
7475 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007476 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007477 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007478 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007479 sr.crashCount++;
7480 }
7481 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007482
7483 // If the crashing process is what we consider to be the "home process" and it has been
7484 // replaced by a third-party app, clear the package preferred activities from packages
7485 // with a home activity running in the process to prevent a repeatedly crashing app
7486 // from blocking the user to manually clear the list.
7487 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7488 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7489 Iterator it = mHomeProcess.activities.iterator();
7490 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007491 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007492 if (r.isHomeActivity) {
7493 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7494 try {
7495 ActivityThread.getPackageManager()
7496 .clearPackagePreferredActivities(r.packageName);
7497 } catch (RemoteException c) {
7498 // pm is in same process, this will never happen.
7499 }
7500 }
7501 }
7502 }
7503
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007504 if (!app.isolated) {
7505 // XXX Can't keep track of crash times for isolated processes,
7506 // because they don't have a perisistent identity.
7507 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7508 }
7509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007510 return true;
7511 }
7512
7513 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007514 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7515 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007516 skipCurrentReceiverLocked(app);
7517 }
7518
7519 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007520 for (BroadcastQueue queue : mBroadcastQueues) {
7521 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007522 }
7523 }
7524
Dan Egnor60d87622009-12-16 16:32:58 -08007525 /**
7526 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7527 * The application process will exit immediately after this call returns.
7528 * @param app object of the crashing app, null for the system server
7529 * @param crashInfo describing the exception
7530 */
7531 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007532 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007533 final String processName = app == null ? "system_server"
7534 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007535
7536 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007537 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007538 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007539 crashInfo.exceptionClassName,
7540 crashInfo.exceptionMessage,
7541 crashInfo.throwFileName,
7542 crashInfo.throwLineNumber);
7543
Jeff Sharkeya353d262011-10-28 11:12:06 -07007544 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007545
7546 crashApplication(r, crashInfo);
7547 }
7548
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007549 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007550 IBinder app,
7551 int violationMask,
7552 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007553 ProcessRecord r = findAppProcess(app, "StrictMode");
7554 if (r == null) {
7555 return;
7556 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007557
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007558 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007559 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007560 boolean logIt = true;
7561 synchronized (mAlreadyLoggedViolatedStacks) {
7562 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7563 logIt = false;
7564 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007565 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007566 // the relative pain numbers, without logging all
7567 // the stack traces repeatedly. We'd want to do
7568 // likewise in the client code, which also does
7569 // dup suppression, before the Binder call.
7570 } else {
7571 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7572 mAlreadyLoggedViolatedStacks.clear();
7573 }
7574 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7575 }
7576 }
7577 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007578 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007579 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007580 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007581
7582 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7583 AppErrorResult result = new AppErrorResult();
7584 synchronized (this) {
7585 final long origId = Binder.clearCallingIdentity();
7586
7587 Message msg = Message.obtain();
7588 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7589 HashMap<String, Object> data = new HashMap<String, Object>();
7590 data.put("result", result);
7591 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007592 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007593 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007594 msg.obj = data;
7595 mHandler.sendMessage(msg);
7596
7597 Binder.restoreCallingIdentity(origId);
7598 }
7599 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007600 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007601 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007602 }
7603
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007604 // Depending on the policy in effect, there could be a bunch of
7605 // these in quick succession so we try to batch these together to
7606 // minimize disk writes, number of dropbox entries, and maximize
7607 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007608 private void logStrictModeViolationToDropBox(
7609 ProcessRecord process,
7610 StrictMode.ViolationInfo info) {
7611 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007612 return;
7613 }
7614 final boolean isSystemApp = process == null ||
7615 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7616 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007617 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007618 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7619 final DropBoxManager dbox = (DropBoxManager)
7620 mContext.getSystemService(Context.DROPBOX_SERVICE);
7621
7622 // Exit early if the dropbox isn't configured to accept this report type.
7623 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7624
7625 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007626 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007627 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7628 synchronized (sb) {
7629 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007630 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007631 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7632 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007633 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7634 if (info.violationNumThisLoop != 0) {
7635 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7636 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007637 if (info.numAnimationsRunning != 0) {
7638 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7639 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007640 if (info.broadcastIntentAction != null) {
7641 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7642 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007643 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007644 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007645 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007646 if (info.numInstances != -1) {
7647 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7648 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007649 if (info.tags != null) {
7650 for (String tag : info.tags) {
7651 sb.append("Span-Tag: ").append(tag).append("\n");
7652 }
7653 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007654 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007655 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7656 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007657 }
7658 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007659
7660 // Only buffer up to ~64k. Various logging bits truncate
7661 // things at 128k.
7662 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007663 }
7664
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007665 // Flush immediately if the buffer's grown too large, or this
7666 // is a non-system app. Non-system apps are isolated with a
7667 // different tag & policy and not batched.
7668 //
7669 // Batching is useful during internal testing with
7670 // StrictMode settings turned up high. Without batching,
7671 // thousands of separate files could be created on boot.
7672 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007673 new Thread("Error dump: " + dropboxTag) {
7674 @Override
7675 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007676 String report;
7677 synchronized (sb) {
7678 report = sb.toString();
7679 sb.delete(0, sb.length());
7680 sb.trimToSize();
7681 }
7682 if (report.length() != 0) {
7683 dbox.addText(dropboxTag, report);
7684 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007685 }
7686 }.start();
7687 return;
7688 }
7689
7690 // System app batching:
7691 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007692 // An existing dropbox-writing thread is outstanding, so
7693 // we don't need to start it up. The existing thread will
7694 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007695 return;
7696 }
7697
7698 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7699 // (After this point, we shouldn't access AMS internal data structures.)
7700 new Thread("Error dump: " + dropboxTag) {
7701 @Override
7702 public void run() {
7703 // 5 second sleep to let stacks arrive and be batched together
7704 try {
7705 Thread.sleep(5000); // 5 seconds
7706 } catch (InterruptedException e) {}
7707
7708 String errorReport;
7709 synchronized (mStrictModeBuffer) {
7710 errorReport = mStrictModeBuffer.toString();
7711 if (errorReport.length() == 0) {
7712 return;
7713 }
7714 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7715 mStrictModeBuffer.trimToSize();
7716 }
7717 dbox.addText(dropboxTag, errorReport);
7718 }
7719 }.start();
7720 }
7721
Dan Egnor60d87622009-12-16 16:32:58 -08007722 /**
7723 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7724 * @param app object of the crashing app, null for the system server
7725 * @param tag reported by the caller
7726 * @param crashInfo describing the context of the error
7727 * @return true if the process should exit immediately (WTF is fatal)
7728 */
7729 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007730 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007731 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007732 final String processName = app == null ? "system_server"
7733 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007734
7735 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007736 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007737 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007738 tag, crashInfo.exceptionMessage);
7739
Jeff Sharkeya353d262011-10-28 11:12:06 -07007740 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007741
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007742 if (r != null && r.pid != Process.myPid() &&
7743 Settings.Secure.getInt(mContext.getContentResolver(),
7744 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007745 crashApplication(r, crashInfo);
7746 return true;
7747 } else {
7748 return false;
7749 }
7750 }
7751
7752 /**
7753 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7754 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7755 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007756 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007757 if (app == null) {
7758 return null;
7759 }
7760
7761 synchronized (this) {
7762 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7763 final int NA = apps.size();
7764 for (int ia=0; ia<NA; ia++) {
7765 ProcessRecord p = apps.valueAt(ia);
7766 if (p.thread != null && p.thread.asBinder() == app) {
7767 return p;
7768 }
7769 }
7770 }
7771
Dianne Hackborncb44d962011-03-10 17:02:27 -08007772 Slog.w(TAG, "Can't find mystery application for " + reason
7773 + " from pid=" + Binder.getCallingPid()
7774 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007775 return null;
7776 }
7777 }
7778
7779 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007780 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7781 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007782 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007783 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7784 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007785 // Watchdog thread ends up invoking this function (with
7786 // a null ProcessRecord) to add the stack file to dropbox.
7787 // Do not acquire a lock on this (am) in such cases, as it
7788 // could cause a potential deadlock, if and when watchdog
7789 // is invoked due to unavailability of lock on am and it
7790 // would prevent watchdog from killing system_server.
7791 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007792 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007793 return;
7794 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007795 // Note: ProcessRecord 'process' is guarded by the service
7796 // instance. (notably process.pkgList, which could otherwise change
7797 // concurrently during execution of this method)
7798 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007799 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007800 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007801 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007802 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7803 for (String pkg : process.pkgList) {
7804 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007805 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007806 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007807 if (pi != null) {
7808 sb.append(" v").append(pi.versionCode);
7809 if (pi.versionName != null) {
7810 sb.append(" (").append(pi.versionName).append(")");
7811 }
7812 }
7813 } catch (RemoteException e) {
7814 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007815 }
Dan Egnora455d192010-03-12 08:52:28 -08007816 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007817 }
Dan Egnora455d192010-03-12 08:52:28 -08007818 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007819 }
7820
7821 private static String processClass(ProcessRecord process) {
7822 if (process == null || process.pid == MY_PID) {
7823 return "system_server";
7824 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7825 return "system_app";
7826 } else {
7827 return "data_app";
7828 }
7829 }
7830
7831 /**
7832 * Write a description of an error (crash, WTF, ANR) to the drop box.
7833 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7834 * @param process which caused the error, null means the system server
7835 * @param activity which triggered the error, null if unknown
7836 * @param parent activity related to the error, null if unknown
7837 * @param subject line related to the error, null if absent
7838 * @param report in long form describing the error, null if absent
7839 * @param logFile to include in the report, null if none
7840 * @param crashInfo giving an application stack trace, null if absent
7841 */
7842 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007843 ProcessRecord process, String processName, ActivityRecord activity,
7844 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007845 final String report, final File logFile,
7846 final ApplicationErrorReport.CrashInfo crashInfo) {
7847 // NOTE -- this must never acquire the ActivityManagerService lock,
7848 // otherwise the watchdog may be prevented from resetting the system.
7849
7850 final String dropboxTag = processClass(process) + "_" + eventType;
7851 final DropBoxManager dbox = (DropBoxManager)
7852 mContext.getSystemService(Context.DROPBOX_SERVICE);
7853
7854 // Exit early if the dropbox isn't configured to accept this report type.
7855 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7856
7857 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007858 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007859 if (activity != null) {
7860 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7861 }
7862 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7863 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7864 }
7865 if (parent != null && parent != activity) {
7866 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7867 }
7868 if (subject != null) {
7869 sb.append("Subject: ").append(subject).append("\n");
7870 }
7871 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007872 if (Debug.isDebuggerConnected()) {
7873 sb.append("Debugger: Connected\n");
7874 }
Dan Egnora455d192010-03-12 08:52:28 -08007875 sb.append("\n");
7876
7877 // Do the rest in a worker thread to avoid blocking the caller on I/O
7878 // (After this point, we shouldn't access AMS internal data structures.)
7879 Thread worker = new Thread("Error dump: " + dropboxTag) {
7880 @Override
7881 public void run() {
7882 if (report != null) {
7883 sb.append(report);
7884 }
7885 if (logFile != null) {
7886 try {
7887 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7888 } catch (IOException e) {
7889 Slog.e(TAG, "Error reading " + logFile, e);
7890 }
7891 }
7892 if (crashInfo != null && crashInfo.stackTrace != null) {
7893 sb.append(crashInfo.stackTrace);
7894 }
7895
7896 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7897 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7898 if (lines > 0) {
7899 sb.append("\n");
7900
7901 // Merge several logcat streams, and take the last N lines
7902 InputStreamReader input = null;
7903 try {
7904 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7905 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7906 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7907
7908 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7909 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7910 input = new InputStreamReader(logcat.getInputStream());
7911
7912 int num;
7913 char[] buf = new char[8192];
7914 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7915 } catch (IOException e) {
7916 Slog.e(TAG, "Error running logcat", e);
7917 } finally {
7918 if (input != null) try { input.close(); } catch (IOException e) {}
7919 }
7920 }
7921
7922 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007923 }
Dan Egnora455d192010-03-12 08:52:28 -08007924 };
7925
7926 if (process == null || process.pid == MY_PID) {
7927 worker.run(); // We may be about to die -- need to run this synchronously
7928 } else {
7929 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007930 }
7931 }
7932
7933 /**
7934 * Bring up the "unexpected error" dialog box for a crashing app.
7935 * Deal with edge cases (intercepts from instrumented applications,
7936 * ActivityController, error intent receivers, that sort of thing).
7937 * @param r the application crashing
7938 * @param crashInfo describing the failure
7939 */
7940 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007941 long timeMillis = System.currentTimeMillis();
7942 String shortMsg = crashInfo.exceptionClassName;
7943 String longMsg = crashInfo.exceptionMessage;
7944 String stackTrace = crashInfo.stackTrace;
7945 if (shortMsg != null && longMsg != null) {
7946 longMsg = shortMsg + ": " + longMsg;
7947 } else if (shortMsg != null) {
7948 longMsg = shortMsg;
7949 }
7950
Dan Egnor60d87622009-12-16 16:32:58 -08007951 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007952 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007953 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007954 try {
7955 String name = r != null ? r.processName : null;
7956 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007957 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007958 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007959 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 + " at watcher's request");
7961 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007962 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007963 }
7964 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007965 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 }
7967 }
7968
7969 final long origId = Binder.clearCallingIdentity();
7970
7971 // If this process is running instrumentation, finish it.
7972 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007973 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007975 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7976 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007977 Bundle info = new Bundle();
7978 info.putString("shortMsg", shortMsg);
7979 info.putString("longMsg", longMsg);
7980 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7981 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007982 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 }
7984
Dan Egnor60d87622009-12-16 16:32:58 -08007985 // If we can't identify the process or it's already exceeded its crash quota,
7986 // quit right away without showing a crash dialog.
7987 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007988 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007989 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007990 }
7991
7992 Message msg = Message.obtain();
7993 msg.what = SHOW_ERROR_MSG;
7994 HashMap data = new HashMap();
7995 data.put("result", result);
7996 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 msg.obj = data;
7998 mHandler.sendMessage(msg);
7999
8000 Binder.restoreCallingIdentity(origId);
8001 }
8002
8003 int res = result.get();
8004
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008005 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008006 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008007 if (r != null && !r.isolated) {
8008 // XXX Can't keep track of crash time for isolated processes,
8009 // since they don't have a persistent identity.
8010 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008011 SystemClock.uptimeMillis());
8012 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008013 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008014 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008015 }
8016 }
8017
8018 if (appErrorIntent != null) {
8019 try {
8020 mContext.startActivity(appErrorIntent);
8021 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008022 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008025 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008026
8027 Intent createAppErrorIntentLocked(ProcessRecord r,
8028 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8029 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008030 if (report == null) {
8031 return null;
8032 }
8033 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8034 result.setComponent(r.errorReportReceiver);
8035 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8036 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8037 return result;
8038 }
8039
Dan Egnorb7f03672009-12-09 16:22:32 -08008040 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8041 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008042 if (r.errorReportReceiver == null) {
8043 return null;
8044 }
8045
8046 if (!r.crashing && !r.notResponding) {
8047 return null;
8048 }
8049
Dan Egnorb7f03672009-12-09 16:22:32 -08008050 ApplicationErrorReport report = new ApplicationErrorReport();
8051 report.packageName = r.info.packageName;
8052 report.installerPackageName = r.errorReportReceiver.getPackageName();
8053 report.processName = r.processName;
8054 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008055 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008056
Dan Egnorb7f03672009-12-09 16:22:32 -08008057 if (r.crashing) {
8058 report.type = ApplicationErrorReport.TYPE_CRASH;
8059 report.crashInfo = crashInfo;
8060 } else if (r.notResponding) {
8061 report.type = ApplicationErrorReport.TYPE_ANR;
8062 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008063
Dan Egnorb7f03672009-12-09 16:22:32 -08008064 report.anrInfo.activity = r.notRespondingReport.tag;
8065 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8066 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008067 }
8068
Dan Egnorb7f03672009-12-09 16:22:32 -08008069 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008070 }
8071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008072 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008073 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 // assume our apps are happy - lazy create the list
8075 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8076
8077 synchronized (this) {
8078
8079 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008080 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8081 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8083 // This one's in trouble, so we'll generate a report for it
8084 // crashes are higher priority (in case there's a crash *and* an anr)
8085 ActivityManager.ProcessErrorStateInfo report = null;
8086 if (app.crashing) {
8087 report = app.crashingReport;
8088 } else if (app.notResponding) {
8089 report = app.notRespondingReport;
8090 }
8091
8092 if (report != null) {
8093 if (errList == null) {
8094 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8095 }
8096 errList.add(report);
8097 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008098 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 " crashing = " + app.crashing +
8100 " notResponding = " + app.notResponding);
8101 }
8102 }
8103 }
8104 }
8105
8106 return errList;
8107 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008108
8109 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008110 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008111 if (currApp != null) {
8112 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8113 }
8114 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008115 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8116 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008117 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8118 if (currApp != null) {
8119 currApp.lru = 0;
8120 }
8121 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008122 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008123 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8124 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8125 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8126 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8127 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8128 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8129 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8130 } else {
8131 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8132 }
8133 }
8134
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008135 private void fillInProcMemInfo(ProcessRecord app,
8136 ActivityManager.RunningAppProcessInfo outInfo) {
8137 outInfo.pid = app.pid;
8138 outInfo.uid = app.info.uid;
8139 if (mHeavyWeightProcess == app) {
8140 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8141 }
8142 if (app.persistent) {
8143 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8144 }
8145 outInfo.lastTrimLevel = app.trimMemoryLevel;
8146 int adj = app.curAdj;
8147 outInfo.importance = oomAdjToImportance(adj, outInfo);
8148 outInfo.importanceReasonCode = app.adjTypeCode;
8149 }
8150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008152 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008153 // Lazy instantiation of list
8154 List<ActivityManager.RunningAppProcessInfo> runList = null;
8155 synchronized (this) {
8156 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008157 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8158 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8160 // Generate process state info for running application
8161 ActivityManager.RunningAppProcessInfo currApp =
8162 new ActivityManager.RunningAppProcessInfo(app.processName,
8163 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008164 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008165 if (app.adjSource instanceof ProcessRecord) {
8166 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008167 currApp.importanceReasonImportance = oomAdjToImportance(
8168 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008169 } else if (app.adjSource instanceof ActivityRecord) {
8170 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008171 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8172 }
8173 if (app.adjTarget instanceof ComponentName) {
8174 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8175 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008176 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 // + " lru=" + currApp.lru);
8178 if (runList == null) {
8179 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8180 }
8181 runList.add(currApp);
8182 }
8183 }
8184 }
8185 return runList;
8186 }
8187
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008188 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008189 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008190 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8191 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8192 if (runningApps != null && runningApps.size() > 0) {
8193 Set<String> extList = new HashSet<String>();
8194 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8195 if (app.pkgList != null) {
8196 for (String pkg : app.pkgList) {
8197 extList.add(pkg);
8198 }
8199 }
8200 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008201 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008202 for (String pkg : extList) {
8203 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008204 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008205 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8206 retList.add(info);
8207 }
8208 } catch (RemoteException e) {
8209 }
8210 }
8211 }
8212 return retList;
8213 }
8214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008215 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008216 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8217 enforceNotIsolatedCaller("getMyMemoryState");
8218 synchronized (this) {
8219 ProcessRecord proc;
8220 synchronized (mPidsSelfLocked) {
8221 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8222 }
8223 fillInProcMemInfo(proc, outInfo);
8224 }
8225 }
8226
8227 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008229 if (checkCallingPermission(android.Manifest.permission.DUMP)
8230 != PackageManager.PERMISSION_GRANTED) {
8231 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8232 + Binder.getCallingPid()
8233 + ", uid=" + Binder.getCallingUid()
8234 + " without permission "
8235 + android.Manifest.permission.DUMP);
8236 return;
8237 }
8238
8239 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008240 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008241 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008242
8243 int opti = 0;
8244 while (opti < args.length) {
8245 String opt = args[opti];
8246 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8247 break;
8248 }
8249 opti++;
8250 if ("-a".equals(opt)) {
8251 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008252 } else if ("-c".equals(opt)) {
8253 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008254 } else if ("-h".equals(opt)) {
8255 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008256 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008257 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008258 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008259 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8260 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8261 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008262 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008263 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008264 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008265 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008266 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008267 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008268 pw.println(" all: dump all activities");
8269 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008270 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008271 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8272 pw.println(" a partial substring in a component name, a");
8273 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008274 pw.println(" -a: include all available server state.");
8275 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008277 } else {
8278 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008279 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008280 }
8281
8282 // Is the caller requesting to dump a particular piece of data?
8283 if (opti < args.length) {
8284 String cmd = args[opti];
8285 opti++;
8286 if ("activities".equals(cmd) || "a".equals(cmd)) {
8287 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008288 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008289 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008290 return;
8291 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008292 String[] newArgs;
8293 String name;
8294 if (opti >= args.length) {
8295 name = null;
8296 newArgs = EMPTY_STRING_ARRAY;
8297 } else {
8298 name = args[opti];
8299 opti++;
8300 newArgs = new String[args.length - opti];
8301 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8302 args.length - opti);
8303 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008304 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008305 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008306 }
8307 return;
8308 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008309 String[] newArgs;
8310 String name;
8311 if (opti >= args.length) {
8312 name = null;
8313 newArgs = EMPTY_STRING_ARRAY;
8314 } else {
8315 name = args[opti];
8316 opti++;
8317 newArgs = new String[args.length - opti];
8318 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8319 args.length - opti);
8320 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008321 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008322 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008323 }
8324 return;
8325 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008326 String[] newArgs;
8327 String name;
8328 if (opti >= args.length) {
8329 name = null;
8330 newArgs = EMPTY_STRING_ARRAY;
8331 } else {
8332 name = args[opti];
8333 opti++;
8334 newArgs = new String[args.length - opti];
8335 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8336 args.length - opti);
8337 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008338 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008339 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008340 }
8341 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008342 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8343 synchronized (this) {
8344 dumpOomLocked(fd, pw, args, opti, true);
8345 }
8346 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008347 } else if ("provider".equals(cmd)) {
8348 String[] newArgs;
8349 String name;
8350 if (opti >= args.length) {
8351 name = null;
8352 newArgs = EMPTY_STRING_ARRAY;
8353 } else {
8354 name = args[opti];
8355 opti++;
8356 newArgs = new String[args.length - opti];
8357 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8358 }
8359 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8360 pw.println("No providers match: " + name);
8361 pw.println("Use -h for help.");
8362 }
8363 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008364 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8365 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008366 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008367 }
8368 return;
8369 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008370 String[] newArgs;
8371 String name;
8372 if (opti >= args.length) {
8373 name = null;
8374 newArgs = EMPTY_STRING_ARRAY;
8375 } else {
8376 name = args[opti];
8377 opti++;
8378 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008379 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8380 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008381 }
8382 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8383 pw.println("No services match: " + name);
8384 pw.println("Use -h for help.");
8385 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008386 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008387 } else if ("package".equals(cmd)) {
8388 String[] newArgs;
8389 if (opti >= args.length) {
8390 pw.println("package: no package name specified");
8391 pw.println("Use -h for help.");
8392 return;
8393 } else {
8394 dumpPackage = args[opti];
8395 opti++;
8396 newArgs = new String[args.length - opti];
8397 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8398 args.length - opti);
8399 args = newArgs;
8400 opti = 0;
8401 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008402 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8403 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008404 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008405 }
8406 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008407 } else {
8408 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008409 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8410 pw.println("Bad activity command, or no activities match: " + cmd);
8411 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008412 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008413 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008414 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008415 }
8416
8417 // No piece of data specified, dump everything.
8418 synchronized (this) {
8419 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008420 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008421 if (needSep) {
8422 pw.println(" ");
8423 }
8424 if (dumpAll) {
8425 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008426 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008427 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008428 if (needSep) {
8429 pw.println(" ");
8430 }
8431 if (dumpAll) {
8432 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008433 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008434 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008435 if (needSep) {
8436 pw.println(" ");
8437 }
8438 if (dumpAll) {
8439 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008440 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008441 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008442 if (needSep) {
8443 pw.println(" ");
8444 }
8445 if (dumpAll) {
8446 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008447 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008448 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008449 if (needSep) {
8450 pw.println(" ");
8451 }
8452 if (dumpAll) {
8453 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008454 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008455 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008456 }
8457 }
8458
8459 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008460 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008461 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8462 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008463 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8464 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008465 pw.println(" ");
8466 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008467 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8468 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008469 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008470 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008471 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008472 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008473 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008474 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008475 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008477 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008478 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008479 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008480 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008481 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8482 pw.println(" ");
8483 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008484 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008485 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008486 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008487 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008488 pw.println(" ");
8489 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008490 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008491 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008493
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008494 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008495 if (mMainStack.mPausingActivity != null) {
8496 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008497 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008498 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008499 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008500 if (dumpAll) {
8501 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8502 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008503 pw.println(" mDismissKeyguardOnNextActivity: "
8504 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008507 if (mRecentTasks.size() > 0) {
8508 pw.println();
8509 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008510
8511 final int N = mRecentTasks.size();
8512 for (int i=0; i<N; i++) {
8513 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008514 if (dumpPackage != null) {
8515 if (tr.realActivity == null ||
8516 !dumpPackage.equals(tr.realActivity)) {
8517 continue;
8518 }
8519 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008520 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8521 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008522 if (dumpAll) {
8523 mRecentTasks.get(i).dump(pw, " ");
8524 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008525 }
8526 }
8527
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008528 if (dumpAll) {
8529 pw.println(" ");
8530 pw.println(" mCurTask: " + mCurTask);
8531 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008532
8533 return true;
8534 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008535
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008536 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008537 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008538 boolean needSep = false;
8539 int numPers = 0;
8540
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008541 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8542
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008543 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008544 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8545 final int NA = procs.size();
8546 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008547 ProcessRecord r = procs.valueAt(ia);
8548 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8549 continue;
8550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008551 if (!needSep) {
8552 pw.println(" All known processes:");
8553 needSep = true;
8554 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008555 pw.print(r.persistent ? " *PERS*" : " *APP*");
8556 pw.print(" UID "); pw.print(procs.keyAt(ia));
8557 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008558 r.dump(pw, " ");
8559 if (r.persistent) {
8560 numPers++;
8561 }
8562 }
8563 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008564 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008565
8566 if (mIsolatedProcesses.size() > 0) {
8567 if (needSep) pw.println(" ");
8568 needSep = true;
8569 pw.println(" Isolated process list (sorted by uid):");
8570 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8571 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8572 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8573 continue;
8574 }
8575 pw.println(String.format("%sIsolated #%2d: %s",
8576 " ", i, r.toString()));
8577 }
8578 }
8579
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008580 if (mLruProcesses.size() > 0) {
8581 if (needSep) pw.println(" ");
8582 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008583 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008584 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008585 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008586 needSep = true;
8587 }
8588
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008589 if (dumpAll) {
8590 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008591 boolean printed = false;
8592 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8593 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8594 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8595 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008596 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008597 if (!printed) {
8598 if (needSep) pw.println(" ");
8599 needSep = true;
8600 pw.println(" PID mappings:");
8601 printed = true;
8602 }
8603 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8604 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008605 }
8606 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008607 }
8608
8609 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008610 synchronized (mPidsSelfLocked) {
8611 boolean printed = false;
8612 for (int i=0; i<mForegroundProcesses.size(); i++) {
8613 ProcessRecord r = mPidsSelfLocked.get(
8614 mForegroundProcesses.valueAt(i).pid);
8615 if (dumpPackage != null && (r == null
8616 || !dumpPackage.equals(r.info.packageName))) {
8617 continue;
8618 }
8619 if (!printed) {
8620 if (needSep) pw.println(" ");
8621 needSep = true;
8622 pw.println(" Foreground Processes:");
8623 printed = true;
8624 }
8625 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8626 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008629 }
8630
8631 if (mPersistentStartingProcesses.size() > 0) {
8632 if (needSep) pw.println(" ");
8633 needSep = true;
8634 pw.println(" Persisent processes that are starting:");
8635 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008636 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008638
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008639 if (mRemovedProcesses.size() > 0) {
8640 if (needSep) pw.println(" ");
8641 needSep = true;
8642 pw.println(" Processes that are being removed:");
8643 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008644 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008645 }
8646
8647 if (mProcessesOnHold.size() > 0) {
8648 if (needSep) pw.println(" ");
8649 needSep = true;
8650 pw.println(" Processes that are on old until the system is ready:");
8651 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008652 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008655 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008656
8657 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008658 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008659 long now = SystemClock.uptimeMillis();
8660 for (Map.Entry<String, SparseArray<Long>> procs
8661 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008662 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008663 SparseArray<Long> uids = procs.getValue();
8664 final int N = uids.size();
8665 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008666 int puid = uids.keyAt(i);
8667 ProcessRecord r = mProcessNames.get(pname, puid);
8668 if (dumpPackage != null && (r == null
8669 || !dumpPackage.equals(r.info.packageName))) {
8670 continue;
8671 }
8672 if (!printed) {
8673 if (needSep) pw.println(" ");
8674 needSep = true;
8675 pw.println(" Time since processes crashed:");
8676 printed = true;
8677 }
8678 pw.print(" Process "); pw.print(pname);
8679 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008680 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008681 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8682 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008683 }
8684 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008687 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008688 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008689 for (Map.Entry<String, SparseArray<Long>> procs
8690 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008691 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008692 SparseArray<Long> uids = procs.getValue();
8693 final int N = uids.size();
8694 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008695 int puid = uids.keyAt(i);
8696 ProcessRecord r = mProcessNames.get(pname, puid);
8697 if (dumpPackage != null && (r == null
8698 || !dumpPackage.equals(r.info.packageName))) {
8699 continue;
8700 }
8701 if (!printed) {
8702 if (needSep) pw.println(" ");
8703 needSep = true;
8704 pw.println(" Bad processes:");
8705 }
8706 pw.print(" Bad process "); pw.print(pname);
8707 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008708 pw.print(": crashed at time ");
8709 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710 }
8711 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008714 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008715 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008716 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008717 if (dumpAll) {
8718 StringBuilder sb = new StringBuilder(128);
8719 sb.append(" mPreviousProcessVisibleTime: ");
8720 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8721 pw.println(sb);
8722 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008723 if (mHeavyWeightProcess != null) {
8724 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8725 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008726 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008727 if (dumpAll) {
8728 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008729 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008730 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008731 for (Map.Entry<String, Integer> entry
8732 : mCompatModePackages.getPackages().entrySet()) {
8733 String pkg = entry.getKey();
8734 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008735 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8736 continue;
8737 }
8738 if (!printed) {
8739 pw.println(" mScreenCompatPackages:");
8740 printed = true;
8741 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008742 pw.print(" "); pw.print(pkg); pw.print(": ");
8743 pw.print(mode); pw.println();
8744 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008745 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008746 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008747 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8748 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8749 || mOrigWaitForDebugger) {
8750 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8751 + " mDebugTransient=" + mDebugTransient
8752 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8753 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008754 if (mOpenGlTraceApp != null) {
8755 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8756 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008757 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8758 || mProfileFd != null) {
8759 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8760 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8761 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8762 + mAutoStopProfiler);
8763 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008764 if (mAlwaysFinishActivities || mController != null) {
8765 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8766 + " mController=" + mController);
8767 }
8768 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008771 + " mProcessesReady=" + mProcessesReady
8772 + " mSystemReady=" + mSystemReady);
8773 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 + " mBooted=" + mBooted
8775 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008776 pw.print(" mLastPowerCheckRealtime=");
8777 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8778 pw.println("");
8779 pw.print(" mLastPowerCheckUptime=");
8780 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8781 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008782 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8783 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008784 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008785 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8786 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008788
8789 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008790 }
8791
Dianne Hackborn287952c2010-09-22 22:34:31 -07008792 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008793 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008794 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008795 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008796 long now = SystemClock.uptimeMillis();
8797 for (int i=0; i<mProcessesToGc.size(); i++) {
8798 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008799 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8800 continue;
8801 }
8802 if (!printed) {
8803 if (needSep) pw.println(" ");
8804 needSep = true;
8805 pw.println(" Processes that are waiting to GC:");
8806 printed = true;
8807 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008808 pw.print(" Process "); pw.println(proc);
8809 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8810 pw.print(", last gced=");
8811 pw.print(now-proc.lastRequestedGc);
8812 pw.print(" ms ago, last lowMem=");
8813 pw.print(now-proc.lastLowMemory);
8814 pw.println(" ms ago");
8815
8816 }
8817 }
8818 return needSep;
8819 }
8820
8821 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8822 int opti, boolean dumpAll) {
8823 boolean needSep = false;
8824
8825 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008826 if (needSep) pw.println(" ");
8827 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008828 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008829 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008830 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008831 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8832 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8833 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8834 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8835 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008836 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008837 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008838 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008839 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008840 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008841 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008842
8843 if (needSep) pw.println(" ");
8844 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008845 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008846 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008847 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008848 needSep = true;
8849 }
8850
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008851 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008852
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008853 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008854 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008855 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008856 if (mHeavyWeightProcess != null) {
8857 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8858 }
8859
8860 return true;
8861 }
8862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008863 /**
8864 * There are three ways to call this:
8865 * - no service specified: dump all the services
8866 * - a flattened component name that matched an existing service was specified as the
8867 * first arg: dump that one service
8868 * - the first arg isn't the flattened component name of an existing service:
8869 * dump all services whose component contains the first arg as a substring
8870 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008871 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8872 int opti, boolean dumpAll) {
8873 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008874
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008875 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008876 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008877 try {
8878 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8879 for (UserInfo user : users) {
8880 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8881 services.add(r1);
8882 }
8883 }
8884 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008885 }
8886 }
8887 } else {
8888 ComponentName componentName = name != null
8889 ? ComponentName.unflattenFromString(name) : null;
8890 int objectId = 0;
8891 if (componentName == null) {
8892 // Not a '/' separated full component name; maybe an object ID?
8893 try {
8894 objectId = Integer.parseInt(name, 16);
8895 name = null;
8896 componentName = null;
8897 } catch (RuntimeException e) {
8898 }
8899 }
8900
8901 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008902 try {
8903 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8904 for (UserInfo user : users) {
8905 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8906 if (componentName != null) {
8907 if (r1.name.equals(componentName)) {
8908 services.add(r1);
8909 }
8910 } else if (name != null) {
8911 if (r1.name.flattenToString().contains(name)) {
8912 services.add(r1);
8913 }
8914 } else if (System.identityHashCode(r1) == objectId) {
8915 services.add(r1);
8916 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008917 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008918 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008919 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008920 }
8921 }
8922 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008923
8924 if (services.size() <= 0) {
8925 return false;
8926 }
8927
8928 boolean needSep = false;
8929 for (int i=0; i<services.size(); i++) {
8930 if (needSep) {
8931 pw.println();
8932 }
8933 needSep = true;
8934 dumpService("", fd, pw, services.get(i), args, dumpAll);
8935 }
8936 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008937 }
8938
8939 /**
8940 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8941 * there is a thread associated with the service.
8942 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008943 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8944 final ServiceRecord r, String[] args, boolean dumpAll) {
8945 String innerPrefix = prefix + " ";
8946 synchronized (this) {
8947 pw.print(prefix); pw.print("SERVICE ");
8948 pw.print(r.shortName); pw.print(" ");
8949 pw.print(Integer.toHexString(System.identityHashCode(r)));
8950 pw.print(" pid=");
8951 if (r.app != null) pw.println(r.app.pid);
8952 else pw.println("(not running)");
8953 if (dumpAll) {
8954 r.dump(pw, innerPrefix);
8955 }
8956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008958 pw.print(prefix); pw.println(" Client:");
8959 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008961 TransferPipe tp = new TransferPipe();
8962 try {
8963 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8964 tp.setBufferPrefix(prefix + " ");
8965 tp.go(fd);
8966 } finally {
8967 tp.kill();
8968 }
8969 } catch (IOException e) {
8970 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008971 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008972 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008973 }
8974 }
8975 }
8976
Marco Nelissen18cb2872011-11-15 11:19:53 -08008977 /**
8978 * There are three ways to call this:
8979 * - no provider specified: dump all the providers
8980 * - a flattened component name that matched an existing provider was specified as the
8981 * first arg: dump that one provider
8982 * - the first arg isn't the flattened component name of an existing provider:
8983 * dump all providers whose component contains the first arg as a substring
8984 */
8985 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8986 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008987 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008988 }
8989
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008990 static class ItemMatcher {
8991 ArrayList<ComponentName> components;
8992 ArrayList<String> strings;
8993 ArrayList<Integer> objects;
8994 boolean all;
8995
8996 ItemMatcher() {
8997 all = true;
8998 }
8999
9000 void build(String name) {
9001 ComponentName componentName = ComponentName.unflattenFromString(name);
9002 if (componentName != null) {
9003 if (components == null) {
9004 components = new ArrayList<ComponentName>();
9005 }
9006 components.add(componentName);
9007 all = false;
9008 } else {
9009 int objectId = 0;
9010 // Not a '/' separated full component name; maybe an object ID?
9011 try {
9012 objectId = Integer.parseInt(name, 16);
9013 if (objects == null) {
9014 objects = new ArrayList<Integer>();
9015 }
9016 objects.add(objectId);
9017 all = false;
9018 } catch (RuntimeException e) {
9019 // Not an integer; just do string match.
9020 if (strings == null) {
9021 strings = new ArrayList<String>();
9022 }
9023 strings.add(name);
9024 all = false;
9025 }
9026 }
9027 }
9028
9029 int build(String[] args, int opti) {
9030 for (; opti<args.length; opti++) {
9031 String name = args[opti];
9032 if ("--".equals(name)) {
9033 return opti+1;
9034 }
9035 build(name);
9036 }
9037 return opti;
9038 }
9039
9040 boolean match(Object object, ComponentName comp) {
9041 if (all) {
9042 return true;
9043 }
9044 if (components != null) {
9045 for (int i=0; i<components.size(); i++) {
9046 if (components.get(i).equals(comp)) {
9047 return true;
9048 }
9049 }
9050 }
9051 if (objects != null) {
9052 for (int i=0; i<objects.size(); i++) {
9053 if (System.identityHashCode(object) == objects.get(i)) {
9054 return true;
9055 }
9056 }
9057 }
9058 if (strings != null) {
9059 String flat = comp.flattenToString();
9060 for (int i=0; i<strings.size(); i++) {
9061 if (flat.contains(strings.get(i))) {
9062 return true;
9063 }
9064 }
9065 }
9066 return false;
9067 }
9068 }
9069
Dianne Hackborn625ac272010-09-17 18:29:22 -07009070 /**
9071 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009072 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009073 * - the cmd arg isn't the flattened component name of an existing activity:
9074 * dump all activity whose component contains the cmd as a substring
9075 * - A hex number of the ActivityRecord object instance.
9076 */
9077 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9078 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009079 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009080
9081 if ("all".equals(name)) {
9082 synchronized (this) {
9083 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009084 activities.add(r1);
9085 }
9086 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009087 } else if ("top".equals(name)) {
9088 synchronized (this) {
9089 final int N = mMainStack.mHistory.size();
9090 if (N > 0) {
9091 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9092 }
9093 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009094 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009095 ItemMatcher matcher = new ItemMatcher();
9096 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009097
9098 synchronized (this) {
9099 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009100 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009101 activities.add(r1);
9102 }
9103 }
9104 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009105 }
9106
9107 if (activities.size() <= 0) {
9108 return false;
9109 }
9110
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009111 String[] newArgs = new String[args.length - opti];
9112 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9113
Dianne Hackborn30d71892010-12-11 10:37:55 -08009114 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009115 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009116 for (int i=activities.size()-1; i>=0; i--) {
9117 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009118 if (needSep) {
9119 pw.println();
9120 }
9121 needSep = true;
9122 synchronized (this) {
9123 if (lastTask != r.task) {
9124 lastTask = r.task;
9125 pw.print("TASK "); pw.print(lastTask.affinity);
9126 pw.print(" id="); pw.println(lastTask.taskId);
9127 if (dumpAll) {
9128 lastTask.dump(pw, " ");
9129 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009130 }
9131 }
9132 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009133 }
9134 return true;
9135 }
9136
9137 /**
9138 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9139 * there is a thread associated with the activity.
9140 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009141 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009142 final ActivityRecord r, String[] args, boolean dumpAll) {
9143 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009144 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009145 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9146 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9147 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009148 if (r.app != null) pw.println(r.app.pid);
9149 else pw.println("(not running)");
9150 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009151 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009152 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009153 }
9154 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009155 // flush anything that is already in the PrintWriter since the thread is going
9156 // to write to the file descriptor directly
9157 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009158 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009159 TransferPipe tp = new TransferPipe();
9160 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009161 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9162 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009163 tp.go(fd);
9164 } finally {
9165 tp.kill();
9166 }
9167 } catch (IOException e) {
9168 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009169 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009170 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009171 }
9172 }
9173 }
9174
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009175 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009176 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009177 boolean needSep = false;
9178
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009179 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009180 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009182 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009183 Iterator it = mRegisteredReceivers.values().iterator();
9184 while (it.hasNext()) {
9185 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009186 if (dumpPackage != null && (r.app == null ||
9187 !dumpPackage.equals(r.app.info.packageName))) {
9188 continue;
9189 }
9190 if (!printed) {
9191 pw.println(" Registered Receivers:");
9192 needSep = true;
9193 printed = true;
9194 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009195 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009196 r.dump(pw, " ");
9197 }
9198 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009199
9200 if (mReceiverResolver.dump(pw, needSep ?
9201 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9202 " ", dumpPackage, false)) {
9203 needSep = true;
9204 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009205 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009206
9207 for (BroadcastQueue q : mBroadcastQueues) {
9208 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009210
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009211 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009212
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009213 if (mStickyBroadcasts != null && dumpPackage == null) {
9214 if (needSep) {
9215 pw.println();
9216 }
9217 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009218 pw.println(" Sticky broadcasts:");
9219 StringBuilder sb = new StringBuilder(128);
9220 for (Map.Entry<String, ArrayList<Intent>> ent
9221 : mStickyBroadcasts.entrySet()) {
9222 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009223 if (dumpAll) {
9224 pw.println(":");
9225 ArrayList<Intent> intents = ent.getValue();
9226 final int N = intents.size();
9227 for (int i=0; i<N; i++) {
9228 sb.setLength(0);
9229 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009230 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009231 pw.println(sb.toString());
9232 Bundle bundle = intents.get(i).getExtras();
9233 if (bundle != null) {
9234 pw.print(" ");
9235 pw.println(bundle.toString());
9236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009237 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009238 } else {
9239 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009240 }
9241 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009242 needSep = true;
9243 }
9244
9245 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009246 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009247 for (BroadcastQueue queue : mBroadcastQueues) {
9248 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9249 + queue.mBroadcastsScheduled);
9250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009251 pw.println(" mHandler:");
9252 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009253 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009254 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009255
9256 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009257 }
9258
Marco Nelissen18cb2872011-11-15 11:19:53 -08009259 /**
9260 * Prints a list of ServiceRecords (dumpsys activity services)
9261 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009262 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009263 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009264 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009265
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009266 ItemMatcher matcher = new ItemMatcher();
9267 matcher.build(args, opti);
9268
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009269 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009270 try {
9271 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9272 for (UserInfo user : users) {
9273 if (mServiceMap.getAllServices(user.id).size() > 0) {
9274 boolean printed = false;
9275 long nowReal = SystemClock.elapsedRealtime();
9276 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9277 user.id).iterator();
9278 needSep = false;
9279 while (it.hasNext()) {
9280 ServiceRecord r = it.next();
9281 if (!matcher.match(r, r.name)) {
9282 continue;
9283 }
9284 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9285 continue;
9286 }
9287 if (!printed) {
9288 pw.println(" Active services:");
9289 printed = true;
9290 }
9291 if (needSep) {
9292 pw.println();
9293 }
9294 pw.print(" * ");
9295 pw.println(r);
9296 if (dumpAll) {
9297 r.dump(pw, " ");
9298 needSep = true;
9299 } else {
9300 pw.print(" app=");
9301 pw.println(r.app);
9302 pw.print(" created=");
9303 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9304 pw.print(" started=");
9305 pw.print(r.startRequested);
9306 pw.print(" connections=");
9307 pw.println(r.connections.size());
9308 if (r.connections.size() > 0) {
9309 pw.println(" Connections:");
9310 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9311 for (int i = 0; i < clist.size(); i++) {
9312 ConnectionRecord conn = clist.get(i);
9313 pw.print(" ");
9314 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009315 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009316 pw.print(" -> ");
9317 ProcessRecord proc = conn.binding.client;
9318 pw.println(proc != null ? proc.toShortString() : "null");
9319 }
9320 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009321 }
9322 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009323 if (dumpClient && r.app != null && r.app.thread != null) {
9324 pw.println(" Client:");
9325 pw.flush();
9326 try {
9327 TransferPipe tp = new TransferPipe();
9328 try {
9329 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9330 r, args);
9331 tp.setBufferPrefix(" ");
9332 // Short timeout, since blocking here can
9333 // deadlock with the application.
9334 tp.go(fd, 2000);
9335 } finally {
9336 tp.kill();
9337 }
9338 } catch (IOException e) {
9339 pw.println(" Failure while dumping the service: " + e);
9340 } catch (RemoteException e) {
9341 pw.println(" Got a RemoteException while dumping the service");
9342 }
9343 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009344 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009345 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009346 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009348 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009349 } catch (RemoteException re) {
9350
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009353 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009354 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009355 for (int i=0; i<mPendingServices.size(); i++) {
9356 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009357 if (!matcher.match(r, r.name)) {
9358 continue;
9359 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009360 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9361 continue;
9362 }
9363 if (!printed) {
9364 if (needSep) pw.println(" ");
9365 needSep = true;
9366 pw.println(" Pending services:");
9367 printed = true;
9368 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009369 pw.print(" * Pending "); pw.println(r);
9370 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009371 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009372 needSep = true;
9373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009374
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009375 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009376 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009377 for (int i=0; i<mRestartingServices.size(); i++) {
9378 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009379 if (!matcher.match(r, r.name)) {
9380 continue;
9381 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009382 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9383 continue;
9384 }
9385 if (!printed) {
9386 if (needSep) pw.println(" ");
9387 needSep = true;
9388 pw.println(" Restarting services:");
9389 printed = true;
9390 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009391 pw.print(" * Restarting "); pw.println(r);
9392 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009393 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009394 needSep = true;
9395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009396
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009397 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009398 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009399 for (int i=0; i<mStoppingServices.size(); i++) {
9400 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009401 if (!matcher.match(r, r.name)) {
9402 continue;
9403 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009404 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9405 continue;
9406 }
9407 if (!printed) {
9408 if (needSep) pw.println(" ");
9409 needSep = true;
9410 pw.println(" Stopping services:");
9411 printed = true;
9412 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009413 pw.print(" * Stopping "); pw.println(r);
9414 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009415 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009416 needSep = true;
9417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009418
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009419 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009420 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009421 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009422 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423 = mServiceConnections.values().iterator();
9424 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009425 ArrayList<ConnectionRecord> r = it.next();
9426 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009427 ConnectionRecord cr = r.get(i);
9428 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9429 continue;
9430 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009431 if (dumpPackage != null && (cr.binding.client == null
9432 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9433 continue;
9434 }
9435 if (!printed) {
9436 if (needSep) pw.println(" ");
9437 needSep = true;
9438 pw.println(" Connection bindings to services:");
9439 printed = true;
9440 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009441 pw.print(" * "); pw.println(cr);
9442 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009444 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009445 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009446 }
9447 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009448
9449 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009450 }
9451
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009452 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009453 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009454 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009455
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009456 ItemMatcher matcher = new ItemMatcher();
9457 matcher.build(args, opti);
9458
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009459 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009460
9461 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009462
9463 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009464 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009465 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009466 ContentProviderRecord r = mLaunchingProviders.get(i);
9467 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9468 continue;
9469 }
9470 if (!printed) {
9471 if (needSep) pw.println(" ");
9472 needSep = true;
9473 pw.println(" Launching content providers:");
9474 printed = true;
9475 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009476 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009477 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009478 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009479 }
9480
9481 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009482 if (needSep) pw.println();
9483 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009484 pw.println("Granted Uri Permissions:");
9485 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9486 int uid = mGrantedUriPermissions.keyAt(i);
9487 HashMap<Uri, UriPermission> perms
9488 = mGrantedUriPermissions.valueAt(i);
9489 pw.print(" * UID "); pw.print(uid);
9490 pw.println(" holds:");
9491 for (UriPermission perm : perms.values()) {
9492 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009493 if (dumpAll) {
9494 perm.dump(pw, " ");
9495 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009496 }
9497 }
9498 needSep = true;
9499 }
9500
9501 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009502 }
9503
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009504 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009505 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009506 boolean needSep = false;
9507
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009508 if (mIntentSenderRecords.size() > 0) {
9509 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009510 Iterator<WeakReference<PendingIntentRecord>> it
9511 = mIntentSenderRecords.values().iterator();
9512 while (it.hasNext()) {
9513 WeakReference<PendingIntentRecord> ref = it.next();
9514 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009515 if (dumpPackage != null && (rec == null
9516 || !dumpPackage.equals(rec.key.packageName))) {
9517 continue;
9518 }
9519 if (!printed) {
9520 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9521 printed = true;
9522 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009523 needSep = true;
9524 if (rec != null) {
9525 pw.print(" * "); pw.println(rec);
9526 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009527 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009528 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009529 } else {
9530 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009531 }
9532 }
9533 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009534
9535 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009536 }
9537
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009538 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009539 String prefix, String label, boolean complete, boolean brief, boolean client,
9540 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009541 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009542 boolean needNL = false;
9543 final String innerPrefix = prefix + " ";
9544 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009545 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009546 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009547 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9548 continue;
9549 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009550 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009551 if (needNL) {
9552 pw.println(" ");
9553 needNL = false;
9554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009555 if (lastTask != r.task) {
9556 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009557 pw.print(prefix);
9558 pw.print(full ? "* " : " ");
9559 pw.println(lastTask);
9560 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009561 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009562 } else if (complete) {
9563 // Complete + brief == give a summary. Isn't that obvious?!?
9564 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009565 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009566 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009567 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009570 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9571 pw.print(" #"); pw.print(i); pw.print(": ");
9572 pw.println(r);
9573 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009574 r.dump(pw, innerPrefix);
9575 } else if (complete) {
9576 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009577 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009578 if (r.app != null) {
9579 pw.print(innerPrefix); pw.println(r.app);
9580 }
9581 }
9582 if (client && r.app != null && r.app.thread != null) {
9583 // flush anything that is already in the PrintWriter since the thread is going
9584 // to write to the file descriptor directly
9585 pw.flush();
9586 try {
9587 TransferPipe tp = new TransferPipe();
9588 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009589 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9590 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009591 // Short timeout, since blocking here can
9592 // deadlock with the application.
9593 tp.go(fd, 2000);
9594 } finally {
9595 tp.kill();
9596 }
9597 } catch (IOException e) {
9598 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9599 } catch (RemoteException e) {
9600 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9601 }
9602 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009604 }
9605 }
9606
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009607 private static String buildOomTag(String prefix, String space, int val, int base) {
9608 if (val == base) {
9609 if (space == null) return prefix;
9610 return prefix + " ";
9611 }
9612 return prefix + "+" + Integer.toString(val-base);
9613 }
9614
9615 private static final int dumpProcessList(PrintWriter pw,
9616 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009617 String prefix, String normalLabel, String persistentLabel,
9618 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009619 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009620 final int N = list.size()-1;
9621 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009622 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009623 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9624 continue;
9625 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009626 pw.println(String.format("%s%s #%2d: %s",
9627 prefix, (r.persistent ? persistentLabel : normalLabel),
9628 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009629 if (r.persistent) {
9630 numPers++;
9631 }
9632 }
9633 return numPers;
9634 }
9635
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009636 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009637 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009638 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009639 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009640
Dianne Hackborn905577f2011-09-07 18:31:28 -07009641 ArrayList<Pair<ProcessRecord, Integer>> list
9642 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9643 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009644 ProcessRecord r = origList.get(i);
9645 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9646 continue;
9647 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009648 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9649 }
9650
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009651 if (list.size() <= 0) {
9652 return false;
9653 }
9654
Dianne Hackborn905577f2011-09-07 18:31:28 -07009655 Comparator<Pair<ProcessRecord, Integer>> comparator
9656 = new Comparator<Pair<ProcessRecord, Integer>>() {
9657 @Override
9658 public int compare(Pair<ProcessRecord, Integer> object1,
9659 Pair<ProcessRecord, Integer> object2) {
9660 if (object1.first.setAdj != object2.first.setAdj) {
9661 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9662 }
9663 if (object1.second.intValue() != object2.second.intValue()) {
9664 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9665 }
9666 return 0;
9667 }
9668 };
9669
9670 Collections.sort(list, comparator);
9671
Dianne Hackborn287952c2010-09-22 22:34:31 -07009672 final long curRealtime = SystemClock.elapsedRealtime();
9673 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9674 final long curUptime = SystemClock.uptimeMillis();
9675 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9676
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009677 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009678 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009679 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009680 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009681 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009682 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9683 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009684 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9685 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009686 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9687 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009688 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9689 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009690 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009691 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009692 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9693 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9694 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9695 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9696 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9697 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9698 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9699 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009700 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9701 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009702 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9703 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009704 } else {
9705 oomAdj = Integer.toString(r.setAdj);
9706 }
9707 String schedGroup;
9708 switch (r.setSchedGroup) {
9709 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9710 schedGroup = "B";
9711 break;
9712 case Process.THREAD_GROUP_DEFAULT:
9713 schedGroup = "F";
9714 break;
9715 default:
9716 schedGroup = Integer.toString(r.setSchedGroup);
9717 break;
9718 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009719 String foreground;
9720 if (r.foregroundActivities) {
9721 foreground = "A";
9722 } else if (r.foregroundServices) {
9723 foreground = "S";
9724 } else {
9725 foreground = " ";
9726 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009727 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009728 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009729 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9730 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009731 if (r.adjSource != null || r.adjTarget != null) {
9732 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009733 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009734 if (r.adjTarget instanceof ComponentName) {
9735 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9736 } else if (r.adjTarget != null) {
9737 pw.print(r.adjTarget.toString());
9738 } else {
9739 pw.print("{null}");
9740 }
9741 pw.print("<=");
9742 if (r.adjSource instanceof ProcessRecord) {
9743 pw.print("Proc{");
9744 pw.print(((ProcessRecord)r.adjSource).toShortString());
9745 pw.println("}");
9746 } else if (r.adjSource != null) {
9747 pw.println(r.adjSource.toString());
9748 } else {
9749 pw.println("{null}");
9750 }
9751 }
9752 if (inclDetails) {
9753 pw.print(prefix);
9754 pw.print(" ");
9755 pw.print("oom: max="); pw.print(r.maxAdj);
9756 pw.print(" hidden="); pw.print(r.hiddenAdj);
9757 pw.print(" curRaw="); pw.print(r.curRawAdj);
9758 pw.print(" setRaw="); pw.print(r.setRawAdj);
9759 pw.print(" cur="); pw.print(r.curAdj);
9760 pw.print(" set="); pw.println(r.setAdj);
9761 pw.print(prefix);
9762 pw.print(" ");
9763 pw.print("keeping="); pw.print(r.keeping);
9764 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009765 pw.print(" empty="); pw.print(r.empty);
9766 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009767
9768 if (!r.keeping) {
9769 if (r.lastWakeTime != 0) {
9770 long wtime;
9771 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9772 synchronized (stats) {
9773 wtime = stats.getProcessWakeTime(r.info.uid,
9774 r.pid, curRealtime);
9775 }
9776 long timeUsed = wtime - r.lastWakeTime;
9777 pw.print(prefix);
9778 pw.print(" ");
9779 pw.print("keep awake over ");
9780 TimeUtils.formatDuration(realtimeSince, pw);
9781 pw.print(" used ");
9782 TimeUtils.formatDuration(timeUsed, pw);
9783 pw.print(" (");
9784 pw.print((timeUsed*100)/realtimeSince);
9785 pw.println("%)");
9786 }
9787 if (r.lastCpuTime != 0) {
9788 long timeUsed = r.curCpuTime - r.lastCpuTime;
9789 pw.print(prefix);
9790 pw.print(" ");
9791 pw.print("run cpu over ");
9792 TimeUtils.formatDuration(uptimeSince, pw);
9793 pw.print(" used ");
9794 TimeUtils.formatDuration(timeUsed, pw);
9795 pw.print(" (");
9796 pw.print((timeUsed*100)/uptimeSince);
9797 pw.println("%)");
9798 }
9799 }
9800 }
9801 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009802 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009803 }
9804
Dianne Hackbornb437e092011-08-05 17:50:29 -07009805 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009806 ArrayList<ProcessRecord> procs;
9807 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009808 if (args != null && args.length > start
9809 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009810 procs = new ArrayList<ProcessRecord>();
9811 int pid = -1;
9812 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009813 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009814 } catch (NumberFormatException e) {
9815
9816 }
9817 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9818 ProcessRecord proc = mLruProcesses.get(i);
9819 if (proc.pid == pid) {
9820 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009821 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009822 procs.add(proc);
9823 }
9824 }
9825 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009826 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009827 return null;
9828 }
9829 } else {
9830 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9831 }
9832 }
9833 return procs;
9834 }
9835
9836 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9837 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009838 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009839 if (procs == null) {
9840 return;
9841 }
9842
9843 long uptime = SystemClock.uptimeMillis();
9844 long realtime = SystemClock.elapsedRealtime();
9845 pw.println("Applications Graphics Acceleration Info:");
9846 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9847
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009848 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9849 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009850 if (r.thread != null) {
9851 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9852 pw.flush();
9853 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009854 TransferPipe tp = new TransferPipe();
9855 try {
9856 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9857 tp.go(fd);
9858 } finally {
9859 tp.kill();
9860 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009861 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009862 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009863 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009864 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009865 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009866 pw.flush();
9867 }
9868 }
9869 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009870 }
9871
Jeff Brown6754ba22011-12-14 20:20:01 -08009872 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9873 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9874 if (procs == null) {
9875 return;
9876 }
9877
9878 pw.println("Applications Database Info:");
9879
9880 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9881 ProcessRecord r = procs.get(i);
9882 if (r.thread != null) {
9883 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9884 pw.flush();
9885 try {
9886 TransferPipe tp = new TransferPipe();
9887 try {
9888 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9889 tp.go(fd);
9890 } finally {
9891 tp.kill();
9892 }
9893 } catch (IOException e) {
9894 pw.println("Failure while dumping the app: " + r);
9895 pw.flush();
9896 } catch (RemoteException e) {
9897 pw.println("Got a RemoteException while dumping the app " + r);
9898 pw.flush();
9899 }
9900 }
9901 }
9902 }
9903
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009904 final static class MemItem {
9905 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009906 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009907 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009908 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009909 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009910
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009911 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009912 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009913 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009914 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009915 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009916 }
9917 }
9918
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009919 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009920 boolean sort) {
9921 if (sort) {
9922 Collections.sort(items, new Comparator<MemItem>() {
9923 @Override
9924 public int compare(MemItem lhs, MemItem rhs) {
9925 if (lhs.pss < rhs.pss) {
9926 return 1;
9927 } else if (lhs.pss > rhs.pss) {
9928 return -1;
9929 }
9930 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009931 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009932 });
9933 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009934
9935 for (int i=0; i<items.size(); i++) {
9936 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009937 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009938 if (mi.subitems != null) {
9939 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9940 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009941 }
9942 }
9943
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009944 // These are in KB.
9945 static final long[] DUMP_MEM_BUCKETS = new long[] {
9946 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9947 120*1024, 160*1024, 200*1024,
9948 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9949 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9950 };
9951
Dianne Hackborn672342c2011-11-29 11:29:02 -08009952 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9953 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009954 int start = label.lastIndexOf('.');
9955 if (start >= 0) start++;
9956 else start = 0;
9957 int end = label.length();
9958 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9959 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9960 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9961 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009962 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009963 out.append(label, start, end);
9964 return;
9965 }
9966 }
9967 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009968 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009969 out.append(label, start, end);
9970 }
9971
9972 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9973 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9974 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9975 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9976 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9977 };
9978 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9979 "System", "Persistent", "Foreground",
9980 "Visible", "Perceptible", "Heavy Weight",
9981 "Backup", "A Services", "Home", "Previous",
9982 "B Services", "Background"
9983 };
9984
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009985 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009986 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009987 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009988 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009989 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009990
9991 int opti = 0;
9992 while (opti < args.length) {
9993 String opt = args[opti];
9994 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9995 break;
9996 }
9997 opti++;
9998 if ("-a".equals(opt)) {
9999 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010000 } else if ("--oom".equals(opt)) {
10001 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010002 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010003 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010004 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010005 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010006 pw.println("If [process] is specified it can be the name or ");
10007 pw.println("pid of a specific process to dump.");
10008 return;
10009 } else {
10010 pw.println("Unknown argument: " + opt + "; use -h for help");
10011 }
10012 }
10013
10014 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010015 if (procs == null) {
10016 return;
10017 }
10018
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010019 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010020 long uptime = SystemClock.uptimeMillis();
10021 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010022
10023 if (procs.size() == 1 || isCheckinRequest) {
10024 dumpAll = true;
10025 }
10026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010027 if (isCheckinRequest) {
10028 // short checkin version
10029 pw.println(uptime + "," + realtime);
10030 pw.flush();
10031 } else {
10032 pw.println("Applications Memory Usage (kB):");
10033 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10034 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010035
Dianne Hackbornb437e092011-08-05 17:50:29 -070010036 String[] innerArgs = new String[args.length-opti];
10037 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10038
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010039 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10040 long nativePss=0, dalvikPss=0, otherPss=0;
10041 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10042
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010043 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10044 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10045 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010046
10047 long totalPss = 0;
10048
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010049 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10050 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010051 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010052 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010053 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10054 pw.flush();
10055 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010056 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010057 if (dumpAll) {
10058 try {
10059 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10060 } catch (RemoteException e) {
10061 if (!isCheckinRequest) {
10062 pw.println("Got RemoteException!");
10063 pw.flush();
10064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010065 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010066 } else {
10067 mi = new Debug.MemoryInfo();
10068 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010069 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010070
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010071 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010072 long myTotalPss = mi.getTotalPss();
10073 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010074 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010075 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010076 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010077
10078 nativePss += mi.nativePss;
10079 dalvikPss += mi.dalvikPss;
10080 otherPss += mi.otherPss;
10081 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10082 long mem = mi.getOtherPss(j);
10083 miscPss[j] += mem;
10084 otherPss -= mem;
10085 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010086
10087 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010088 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10089 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010090 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010091 if (oomProcs[oomIndex] == null) {
10092 oomProcs[oomIndex] = new ArrayList<MemItem>();
10093 }
10094 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010095 break;
10096 }
10097 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010099 }
10100 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010101
10102 if (!isCheckinRequest && procs.size() > 1) {
10103 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10104
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010105 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10106 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10107 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010108 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010109 String label = Debug.MemoryInfo.getOtherLabel(j);
10110 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010111 }
10112
Dianne Hackbornb437e092011-08-05 17:50:29 -070010113 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10114 for (int j=0; j<oomPss.length; j++) {
10115 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010116 String label = DUMP_MEM_OOM_LABEL[j];
10117 MemItem item = new MemItem(label, label, oomPss[j],
10118 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010119 item.subitems = oomProcs[j];
10120 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010121 }
10122 }
10123
Dianne Hackborn672342c2011-11-29 11:29:02 -080010124 if (outTag != null || outStack != null) {
10125 if (outTag != null) {
10126 appendMemBucket(outTag, totalPss, "total", false);
10127 }
10128 if (outStack != null) {
10129 appendMemBucket(outStack, totalPss, "total", true);
10130 }
10131 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010132 for (int i=0; i<oomMems.size(); i++) {
10133 MemItem miCat = oomMems.get(i);
10134 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10135 continue;
10136 }
10137 if (miCat.id < ProcessList.SERVICE_ADJ
10138 || miCat.id == ProcessList.HOME_APP_ADJ
10139 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010140 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10141 outTag.append(" / ");
10142 }
10143 if (outStack != null) {
10144 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10145 if (firstLine) {
10146 outStack.append(":");
10147 firstLine = false;
10148 }
10149 outStack.append("\n\t at ");
10150 } else {
10151 outStack.append("$");
10152 }
10153 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010154 for (int j=0; j<miCat.subitems.size(); j++) {
10155 MemItem mi = miCat.subitems.get(j);
10156 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010157 if (outTag != null) {
10158 outTag.append(" ");
10159 }
10160 if (outStack != null) {
10161 outStack.append("$");
10162 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010163 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010164 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10165 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10166 }
10167 if (outStack != null) {
10168 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10169 }
10170 }
10171 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10172 outStack.append("(");
10173 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10174 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10175 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10176 outStack.append(":");
10177 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10178 }
10179 }
10180 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010181 }
10182 }
10183 }
10184 }
10185
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010186 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010187 pw.println();
10188 pw.println("Total PSS by process:");
10189 dumpMemItems(pw, " ", procMems, true);
10190 pw.println();
10191 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010192 pw.println("Total PSS by OOM adjustment:");
10193 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010194 if (!oomOnly) {
10195 PrintWriter out = categoryPw != null ? categoryPw : pw;
10196 out.println();
10197 out.println("Total PSS by category:");
10198 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010199 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010200 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010201 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010203 }
10204
10205 /**
10206 * Searches array of arguments for the specified string
10207 * @param args array of argument strings
10208 * @param value value to search for
10209 * @return true if the value is contained in the array
10210 */
10211 private static boolean scanArgs(String[] args, String value) {
10212 if (args != null) {
10213 for (String arg : args) {
10214 if (value.equals(arg)) {
10215 return true;
10216 }
10217 }
10218 }
10219 return false;
10220 }
10221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010222 private final void killServicesLocked(ProcessRecord app,
10223 boolean allowRestart) {
10224 // Report disconnected services.
10225 if (false) {
10226 // XXX we are letting the client link to the service for
10227 // death notifications.
10228 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010229 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010230 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010231 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010232 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010233 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010234 = r.connections.values().iterator();
10235 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010236 ArrayList<ConnectionRecord> cl = jt.next();
10237 for (int i=0; i<cl.size(); i++) {
10238 ConnectionRecord c = cl.get(i);
10239 if (c.binding.client != app) {
10240 try {
10241 //c.conn.connected(r.className, null);
10242 } catch (Exception e) {
10243 // todo: this should be asynchronous!
10244 Slog.w(TAG, "Exception thrown disconnected servce "
10245 + r.shortName
10246 + " from app " + app.processName, e);
10247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010248 }
10249 }
10250 }
10251 }
10252 }
10253 }
10254 }
10255
10256 // Clean up any connections this application has to other services.
10257 if (app.connections.size() > 0) {
10258 Iterator<ConnectionRecord> it = app.connections.iterator();
10259 while (it.hasNext()) {
10260 ConnectionRecord r = it.next();
10261 removeConnectionLocked(r, app, null);
10262 }
10263 }
10264 app.connections.clear();
10265
10266 if (app.services.size() != 0) {
10267 // Any services running in the application need to be placed
10268 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010269 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010270 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010271 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010272 synchronized (sr.stats.getBatteryStats()) {
10273 sr.stats.stopLaunchedLocked();
10274 }
10275 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010276 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010277 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010278 if (mStoppingServices.remove(sr)) {
10279 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10280 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010281
10282 boolean hasClients = sr.bindings.size() > 0;
10283 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010284 Iterator<IntentBindRecord> bindings
10285 = sr.bindings.values().iterator();
10286 while (bindings.hasNext()) {
10287 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010288 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010289 + ": shouldUnbind=" + b.hasBound);
10290 b.binder = null;
10291 b.requested = b.received = b.hasBound = false;
10292 }
10293 }
10294
Dianne Hackborn070783f2010-12-29 16:46:28 -080010295 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10296 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010297 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010298 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010299 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010300 sr.crashCount, sr.shortName, app.pid);
10301 bringDownServiceLocked(sr, true);
10302 } else if (!allowRestart) {
10303 bringDownServiceLocked(sr, true);
10304 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010305 boolean canceled = scheduleServiceRestartLocked(sr, true);
10306
10307 // Should the service remain running? Note that in the
10308 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010309 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010310 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10311 if (sr.pendingStarts.size() == 0) {
10312 sr.startRequested = false;
10313 if (!hasClients) {
10314 // Whoops, no reason to restart!
10315 bringDownServiceLocked(sr, true);
10316 }
10317 }
10318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010319 }
10320 }
10321
10322 if (!allowRestart) {
10323 app.services.clear();
10324 }
10325 }
10326
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010327 // Make sure we have no more records on the stopping list.
10328 int i = mStoppingServices.size();
10329 while (i > 0) {
10330 i--;
10331 ServiceRecord sr = mStoppingServices.get(i);
10332 if (sr.app == app) {
10333 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010334 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010335 }
10336 }
10337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010338 app.executingServices.clear();
10339 }
10340
10341 private final void removeDyingProviderLocked(ProcessRecord proc,
10342 ContentProviderRecord cpr) {
10343 synchronized (cpr) {
10344 cpr.launchingApp = null;
10345 cpr.notifyAll();
10346 }
10347
Amith Yamasani742a6712011-05-04 14:49:28 -070010348 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010349 String names[] = cpr.info.authority.split(";");
10350 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010351 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010352 }
10353
10354 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10355 while (cit.hasNext()) {
10356 ProcessRecord capp = cit.next();
10357 if (!capp.persistent && capp.thread != null
10358 && capp.pid != 0
10359 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010360 Slog.i(TAG, "Kill " + capp.processName
10361 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010362 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010363 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010364 capp.processName, capp.setAdj, "dying provider "
10365 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010366 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010367 }
10368 }
10369
10370 mLaunchingProviders.remove(cpr);
10371 }
10372
10373 /**
10374 * Main code for cleaning up a process when it has gone away. This is
10375 * called both as a result of the process dying, or directly when stopping
10376 * a process when running in single process mode.
10377 */
10378 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010379 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010380 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010381 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010382 }
10383
Dianne Hackborn36124872009-10-08 16:22:03 -070010384 mProcessesToGc.remove(app);
10385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010386 // Dismiss any open dialogs.
10387 if (app.crashDialog != null) {
10388 app.crashDialog.dismiss();
10389 app.crashDialog = null;
10390 }
10391 if (app.anrDialog != null) {
10392 app.anrDialog.dismiss();
10393 app.anrDialog = null;
10394 }
10395 if (app.waitDialog != null) {
10396 app.waitDialog.dismiss();
10397 app.waitDialog = null;
10398 }
10399
10400 app.crashing = false;
10401 app.notResponding = false;
10402
10403 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010404 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010405 app.thread = null;
10406 app.forcingToForeground = null;
10407 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010408 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010409 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010410 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010411
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010412 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010413
10414 boolean restart = false;
10415
10416 int NL = mLaunchingProviders.size();
10417
10418 // Remove published content providers.
10419 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010420 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010421 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010422 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010423 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010424 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010425
10426 // See if someone is waiting for this provider... in which
10427 // case we don't remove it, but just let it restart.
10428 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010429 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010430 for (; i<NL; i++) {
10431 if (mLaunchingProviders.get(i) == cpr) {
10432 restart = true;
10433 break;
10434 }
10435 }
10436 } else {
10437 i = NL;
10438 }
10439
10440 if (i >= NL) {
10441 removeDyingProviderLocked(app, cpr);
10442 NL = mLaunchingProviders.size();
10443 }
10444 }
10445 app.pubProviders.clear();
10446 }
10447
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010448 // Take care of any launching providers waiting for this process.
10449 if (checkAppInLaunchingProvidersLocked(app, false)) {
10450 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010451 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010453 // Unregister from connected content providers.
10454 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010455 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010456 while (it.hasNext()) {
10457 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10458 cpr.clients.remove(app);
10459 }
10460 app.conProviders.clear();
10461 }
10462
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010463 // At this point there may be remaining entries in mLaunchingProviders
10464 // where we were the only one waiting, so they are no longer of use.
10465 // Look for these and clean up if found.
10466 // XXX Commented out for now. Trying to figure out a way to reproduce
10467 // the actual situation to identify what is actually going on.
10468 if (false) {
10469 for (int i=0; i<NL; i++) {
10470 ContentProviderRecord cpr = (ContentProviderRecord)
10471 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010472 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010473 synchronized (cpr) {
10474 cpr.launchingApp = null;
10475 cpr.notifyAll();
10476 }
10477 }
10478 }
10479 }
10480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010481 skipCurrentReceiverLocked(app);
10482
10483 // Unregister any receivers.
10484 if (app.receivers.size() > 0) {
10485 Iterator<ReceiverList> it = app.receivers.iterator();
10486 while (it.hasNext()) {
10487 removeReceiverLocked(it.next());
10488 }
10489 app.receivers.clear();
10490 }
10491
Christopher Tate181fafa2009-05-14 11:12:14 -070010492 // If the app is undergoing backup, tell the backup manager about it
10493 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010494 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010495 try {
10496 IBackupManager bm = IBackupManager.Stub.asInterface(
10497 ServiceManager.getService(Context.BACKUP_SERVICE));
10498 bm.agentDisconnected(app.info.packageName);
10499 } catch (RemoteException e) {
10500 // can't happen; backup manager is local
10501 }
10502 }
10503
Jeff Sharkey287bd832011-05-28 19:36:26 -070010504 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010506 // If the caller is restarting this app, then leave it in its
10507 // current lists and let the caller take care of it.
10508 if (restarting) {
10509 return;
10510 }
10511
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010512 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010513 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010515 mProcessNames.remove(app.processName, app.uid);
10516 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010517 if (mHeavyWeightProcess == app) {
10518 mHeavyWeightProcess = null;
10519 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010521 } else if (!app.removed) {
10522 // This app is persistent, so we need to keep its record around.
10523 // If it is not already on the pending app list, add it there
10524 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010525 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10526 mPersistentStartingProcesses.add(app);
10527 restart = true;
10528 }
10529 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010530 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10531 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010532 mProcessesOnHold.remove(app);
10533
The Android Open Source Project4df24232009-03-05 14:34:35 -080010534 if (app == mHomeProcess) {
10535 mHomeProcess = null;
10536 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010537 if (app == mPreviousProcess) {
10538 mPreviousProcess = null;
10539 }
10540
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010541 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 // We have components that still need to be running in the
10543 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010544 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010545 startProcessLocked(app, "restart", app.processName);
10546 } else if (app.pid > 0 && app.pid != MY_PID) {
10547 // Goodbye!
10548 synchronized (mPidsSelfLocked) {
10549 mPidsSelfLocked.remove(app.pid);
10550 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10551 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010552 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010553 }
10554 }
10555
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010556 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10557 // Look through the content providers we are waiting to have launched,
10558 // and if any run in this process then either schedule a restart of
10559 // the process or kill the client waiting for it if this process has
10560 // gone bad.
10561 int NL = mLaunchingProviders.size();
10562 boolean restart = false;
10563 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010564 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010565 if (cpr.launchingApp == app) {
10566 if (!alwaysBad && !app.bad) {
10567 restart = true;
10568 } else {
10569 removeDyingProviderLocked(app, cpr);
10570 NL = mLaunchingProviders.size();
10571 }
10572 }
10573 }
10574 return restart;
10575 }
10576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010577 // =========================================================
10578 // SERVICES
10579 // =========================================================
10580
10581 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10582 ActivityManager.RunningServiceInfo info =
10583 new ActivityManager.RunningServiceInfo();
10584 info.service = r.name;
10585 if (r.app != null) {
10586 info.pid = r.app.pid;
10587 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010588 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010589 info.process = r.processName;
10590 info.foreground = r.isForeground;
10591 info.activeSince = r.createTime;
10592 info.started = r.startRequested;
10593 info.clientCount = r.connections.size();
10594 info.crashCount = r.crashCount;
10595 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010596 if (r.isForeground) {
10597 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10598 }
10599 if (r.startRequested) {
10600 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10601 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010602 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010603 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10604 }
10605 if (r.app != null && r.app.persistent) {
10606 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10607 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010608
10609 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10610 for (int i=0; i<connl.size(); i++) {
10611 ConnectionRecord conn = connl.get(i);
10612 if (conn.clientLabel != 0) {
10613 info.clientPackage = conn.binding.client.info.packageName;
10614 info.clientLabel = conn.clientLabel;
10615 return info;
10616 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010617 }
10618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010619 return info;
10620 }
10621
10622 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10623 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010624 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010625 synchronized (this) {
10626 ArrayList<ActivityManager.RunningServiceInfo> res
10627 = new ArrayList<ActivityManager.RunningServiceInfo>();
10628
Amith Yamasani742a6712011-05-04 14:49:28 -070010629 int userId = UserId.getUserId(Binder.getCallingUid());
10630 if (mServiceMap.getAllServices(userId).size() > 0) {
10631 Iterator<ServiceRecord> it
10632 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010633 while (it.hasNext() && res.size() < maxNum) {
10634 res.add(makeRunningServiceInfoLocked(it.next()));
10635 }
10636 }
10637
10638 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10639 ServiceRecord r = mRestartingServices.get(i);
10640 ActivityManager.RunningServiceInfo info =
10641 makeRunningServiceInfoLocked(r);
10642 info.restarting = r.nextRestartTime;
10643 res.add(info);
10644 }
10645
10646 return res;
10647 }
10648 }
10649
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010650 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010651 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010652 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010653 int userId = UserId.getUserId(Binder.getCallingUid());
10654 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010655 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010656 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10657 for (int i=0; i<conn.size(); i++) {
10658 if (conn.get(i).clientIntent != null) {
10659 return conn.get(i).clientIntent;
10660 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010661 }
10662 }
10663 }
10664 }
10665 return null;
10666 }
10667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010668 private final ServiceRecord findServiceLocked(ComponentName name,
10669 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010670 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010671 return r == token ? r : null;
10672 }
10673
10674 private final class ServiceLookupResult {
10675 final ServiceRecord record;
10676 final String permission;
10677
10678 ServiceLookupResult(ServiceRecord _record, String _permission) {
10679 record = _record;
10680 permission = _permission;
10681 }
10682 };
10683
10684 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010685 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010686 ServiceRecord r = null;
10687 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010688 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010689 }
10690 if (r == null) {
10691 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010692 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010693 }
10694
10695 if (r == null) {
10696 try {
10697 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010698 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010699 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010700 ServiceInfo sInfo =
10701 rInfo != null ? rInfo.serviceInfo : null;
10702 if (sInfo == null) {
10703 return null;
10704 }
10705
10706 ComponentName name = new ComponentName(
10707 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010708 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010709 } catch (RemoteException ex) {
10710 // pm is in same process, this will never happen.
10711 }
10712 }
10713 if (r != null) {
10714 int callingPid = Binder.getCallingPid();
10715 int callingUid = Binder.getCallingUid();
10716 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010717 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010718 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010719 if (!r.exported) {
10720 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10721 + " from pid=" + callingPid
10722 + ", uid=" + callingUid
10723 + " that is not exported from uid " + r.appInfo.uid);
10724 return new ServiceLookupResult(null, "not exported from uid "
10725 + r.appInfo.uid);
10726 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010727 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010728 + " from pid=" + callingPid
10729 + ", uid=" + callingUid
10730 + " requires " + r.permission);
10731 return new ServiceLookupResult(null, r.permission);
10732 }
10733 return new ServiceLookupResult(r, null);
10734 }
10735 return null;
10736 }
10737
10738 private class ServiceRestarter implements Runnable {
10739 private ServiceRecord mService;
10740
10741 void setService(ServiceRecord service) {
10742 mService = service;
10743 }
10744
10745 public void run() {
10746 synchronized(ActivityManagerService.this) {
10747 performServiceRestartLocked(mService);
10748 }
10749 }
10750 }
10751
10752 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010753 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010754 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010755 if (DEBUG_SERVICE)
10756 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010757 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010759 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010760 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010761 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010762 if (r == null) {
10763 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010764 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766 if (r == null) {
10767 try {
10768 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010769 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010770 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771 ServiceInfo sInfo =
10772 rInfo != null ? rInfo.serviceInfo : null;
10773 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010774 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010775 ": not found");
10776 return null;
10777 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010778 if (userId > 0) {
10779 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010781 ComponentName name = new ComponentName(
10782 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010783 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010784 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010785 Intent.FilterComparison filter = new Intent.FilterComparison(
10786 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010787 ServiceRestarter res = new ServiceRestarter();
10788 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10789 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10790 synchronized (stats) {
10791 ss = stats.getServiceStatsLocked(
10792 sInfo.applicationInfo.uid, sInfo.packageName,
10793 sInfo.name);
10794 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010795 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010796 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010797 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10798 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010799
10800 // Make sure this component isn't in the pending list.
10801 int N = mPendingServices.size();
10802 for (int i=0; i<N; i++) {
10803 ServiceRecord pr = mPendingServices.get(i);
10804 if (pr.name.equals(name)) {
10805 mPendingServices.remove(i);
10806 i--;
10807 N--;
10808 }
10809 }
10810 }
10811 } catch (RemoteException ex) {
10812 // pm is in same process, this will never happen.
10813 }
10814 }
10815 if (r != null) {
10816 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010817 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010818 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010819 if (!r.exported) {
10820 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10821 + " from pid=" + callingPid
10822 + ", uid=" + callingUid
10823 + " that is not exported from uid " + r.appInfo.uid);
10824 return new ServiceLookupResult(null, "not exported from uid "
10825 + r.appInfo.uid);
10826 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010827 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010828 + " from pid=" + callingPid
10829 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010830 + " requires " + r.permission);
10831 return new ServiceLookupResult(null, r.permission);
10832 }
10833 return new ServiceLookupResult(r, null);
10834 }
10835 return null;
10836 }
10837
Dianne Hackborn287952c2010-09-22 22:34:31 -070010838 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10839 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10840 + why + " of " + r + " in app " + r.app);
10841 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10842 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010843 long now = SystemClock.uptimeMillis();
10844 if (r.executeNesting == 0 && r.app != null) {
10845 if (r.app.executingServices.size() == 0) {
10846 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10847 msg.obj = r.app;
10848 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10849 }
10850 r.app.executingServices.add(r);
10851 }
10852 r.executeNesting++;
10853 r.executingStart = now;
10854 }
10855
10856 private final void sendServiceArgsLocked(ServiceRecord r,
10857 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010858 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010859 if (N == 0) {
10860 return;
10861 }
10862
Dianne Hackborn39792d22010-08-19 18:01:52 -070010863 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010864 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010865 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010866 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10867 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010868 if (si.intent == null && N > 1) {
10869 // If somehow we got a dummy null intent in the middle,
10870 // then skip it. DO NOT skip a null intent when it is
10871 // the only one in the list -- this is to support the
10872 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010873 continue;
10874 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010875 si.deliveredTime = SystemClock.uptimeMillis();
10876 r.deliveredStarts.add(si);
10877 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010878 if (si.neededGrants != null) {
10879 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10880 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010881 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010882 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010883 if (!oomAdjusted) {
10884 oomAdjusted = true;
10885 updateOomAdjLocked(r.app);
10886 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010887 int flags = 0;
10888 if (si.deliveryCount > 0) {
10889 flags |= Service.START_FLAG_RETRY;
10890 }
10891 if (si.doneExecutingCount > 0) {
10892 flags |= Service.START_FLAG_REDELIVERY;
10893 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010894 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010895 } catch (RemoteException e) {
10896 // Remote process gone... we'll let the normal cleanup take
10897 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010898 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010899 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010900 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010901 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010902 break;
10903 }
10904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010905 }
10906
10907 private final boolean requestServiceBindingLocked(ServiceRecord r,
10908 IntentBindRecord i, boolean rebind) {
10909 if (r.app == null || r.app.thread == null) {
10910 // If service is not currently running, can't yet bind.
10911 return false;
10912 }
10913 if ((!i.requested || rebind) && i.apps.size() > 0) {
10914 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010915 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010916 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10917 if (!rebind) {
10918 i.requested = true;
10919 }
10920 i.hasBound = true;
10921 i.doRebind = false;
10922 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010923 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010924 return false;
10925 }
10926 }
10927 return true;
10928 }
10929
10930 private final void requestServiceBindingsLocked(ServiceRecord r) {
10931 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10932 while (bindings.hasNext()) {
10933 IntentBindRecord i = bindings.next();
10934 if (!requestServiceBindingLocked(r, i, false)) {
10935 break;
10936 }
10937 }
10938 }
10939
10940 private final void realStartServiceLocked(ServiceRecord r,
10941 ProcessRecord app) throws RemoteException {
10942 if (app.thread == null) {
10943 throw new RemoteException();
10944 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010945 if (DEBUG_MU)
10946 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010947 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010949 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010950
10951 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010952 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010953 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010954
10955 boolean created = false;
10956 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010957 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010958 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010959 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010961 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010962 synchronized (r.stats.getBatteryStats()) {
10963 r.stats.startLaunchedLocked();
10964 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010965 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010966 app.thread.scheduleCreateService(r, r.serviceInfo,
10967 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010968 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010969 created = true;
10970 } finally {
10971 if (!created) {
10972 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010973 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010974 }
10975 }
10976
10977 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010978
10979 // If the service is in the started state, and there are no
10980 // pending arguments, then fake up one so its onStartCommand() will
10981 // be called.
10982 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010983 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010984 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010985 }
10986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010987 sendServiceArgsLocked(r, true);
10988 }
10989
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010990 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10991 boolean allowCancel) {
10992 boolean canceled = false;
10993
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010994 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010995 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010996 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010997
Dianne Hackborn070783f2010-12-29 16:46:28 -080010998 if ((r.serviceInfo.applicationInfo.flags
10999 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11000 minDuration /= 4;
11001 }
11002
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011003 // Any delivered but not yet finished starts should be put back
11004 // on the pending list.
11005 final int N = r.deliveredStarts.size();
11006 if (N > 0) {
11007 for (int i=N-1; i>=0; i--) {
11008 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011009 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011010 if (si.intent == null) {
11011 // We'll generate this again if needed.
11012 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11013 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11014 r.pendingStarts.add(0, si);
11015 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11016 dur *= 2;
11017 if (minDuration < dur) minDuration = dur;
11018 if (resetTime < dur) resetTime = dur;
11019 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011020 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011021 + r.name);
11022 canceled = true;
11023 }
11024 }
11025 r.deliveredStarts.clear();
11026 }
11027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011028 r.totalRestartCount++;
11029 if (r.restartDelay == 0) {
11030 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011031 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011032 } else {
11033 // If it has been a "reasonably long time" since the service
11034 // was started, then reset our restart duration back to
11035 // the beginning, so we don't infinitely increase the duration
11036 // on a service that just occasionally gets killed (which is
11037 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011038 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011040 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011041 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011042 if ((r.serviceInfo.applicationInfo.flags
11043 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11044 // Services in peristent processes will restart much more
11045 // quickly, since they are pretty important. (Think SystemUI).
11046 r.restartDelay += minDuration/2;
11047 } else {
11048 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11049 if (r.restartDelay < minDuration) {
11050 r.restartDelay = minDuration;
11051 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011053 }
11054 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011055
11056 r.nextRestartTime = now + r.restartDelay;
11057
11058 // Make sure that we don't end up restarting a bunch of services
11059 // all at the same time.
11060 boolean repeat;
11061 do {
11062 repeat = false;
11063 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11064 ServiceRecord r2 = mRestartingServices.get(i);
11065 if (r2 != r && r.nextRestartTime
11066 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11067 && r.nextRestartTime
11068 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11069 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11070 r.restartDelay = r.nextRestartTime - now;
11071 repeat = true;
11072 break;
11073 }
11074 }
11075 } while (repeat);
11076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011077 if (!mRestartingServices.contains(r)) {
11078 mRestartingServices.add(r);
11079 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011080
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011081 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011083 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011084 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011085 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011086 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011087 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011088 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011089 r.shortName, r.restartDelay);
11090
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011091 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011092 }
11093
11094 final void performServiceRestartLocked(ServiceRecord r) {
11095 if (!mRestartingServices.contains(r)) {
11096 return;
11097 }
11098 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11099 }
11100
11101 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11102 if (r.restartDelay == 0) {
11103 return false;
11104 }
11105 r.resetRestartCounter();
11106 mRestartingServices.remove(r);
11107 mHandler.removeCallbacks(r.restarter);
11108 return true;
11109 }
11110
11111 private final boolean bringUpServiceLocked(ServiceRecord r,
11112 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011113 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114 //r.dump(" ");
11115
Dianne Hackborn36124872009-10-08 16:22:03 -070011116 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011117 sendServiceArgsLocked(r, false);
11118 return true;
11119 }
11120
11121 if (!whileRestarting && r.restartDelay > 0) {
11122 // If waiting for a restart, then do nothing.
11123 return true;
11124 }
11125
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011126 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011127
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011128 // We are now bringing the service up, so no longer in the
11129 // restarting state.
11130 mRestartingServices.remove(r);
11131
Dianne Hackborne7f97212011-02-24 14:40:20 -080011132 // Service is now being launched, its package can't be stopped.
11133 try {
11134 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011135 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011136 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011137 } catch (IllegalArgumentException e) {
11138 Slog.w(TAG, "Failed trying to unstop package "
11139 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011140 }
11141
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011142 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011143 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011144 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011145
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011146 if (!isolated) {
11147 app = getProcessRecordLocked(appName, r.appInfo.uid);
11148 if (DEBUG_MU)
11149 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11150 if (app != null && app.thread != null) {
11151 try {
11152 app.addPackage(r.appInfo.packageName);
11153 realStartServiceLocked(r, app);
11154 return true;
11155 } catch (RemoteException e) {
11156 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11157 }
11158
11159 // If a dead object exception was thrown -- fall through to
11160 // restart the application.
11161 }
11162 } else {
11163 // If this service runs in an isolated process, then each time
11164 // we call startProcessLocked() we will get a new isolated
11165 // process, starting another process if we are currently waiting
11166 // for a previous process to come up. To deal with this, we store
11167 // in the service any current isolated process it is running in or
11168 // waiting to have come up.
11169 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011170 }
11171
Dianne Hackborn36124872009-10-08 16:22:03 -070011172 // Not running -- get it started, and enqueue this service record
11173 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011174 if (app == null) {
11175 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11176 "service", r.name, false, isolated)) == null) {
11177 Slog.w(TAG, "Unable to launch app "
11178 + r.appInfo.packageName + "/"
11179 + r.appInfo.uid + " for service "
11180 + r.intent.getIntent() + ": process is bad");
11181 bringDownServiceLocked(r, true);
11182 return false;
11183 }
11184 if (isolated) {
11185 r.isolatedProc = app;
11186 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011187 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011189 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011190 mPendingServices.add(r);
11191 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011193 return true;
11194 }
11195
11196 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011197 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011198 //r.dump(" ");
11199
11200 // Does it still need to run?
11201 if (!force && r.startRequested) {
11202 return;
11203 }
11204 if (r.connections.size() > 0) {
11205 if (!force) {
11206 // XXX should probably keep a count of the number of auto-create
11207 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011208 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011209 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011210 ArrayList<ConnectionRecord> cr = it.next();
11211 for (int i=0; i<cr.size(); i++) {
11212 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11213 return;
11214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011215 }
11216 }
11217 }
11218
11219 // Report to all of the connections that the service is no longer
11220 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011221 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011222 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011223 ArrayList<ConnectionRecord> c = it.next();
11224 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011225 ConnectionRecord cr = c.get(i);
11226 // There is still a connection to the service that is
11227 // being brought down. Mark it as dead.
11228 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011229 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011230 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011231 } catch (Exception e) {
11232 Slog.w(TAG, "Failure disconnecting service " + r.name +
11233 " to connection " + c.get(i).conn.asBinder() +
11234 " (in " + c.get(i).binding.client.processName + ")", e);
11235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011236 }
11237 }
11238 }
11239
11240 // Tell the service that it has been unbound.
11241 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11242 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11243 while (it.hasNext()) {
11244 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011245 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011246 + ": hasBound=" + ibr.hasBound);
11247 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11248 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011249 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011250 updateOomAdjLocked(r.app);
11251 ibr.hasBound = false;
11252 r.app.thread.scheduleUnbindService(r,
11253 ibr.intent.getIntent());
11254 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011255 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256 + r.shortName, e);
11257 serviceDoneExecutingLocked(r, true);
11258 }
11259 }
11260 }
11261 }
11262
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011263 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011264 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011265 System.identityHashCode(r), r.shortName,
11266 (r.app != null) ? r.app.pid : -1);
11267
Amith Yamasani742a6712011-05-04 14:49:28 -070011268 mServiceMap.removeServiceByName(r.name, r.userId);
11269 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011270 r.totalRestartCount = 0;
11271 unscheduleServiceRestartLocked(r);
11272
11273 // Also make sure it is not on the pending list.
11274 int N = mPendingServices.size();
11275 for (int i=0; i<N; i++) {
11276 if (mPendingServices.get(i) == r) {
11277 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011278 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011279 i--;
11280 N--;
11281 }
11282 }
11283
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011284 r.cancelNotification();
11285 r.isForeground = false;
11286 r.foregroundId = 0;
11287 r.foregroundNoti = null;
11288
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011289 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011290 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011291 r.pendingStarts.clear();
11292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011293 if (r.app != null) {
11294 synchronized (r.stats.getBatteryStats()) {
11295 r.stats.stopLaunchedLocked();
11296 }
11297 r.app.services.remove(r);
11298 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011299 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011300 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011301 mStoppingServices.add(r);
11302 updateOomAdjLocked(r.app);
11303 r.app.thread.scheduleStopService(r);
11304 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011305 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011306 + r.shortName, e);
11307 serviceDoneExecutingLocked(r, true);
11308 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011309 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011310 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011311 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011312 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313 }
11314 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011315 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011316 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011317 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011318
11319 if (r.bindings.size() > 0) {
11320 r.bindings.clear();
11321 }
11322
11323 if (r.restarter instanceof ServiceRestarter) {
11324 ((ServiceRestarter)r.restarter).setService(null);
11325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011326 }
11327
11328 ComponentName startServiceLocked(IApplicationThread caller,
11329 Intent service, String resolvedType,
11330 int callingPid, int callingUid) {
11331 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011332 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 + " type=" + resolvedType + " args=" + service.getExtras());
11334
11335 if (caller != null) {
11336 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11337 if (callerApp == null) {
11338 throw new SecurityException(
11339 "Unable to find app for caller " + caller
11340 + " (pid=" + Binder.getCallingPid()
11341 + ") when starting service " + service);
11342 }
11343 }
11344
11345 ServiceLookupResult res =
11346 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011347 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011348 if (res == null) {
11349 return null;
11350 }
11351 if (res.record == null) {
11352 return new ComponentName("!", res.permission != null
11353 ? res.permission : "private to package");
11354 }
11355 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011356 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11357 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011358 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011359 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011360 }
11361 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011362 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011363 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011364 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011365 r.lastActivity = SystemClock.uptimeMillis();
11366 synchronized (r.stats.getBatteryStats()) {
11367 r.stats.startRunningLocked();
11368 }
11369 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11370 return new ComponentName("!", "Service process is bad");
11371 }
11372 return r.name;
11373 }
11374 }
11375
11376 public ComponentName startService(IApplicationThread caller, Intent service,
11377 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011378 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 // Refuse possible leaked file descriptors
11380 if (service != null && service.hasFileDescriptors() == true) {
11381 throw new IllegalArgumentException("File descriptors passed in Intent");
11382 }
11383
Amith Yamasani742a6712011-05-04 14:49:28 -070011384 if (DEBUG_SERVICE)
11385 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011386 synchronized(this) {
11387 final int callingPid = Binder.getCallingPid();
11388 final int callingUid = Binder.getCallingUid();
11389 final long origId = Binder.clearCallingIdentity();
11390 ComponentName res = startServiceLocked(caller, service,
11391 resolvedType, callingPid, callingUid);
11392 Binder.restoreCallingIdentity(origId);
11393 return res;
11394 }
11395 }
11396
11397 ComponentName startServiceInPackage(int uid,
11398 Intent service, String resolvedType) {
11399 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011400 if (DEBUG_SERVICE)
11401 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011402 final long origId = Binder.clearCallingIdentity();
11403 ComponentName res = startServiceLocked(null, service,
11404 resolvedType, -1, uid);
11405 Binder.restoreCallingIdentity(origId);
11406 return res;
11407 }
11408 }
11409
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011410 private void stopServiceLocked(ServiceRecord service) {
11411 synchronized (service.stats.getBatteryStats()) {
11412 service.stats.stopRunningLocked();
11413 }
11414 service.startRequested = false;
11415 service.callStart = false;
11416 bringDownServiceLocked(service, false);
11417 }
11418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011419 public int stopService(IApplicationThread caller, Intent service,
11420 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011421 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011422 // Refuse possible leaked file descriptors
11423 if (service != null && service.hasFileDescriptors() == true) {
11424 throw new IllegalArgumentException("File descriptors passed in Intent");
11425 }
11426
11427 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011428 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011429 + " type=" + resolvedType);
11430
11431 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11432 if (caller != null && callerApp == null) {
11433 throw new SecurityException(
11434 "Unable to find app for caller " + caller
11435 + " (pid=" + Binder.getCallingPid()
11436 + ") when stopping service " + service);
11437 }
11438
11439 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011440 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11441 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011442 if (r != null) {
11443 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011444 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011445 try {
11446 stopServiceLocked(r.record);
11447 } finally {
11448 Binder.restoreCallingIdentity(origId);
11449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011450 return 1;
11451 }
11452 return -1;
11453 }
11454 }
11455
11456 return 0;
11457 }
11458
11459 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011460 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011461 // Refuse possible leaked file descriptors
11462 if (service != null && service.hasFileDescriptors() == true) {
11463 throw new IllegalArgumentException("File descriptors passed in Intent");
11464 }
11465
11466 IBinder ret = null;
11467
11468 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011469 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11470 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011471
11472 if (r != null) {
11473 // r.record is null if findServiceLocked() failed the caller permission check
11474 if (r.record == null) {
11475 throw new SecurityException(
11476 "Permission Denial: Accessing service " + r.record.name
11477 + " from pid=" + Binder.getCallingPid()
11478 + ", uid=" + Binder.getCallingUid()
11479 + " requires " + r.permission);
11480 }
11481 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11482 if (ib != null) {
11483 ret = ib.binder;
11484 }
11485 }
11486 }
11487
11488 return ret;
11489 }
11490
11491 public boolean stopServiceToken(ComponentName className, IBinder token,
11492 int startId) {
11493 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011494 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011495 + " " + token + " startId=" + startId);
11496 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011497 if (r != null) {
11498 if (startId >= 0) {
11499 // Asked to only stop if done with all work. Note that
11500 // to avoid leaks, we will take this as dropping all
11501 // start items up to and including this one.
11502 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11503 if (si != null) {
11504 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011505 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11506 cur.removeUriPermissionsLocked();
11507 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011508 break;
11509 }
11510 }
11511 }
11512
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011513 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011514 return false;
11515 }
11516
11517 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011518 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011519 + " is last, but have " + r.deliveredStarts.size()
11520 + " remaining args");
11521 }
11522 }
11523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011524 synchronized (r.stats.getBatteryStats()) {
11525 r.stats.stopRunningLocked();
11526 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011527 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011528 }
11529 final long origId = Binder.clearCallingIdentity();
11530 bringDownServiceLocked(r, false);
11531 Binder.restoreCallingIdentity(origId);
11532 return true;
11533 }
11534 }
11535 return false;
11536 }
11537
11538 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011539 int id, Notification notification, boolean removeNotification) {
11540 final long origId = Binder.clearCallingIdentity();
11541 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011542 synchronized(this) {
11543 ServiceRecord r = findServiceLocked(className, token);
11544 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011545 if (id != 0) {
11546 if (notification == null) {
11547 throw new IllegalArgumentException("null notification");
11548 }
11549 if (r.foregroundId != id) {
11550 r.cancelNotification();
11551 r.foregroundId = id;
11552 }
11553 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11554 r.foregroundNoti = notification;
11555 r.isForeground = true;
11556 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011557 if (r.app != null) {
11558 updateServiceForegroundLocked(r.app, true);
11559 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011560 } else {
11561 if (r.isForeground) {
11562 r.isForeground = false;
11563 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011564 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011565 updateServiceForegroundLocked(r.app, true);
11566 }
11567 }
11568 if (removeNotification) {
11569 r.cancelNotification();
11570 r.foregroundId = 0;
11571 r.foregroundNoti = null;
11572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011573 }
11574 }
11575 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011576 } finally {
11577 Binder.restoreCallingIdentity(origId);
11578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011579 }
11580
11581 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11582 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011583 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011584 if (sr.isForeground) {
11585 anyForeground = true;
11586 break;
11587 }
11588 }
11589 if (anyForeground != proc.foregroundServices) {
11590 proc.foregroundServices = anyForeground;
11591 if (oomAdj) {
11592 updateOomAdjLocked();
11593 }
11594 }
11595 }
11596
11597 public int bindService(IApplicationThread caller, IBinder token,
11598 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011599 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011600 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011601 // Refuse possible leaked file descriptors
11602 if (service != null && service.hasFileDescriptors() == true) {
11603 throw new IllegalArgumentException("File descriptors passed in Intent");
11604 }
11605
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011606 checkValidCaller(Binder.getCallingUid(), userId);
11607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011608 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011609 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011610 + " type=" + resolvedType + " conn=" + connection.asBinder()
11611 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011612 if (DEBUG_MU)
11613 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11614 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011615 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11616 if (callerApp == null) {
11617 throw new SecurityException(
11618 "Unable to find app for caller " + caller
11619 + " (pid=" + Binder.getCallingPid()
11620 + ") when binding service " + service);
11621 }
11622
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011623 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011624 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011625 activity = mMainStack.isInStackLocked(token);
11626 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011627 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011628 return 0;
11629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011630 }
11631
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011632 int clientLabel = 0;
11633 PendingIntent clientIntent = null;
11634
11635 if (callerApp.info.uid == Process.SYSTEM_UID) {
11636 // Hacky kind of thing -- allow system stuff to tell us
11637 // what they are, so we can report this elsewhere for
11638 // others to know why certain services are running.
11639 try {
11640 clientIntent = (PendingIntent)service.getParcelableExtra(
11641 Intent.EXTRA_CLIENT_INTENT);
11642 } catch (RuntimeException e) {
11643 }
11644 if (clientIntent != null) {
11645 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11646 if (clientLabel != 0) {
11647 // There are no useful extras in the intent, trash them.
11648 // System code calling with this stuff just needs to know
11649 // this will happen.
11650 service = service.cloneFilter();
11651 }
11652 }
11653 }
11654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 ServiceLookupResult res =
11656 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011657 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011658 if (res == null) {
11659 return 0;
11660 }
11661 if (res.record == null) {
11662 return -1;
11663 }
11664 ServiceRecord s = res.record;
11665
11666 final long origId = Binder.clearCallingIdentity();
11667
11668 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011669 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011670 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011671 }
11672
11673 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11674 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011675 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011676
11677 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011678 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11679 if (clist == null) {
11680 clist = new ArrayList<ConnectionRecord>();
11681 s.connections.put(binder, clist);
11682 }
11683 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011684 b.connections.add(c);
11685 if (activity != null) {
11686 if (activity.connections == null) {
11687 activity.connections = new HashSet<ConnectionRecord>();
11688 }
11689 activity.connections.add(c);
11690 }
11691 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011692 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11693 b.client.hasAboveClient = true;
11694 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011695 clist = mServiceConnections.get(binder);
11696 if (clist == null) {
11697 clist = new ArrayList<ConnectionRecord>();
11698 mServiceConnections.put(binder, clist);
11699 }
11700 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011701
11702 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11703 s.lastActivity = SystemClock.uptimeMillis();
11704 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11705 return 0;
11706 }
11707 }
11708
11709 if (s.app != null) {
11710 // This could have made the service more important.
11711 updateOomAdjLocked(s.app);
11712 }
11713
Joe Onorato8a9b2202010-02-26 18:56:32 -080011714 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011715 + ": received=" + b.intent.received
11716 + " apps=" + b.intent.apps.size()
11717 + " doRebind=" + b.intent.doRebind);
11718
11719 if (s.app != null && b.intent.received) {
11720 // Service is already running, so we can immediately
11721 // publish the connection.
11722 try {
11723 c.conn.connected(s.name, b.intent.binder);
11724 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011725 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011726 + " to connection " + c.conn.asBinder()
11727 + " (in " + c.binding.client.processName + ")", e);
11728 }
11729
11730 // If this is the first app connected back to this binding,
11731 // and the service had previously asked to be told when
11732 // rebound, then do so.
11733 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11734 requestServiceBindingLocked(s, b.intent, true);
11735 }
11736 } else if (!b.intent.requested) {
11737 requestServiceBindingLocked(s, b.intent, false);
11738 }
11739
11740 Binder.restoreCallingIdentity(origId);
11741 }
11742
11743 return 1;
11744 }
11745
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011746 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011747 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011748 IBinder binder = c.conn.asBinder();
11749 AppBindRecord b = c.binding;
11750 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011751 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11752 if (clist != null) {
11753 clist.remove(c);
11754 if (clist.size() == 0) {
11755 s.connections.remove(binder);
11756 }
11757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011758 b.connections.remove(c);
11759 if (c.activity != null && c.activity != skipAct) {
11760 if (c.activity.connections != null) {
11761 c.activity.connections.remove(c);
11762 }
11763 }
11764 if (b.client != skipApp) {
11765 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011766 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11767 b.client.updateHasAboveClientLocked();
11768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011769 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011770 clist = mServiceConnections.get(binder);
11771 if (clist != null) {
11772 clist.remove(c);
11773 if (clist.size() == 0) {
11774 mServiceConnections.remove(binder);
11775 }
11776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011777
11778 if (b.connections.size() == 0) {
11779 b.intent.apps.remove(b.client);
11780 }
11781
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011782 if (!c.serviceDead) {
11783 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11784 + ": shouldUnbind=" + b.intent.hasBound);
11785 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11786 && b.intent.hasBound) {
11787 try {
11788 bumpServiceExecutingLocked(s, "unbind");
11789 updateOomAdjLocked(s.app);
11790 b.intent.hasBound = false;
11791 // Assume the client doesn't want to know about a rebind;
11792 // we will deal with that later if it asks for one.
11793 b.intent.doRebind = false;
11794 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11795 } catch (Exception e) {
11796 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11797 serviceDoneExecutingLocked(s, true);
11798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011799 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011800
11801 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11802 bringDownServiceLocked(s, false);
11803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011804 }
11805 }
11806
11807 public boolean unbindService(IServiceConnection connection) {
11808 synchronized (this) {
11809 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011810 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011811 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11812 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011813 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011814 + connection.asBinder());
11815 return false;
11816 }
11817
11818 final long origId = Binder.clearCallingIdentity();
11819
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011820 while (clist.size() > 0) {
11821 ConnectionRecord r = clist.get(0);
11822 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011823
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011824 if (r.binding.service.app != null) {
11825 // This could have made the service less important.
11826 updateOomAdjLocked(r.binding.service.app);
11827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 }
11829
11830 Binder.restoreCallingIdentity(origId);
11831 }
11832
11833 return true;
11834 }
11835
11836 public void publishService(IBinder token, Intent intent, IBinder service) {
11837 // Refuse possible leaked file descriptors
11838 if (intent != null && intent.hasFileDescriptors() == true) {
11839 throw new IllegalArgumentException("File descriptors passed in Intent");
11840 }
11841
11842 synchronized(this) {
11843 if (!(token instanceof ServiceRecord)) {
11844 throw new IllegalArgumentException("Invalid service token");
11845 }
11846 ServiceRecord r = (ServiceRecord)token;
11847
11848 final long origId = Binder.clearCallingIdentity();
11849
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011850 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011851 + " " + intent + ": " + service);
11852 if (r != null) {
11853 Intent.FilterComparison filter
11854 = new Intent.FilterComparison(intent);
11855 IntentBindRecord b = r.bindings.get(filter);
11856 if (b != null && !b.received) {
11857 b.binder = service;
11858 b.requested = true;
11859 b.received = true;
11860 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011861 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011862 = r.connections.values().iterator();
11863 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011864 ArrayList<ConnectionRecord> clist = it.next();
11865 for (int i=0; i<clist.size(); i++) {
11866 ConnectionRecord c = clist.get(i);
11867 if (!filter.equals(c.binding.intent.intent)) {
11868 if (DEBUG_SERVICE) Slog.v(
11869 TAG, "Not publishing to: " + c);
11870 if (DEBUG_SERVICE) Slog.v(
11871 TAG, "Bound intent: " + c.binding.intent.intent);
11872 if (DEBUG_SERVICE) Slog.v(
11873 TAG, "Published intent: " + intent);
11874 continue;
11875 }
11876 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11877 try {
11878 c.conn.connected(r.name, service);
11879 } catch (Exception e) {
11880 Slog.w(TAG, "Failure sending service " + r.name +
11881 " to connection " + c.conn.asBinder() +
11882 " (in " + c.binding.client.processName + ")", e);
11883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011884 }
11885 }
11886 }
11887 }
11888
11889 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11890
11891 Binder.restoreCallingIdentity(origId);
11892 }
11893 }
11894 }
11895
11896 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11897 // Refuse possible leaked file descriptors
11898 if (intent != null && intent.hasFileDescriptors() == true) {
11899 throw new IllegalArgumentException("File descriptors passed in Intent");
11900 }
11901
11902 synchronized(this) {
11903 if (!(token instanceof ServiceRecord)) {
11904 throw new IllegalArgumentException("Invalid service token");
11905 }
11906 ServiceRecord r = (ServiceRecord)token;
11907
11908 final long origId = Binder.clearCallingIdentity();
11909
11910 if (r != null) {
11911 Intent.FilterComparison filter
11912 = new Intent.FilterComparison(intent);
11913 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011914 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011915 + " at " + b + ": apps="
11916 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011917
11918 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011919 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011920 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011921 // Applications have already bound since the last
11922 // unbind, so just rebind right here.
11923 requestServiceBindingLocked(r, b, true);
11924 } else {
11925 // Note to tell the service the next time there is
11926 // a new client.
11927 b.doRebind = true;
11928 }
11929 }
11930
Per Edelberg78f9fff2010-08-30 20:01:35 +020011931 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011932
11933 Binder.restoreCallingIdentity(origId);
11934 }
11935 }
11936 }
11937
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011938 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011939 synchronized(this) {
11940 if (!(token instanceof ServiceRecord)) {
11941 throw new IllegalArgumentException("Invalid service token");
11942 }
11943 ServiceRecord r = (ServiceRecord)token;
11944 boolean inStopping = mStoppingServices.contains(token);
11945 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011946 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011947 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011948 + " with incorrect token: given " + token
11949 + ", expected " + r);
11950 return;
11951 }
11952
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011953 if (type == 1) {
11954 // This is a call from a service start... take care of
11955 // book-keeping.
11956 r.callStart = true;
11957 switch (res) {
11958 case Service.START_STICKY_COMPATIBILITY:
11959 case Service.START_STICKY: {
11960 // We are done with the associated start arguments.
11961 r.findDeliveredStart(startId, true);
11962 // Don't stop if killed.
11963 r.stopIfKilled = false;
11964 break;
11965 }
11966 case Service.START_NOT_STICKY: {
11967 // We are done with the associated start arguments.
11968 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011969 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011970 // There is no more work, and this service
11971 // doesn't want to hang around if killed.
11972 r.stopIfKilled = true;
11973 }
11974 break;
11975 }
11976 case Service.START_REDELIVER_INTENT: {
11977 // We'll keep this item until they explicitly
11978 // call stop for it, but keep track of the fact
11979 // that it was delivered.
11980 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11981 if (si != null) {
11982 si.deliveryCount = 0;
11983 si.doneExecutingCount++;
11984 // Don't stop if killed.
11985 r.stopIfKilled = true;
11986 }
11987 break;
11988 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011989 case Service.START_TASK_REMOVED_COMPLETE: {
11990 // Special processing for onTaskRemoved(). Don't
11991 // impact normal onStartCommand() processing.
11992 r.findDeliveredStart(startId, true);
11993 break;
11994 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011995 default:
11996 throw new IllegalArgumentException(
11997 "Unknown service start result: " + res);
11998 }
11999 if (res == Service.START_STICKY_COMPATIBILITY) {
12000 r.callStart = false;
12001 }
12002 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012003 if (DEBUG_MU)
12004 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12005 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012006 final long origId = Binder.clearCallingIdentity();
12007 serviceDoneExecutingLocked(r, inStopping);
12008 Binder.restoreCallingIdentity(origId);
12009 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012010 Slog.w(TAG, "Done executing unknown service from pid "
12011 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012012 }
12013 }
12014 }
12015
12016 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012017 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12018 + ": nesting=" + r.executeNesting
12019 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012020 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012021 r.executeNesting--;
12022 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012023 if (DEBUG_SERVICE) Slog.v(TAG,
12024 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012025 r.app.executingServices.remove(r);
12026 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012027 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12028 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012029 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12030 }
12031 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012032 if (DEBUG_SERVICE) Slog.v(TAG,
12033 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012034 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012035 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012036 }
12037 updateOomAdjLocked(r.app);
12038 }
12039 }
12040
12041 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012042 String anrMessage = null;
12043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012044 synchronized(this) {
12045 if (proc.executingServices.size() == 0 || proc.thread == null) {
12046 return;
12047 }
12048 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12049 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12050 ServiceRecord timeout = null;
12051 long nextTime = 0;
12052 while (it.hasNext()) {
12053 ServiceRecord sr = it.next();
12054 if (sr.executingStart < maxTime) {
12055 timeout = sr;
12056 break;
12057 }
12058 if (sr.executingStart > nextTime) {
12059 nextTime = sr.executingStart;
12060 }
12061 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012062 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012063 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012064 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012065 } else {
12066 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12067 msg.obj = proc;
12068 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12069 }
12070 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012071
12072 if (anrMessage != null) {
12073 appNotResponding(proc, null, null, anrMessage);
12074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075 }
12076
12077 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012078 // BACKUP AND RESTORE
12079 // =========================================================
12080
12081 // Cause the target app to be launched if necessary and its backup agent
12082 // instantiated. The backup agent will invoke backupAgentCreated() on the
12083 // activity manager to announce its creation.
12084 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012085 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012086 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12087
12088 synchronized(this) {
12089 // !!! TODO: currently no check here that we're already bound
12090 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12091 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12092 synchronized (stats) {
12093 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12094 }
12095
Dianne Hackborne7f97212011-02-24 14:40:20 -080012096 // Backup agent is now in use, its package can't be stopped.
12097 try {
12098 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012099 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012100 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012101 } catch (IllegalArgumentException e) {
12102 Slog.w(TAG, "Failed trying to unstop package "
12103 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012104 }
12105
Christopher Tate181fafa2009-05-14 11:12:14 -070012106 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012107 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12108 ? new ComponentName(app.packageName, app.backupAgentName)
12109 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012110 // startProcessLocked() returns existing proc's record if it's already running
12111 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012112 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012113 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012114 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012115 return false;
12116 }
12117
12118 r.app = proc;
12119 mBackupTarget = r;
12120 mBackupAppName = app.packageName;
12121
Christopher Tate6fa95972009-06-05 18:43:55 -070012122 // Try not to kill the process during backup
12123 updateOomAdjLocked(proc);
12124
Christopher Tate181fafa2009-05-14 11:12:14 -070012125 // If the process is already attached, schedule the creation of the backup agent now.
12126 // If it is not yet live, this will be done when it attaches to the framework.
12127 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012128 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012129 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012130 proc.thread.scheduleCreateBackupAgent(app,
12131 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012132 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012133 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012134 }
12135 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012136 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012137 }
12138 // Invariants: at this point, the target app process exists and the application
12139 // is either already running or in the process of coming up. mBackupTarget and
12140 // mBackupAppName describe the app, so that when it binds back to the AM we
12141 // know that it's scheduled for a backup-agent operation.
12142 }
12143
12144 return true;
12145 }
12146
12147 // A backup agent has just come up
12148 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012149 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012150 + " = " + agent);
12151
12152 synchronized(this) {
12153 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012154 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012155 return;
12156 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012157 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012158
Dianne Hackborn06740692010-09-22 22:46:21 -070012159 long oldIdent = Binder.clearCallingIdentity();
12160 try {
12161 IBackupManager bm = IBackupManager.Stub.asInterface(
12162 ServiceManager.getService(Context.BACKUP_SERVICE));
12163 bm.agentConnected(agentPackageName, agent);
12164 } catch (RemoteException e) {
12165 // can't happen; the backup manager service is local
12166 } catch (Exception e) {
12167 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12168 e.printStackTrace();
12169 } finally {
12170 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012171 }
12172 }
12173
12174 // done with this agent
12175 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012176 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012177 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012178 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012179 return;
12180 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012181
12182 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012183 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012184 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012185 return;
12186 }
12187
Christopher Tate181fafa2009-05-14 11:12:14 -070012188 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012189 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012190 return;
12191 }
12192
Christopher Tate6fa95972009-06-05 18:43:55 -070012193 ProcessRecord proc = mBackupTarget.app;
12194 mBackupTarget = null;
12195 mBackupAppName = null;
12196
12197 // Not backing this app up any more; reset its OOM adjustment
12198 updateOomAdjLocked(proc);
12199
Christopher Tatec7b31e32009-06-10 15:49:30 -070012200 // If the app crashed during backup, 'thread' will be null here
12201 if (proc.thread != null) {
12202 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012203 proc.thread.scheduleDestroyBackupAgent(appInfo,
12204 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012205 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012206 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012207 e.printStackTrace();
12208 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012209 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012210 }
12211 }
12212 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012213 // BROADCASTS
12214 // =========================================================
12215
Josh Bartel7f208742010-02-25 11:01:44 -060012216 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012217 List cur) {
12218 final ContentResolver resolver = mContext.getContentResolver();
12219 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12220 if (list == null) {
12221 return cur;
12222 }
12223 int N = list.size();
12224 for (int i=0; i<N; i++) {
12225 Intent intent = list.get(i);
12226 if (filter.match(resolver, intent, true, TAG) >= 0) {
12227 if (cur == null) {
12228 cur = new ArrayList<Intent>();
12229 }
12230 cur.add(intent);
12231 }
12232 }
12233 return cur;
12234 }
12235
Christopher Tatef46723b2012-01-26 14:19:24 -080012236 boolean isPendingBroadcastProcessLocked(int pid) {
12237 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12238 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012240
Christopher Tatef46723b2012-01-26 14:19:24 -080012241 void skipPendingBroadcastLocked(int pid) {
12242 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12243 for (BroadcastQueue queue : mBroadcastQueues) {
12244 queue.skipPendingBroadcastLocked(pid);
12245 }
12246 }
12247
12248 // The app just attached; send any pending broadcasts that it should receive
12249 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12250 boolean didSomething = false;
12251 for (BroadcastQueue queue : mBroadcastQueues) {
12252 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012253 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012254 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012255 }
12256
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012257 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012258 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012259 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012260 synchronized(this) {
12261 ProcessRecord callerApp = null;
12262 if (caller != null) {
12263 callerApp = getRecordForAppLocked(caller);
12264 if (callerApp == null) {
12265 throw new SecurityException(
12266 "Unable to find app for caller " + caller
12267 + " (pid=" + Binder.getCallingPid()
12268 + ") when registering receiver " + receiver);
12269 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012270 if (callerApp.info.uid != Process.SYSTEM_UID &&
12271 !callerApp.pkgList.contains(callerPackage)) {
12272 throw new SecurityException("Given caller package " + callerPackage
12273 + " is not running in process " + callerApp);
12274 }
12275 } else {
12276 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012277 }
12278
12279 List allSticky = null;
12280
12281 // Look for any matching sticky broadcasts...
12282 Iterator actions = filter.actionsIterator();
12283 if (actions != null) {
12284 while (actions.hasNext()) {
12285 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012286 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012287 }
12288 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012289 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012290 }
12291
12292 // The first sticky in the list is returned directly back to
12293 // the client.
12294 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12295
Joe Onorato8a9b2202010-02-26 18:56:32 -080012296 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012297 + ": " + sticky);
12298
12299 if (receiver == null) {
12300 return sticky;
12301 }
12302
12303 ReceiverList rl
12304 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12305 if (rl == null) {
12306 rl = new ReceiverList(this, callerApp,
12307 Binder.getCallingPid(),
12308 Binder.getCallingUid(), receiver);
12309 if (rl.app != null) {
12310 rl.app.receivers.add(rl);
12311 } else {
12312 try {
12313 receiver.asBinder().linkToDeath(rl, 0);
12314 } catch (RemoteException e) {
12315 return sticky;
12316 }
12317 rl.linkedToDeath = true;
12318 }
12319 mRegisteredReceivers.put(receiver.asBinder(), rl);
12320 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012321 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012322 rl.add(bf);
12323 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012324 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012325 }
12326 mReceiverResolver.addFilter(bf);
12327
12328 // Enqueue broadcasts for all existing stickies that match
12329 // this filter.
12330 if (allSticky != null) {
12331 ArrayList receivers = new ArrayList();
12332 receivers.add(bf);
12333
12334 int N = allSticky.size();
12335 for (int i=0; i<N; i++) {
12336 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012337 BroadcastQueue queue = broadcastQueueForIntent(intent);
12338 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012339 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012340 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012341 queue.enqueueParallelBroadcastLocked(r);
12342 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012343 }
12344 }
12345
12346 return sticky;
12347 }
12348 }
12349
12350 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012351 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012352
Christopher Tatef46723b2012-01-26 14:19:24 -080012353 final long origId = Binder.clearCallingIdentity();
12354 try {
12355 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012356
Christopher Tatef46723b2012-01-26 14:19:24 -080012357 synchronized(this) {
12358 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012359 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012360 if (rl != null) {
12361 if (rl.curBroadcast != null) {
12362 BroadcastRecord r = rl.curBroadcast;
12363 final boolean doNext = finishReceiverLocked(
12364 receiver.asBinder(), r.resultCode, r.resultData,
12365 r.resultExtras, r.resultAbort, true);
12366 if (doNext) {
12367 doTrim = true;
12368 r.queue.processNextBroadcast(false);
12369 }
12370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012371
Christopher Tatef46723b2012-01-26 14:19:24 -080012372 if (rl.app != null) {
12373 rl.app.receivers.remove(rl);
12374 }
12375 removeReceiverLocked(rl);
12376 if (rl.linkedToDeath) {
12377 rl.linkedToDeath = false;
12378 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012380 }
12381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012382
Christopher Tatef46723b2012-01-26 14:19:24 -080012383 // If we actually concluded any broadcasts, we might now be able
12384 // to trim the recipients' apps from our working set
12385 if (doTrim) {
12386 trimApplications();
12387 return;
12388 }
12389
12390 } finally {
12391 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012393 }
12394
12395 void removeReceiverLocked(ReceiverList rl) {
12396 mRegisteredReceivers.remove(rl.receiver.asBinder());
12397 int N = rl.size();
12398 for (int i=0; i<N; i++) {
12399 mReceiverResolver.removeFilter(rl.get(i));
12400 }
12401 }
12402
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012403 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12404 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12405 ProcessRecord r = mLruProcesses.get(i);
12406 if (r.thread != null) {
12407 try {
12408 r.thread.dispatchPackageBroadcast(cmd, packages);
12409 } catch (RemoteException ex) {
12410 }
12411 }
12412 }
12413 }
12414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012415 private final int broadcastIntentLocked(ProcessRecord callerApp,
12416 String callerPackage, Intent intent, String resolvedType,
12417 IIntentReceiver resultTo, int resultCode, String resultData,
12418 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012419 boolean ordered, boolean sticky, int callingPid, int callingUid,
12420 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012421 intent = new Intent(intent);
12422
Dianne Hackborne7f97212011-02-24 14:40:20 -080012423 // By default broadcasts do not go to stopped apps.
12424 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12425
Joe Onorato8a9b2202010-02-26 18:56:32 -080012426 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012427 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12428 + " ordered=" + ordered);
12429 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012430 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012431 }
12432
12433 // Handle special intents: if this broadcast is from the package
12434 // manager about a package being removed, we need to remove all of
12435 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012436 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012437 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012438 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12439 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012440 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012441 || uidRemoved) {
12442 if (checkComponentPermission(
12443 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012444 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445 == PackageManager.PERMISSION_GRANTED) {
12446 if (uidRemoved) {
12447 final Bundle intentExtras = intent.getExtras();
12448 final int uid = intentExtras != null
12449 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12450 if (uid >= 0) {
12451 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12452 synchronized (bs) {
12453 bs.removeUidStatsLocked(uid);
12454 }
12455 }
12456 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012457 // If resources are unvailble just force stop all
12458 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012459 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012460 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12461 if (list != null && (list.length > 0)) {
12462 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012463 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012464 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012465 sendPackageBroadcastLocked(
12466 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012467 }
12468 } else {
12469 Uri data = intent.getData();
12470 String ssp;
12471 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12472 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12473 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012474 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12475 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012476 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012477 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012478 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12479 new String[] {ssp});
12480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012481 }
12482 }
12483 }
12484 } else {
12485 String msg = "Permission Denial: " + intent.getAction()
12486 + " broadcast from " + callerPackage + " (pid=" + callingPid
12487 + ", uid=" + callingUid + ")"
12488 + " requires "
12489 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012490 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012491 throw new SecurityException(msg);
12492 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012493
12494 // Special case for adding a package: by default turn on compatibility
12495 // mode.
12496 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012497 Uri data = intent.getData();
12498 String ssp;
12499 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12500 mCompatModePackages.handlePackageAddedLocked(ssp,
12501 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012503 }
12504
12505 /*
12506 * If this is the time zone changed action, queue up a message that will reset the timezone
12507 * of all currently running processes. This message will get queued up before the broadcast
12508 * happens.
12509 */
12510 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12511 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12512 }
12513
Robert Greenwalt03595d02010-11-02 14:08:23 -070012514 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12515 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12516 }
12517
Robert Greenwalt434203a2010-10-11 16:00:27 -070012518 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12519 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12520 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12521 }
12522
Dianne Hackborn854060af2009-07-09 18:14:31 -070012523 /*
12524 * Prevent non-system code (defined here to be non-persistent
12525 * processes) from sending protected broadcasts.
12526 */
12527 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12528 || callingUid == Process.SHELL_UID || callingUid == 0) {
12529 // Always okay.
12530 } else if (callerApp == null || !callerApp.persistent) {
12531 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012532 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012533 intent.getAction())) {
12534 String msg = "Permission Denial: not allowed to send broadcast "
12535 + intent.getAction() + " from pid="
12536 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012537 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012538 throw new SecurityException(msg);
12539 }
12540 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012541 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012542 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012543 }
12544 }
12545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012546 // Add to the sticky list if requested.
12547 if (sticky) {
12548 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12549 callingPid, callingUid)
12550 != PackageManager.PERMISSION_GRANTED) {
12551 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12552 + callingPid + ", uid=" + callingUid
12553 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012554 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012555 throw new SecurityException(msg);
12556 }
12557 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012558 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012559 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012560 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012561 }
12562 if (intent.getComponent() != null) {
12563 throw new SecurityException(
12564 "Sticky broadcasts can't target a specific component");
12565 }
12566 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12567 if (list == null) {
12568 list = new ArrayList<Intent>();
12569 mStickyBroadcasts.put(intent.getAction(), list);
12570 }
12571 int N = list.size();
12572 int i;
12573 for (i=0; i<N; i++) {
12574 if (intent.filterEquals(list.get(i))) {
12575 // This sticky already exists, replace it.
12576 list.set(i, new Intent(intent));
12577 break;
12578 }
12579 }
12580 if (i >= N) {
12581 list.add(new Intent(intent));
12582 }
12583 }
12584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585 // Figure out who all will receive this broadcast.
12586 List receivers = null;
12587 List<BroadcastFilter> registeredReceivers = null;
12588 try {
12589 if (intent.getComponent() != null) {
12590 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012591 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012592 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012593 if (ai != null) {
12594 receivers = new ArrayList();
12595 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012596 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012597 receivers.add(ri);
12598 }
12599 } else {
12600 // Need to resolve the intent to interested receivers...
12601 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12602 == 0) {
12603 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012604 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012605 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012606 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012607 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12608 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012609 }
12610 } catch (RemoteException ex) {
12611 // pm is in same process, this will never happen.
12612 }
12613
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012614 final boolean replacePending =
12615 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12616
Joe Onorato8a9b2202010-02-26 18:56:32 -080012617 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012618 + " replacePending=" + replacePending);
12619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012620 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12621 if (!ordered && NR > 0) {
12622 // If we are not serializing this broadcast, then send the
12623 // registered receivers separately so they don't wait for the
12624 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012625 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12626 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012627 callerPackage, callingPid, callingUid, requiredPermission,
12628 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012629 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012630 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012631 TAG, "Enqueueing parallel broadcast " + r);
12632 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012633 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012634 queue.enqueueParallelBroadcastLocked(r);
12635 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012637 registeredReceivers = null;
12638 NR = 0;
12639 }
12640
12641 // Merge into one list.
12642 int ir = 0;
12643 if (receivers != null) {
12644 // A special case for PACKAGE_ADDED: do not allow the package
12645 // being added to see this broadcast. This prevents them from
12646 // using this as a back door to get run as soon as they are
12647 // installed. Maybe in the future we want to have a special install
12648 // broadcast or such for apps, but we'd like to deliberately make
12649 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012650 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012651 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12652 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12653 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012654 Uri data = intent.getData();
12655 if (data != null) {
12656 String pkgName = data.getSchemeSpecificPart();
12657 if (pkgName != null) {
12658 skipPackages = new String[] { pkgName };
12659 }
12660 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012661 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012662 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012663 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012664 if (skipPackages != null && (skipPackages.length > 0)) {
12665 for (String skipPackage : skipPackages) {
12666 if (skipPackage != null) {
12667 int NT = receivers.size();
12668 for (int it=0; it<NT; it++) {
12669 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12670 if (curt.activityInfo.packageName.equals(skipPackage)) {
12671 receivers.remove(it);
12672 it--;
12673 NT--;
12674 }
12675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012676 }
12677 }
12678 }
12679
12680 int NT = receivers != null ? receivers.size() : 0;
12681 int it = 0;
12682 ResolveInfo curt = null;
12683 BroadcastFilter curr = null;
12684 while (it < NT && ir < NR) {
12685 if (curt == null) {
12686 curt = (ResolveInfo)receivers.get(it);
12687 }
12688 if (curr == null) {
12689 curr = registeredReceivers.get(ir);
12690 }
12691 if (curr.getPriority() >= curt.priority) {
12692 // Insert this broadcast record into the final list.
12693 receivers.add(it, curr);
12694 ir++;
12695 curr = null;
12696 it++;
12697 NT++;
12698 } else {
12699 // Skip to the next ResolveInfo in the final list.
12700 it++;
12701 curt = null;
12702 }
12703 }
12704 }
12705 while (ir < NR) {
12706 if (receivers == null) {
12707 receivers = new ArrayList();
12708 }
12709 receivers.add(registeredReceivers.get(ir));
12710 ir++;
12711 }
12712
12713 if ((receivers != null && receivers.size() > 0)
12714 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012715 BroadcastQueue queue = broadcastQueueForIntent(intent);
12716 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012717 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012718 receivers, resultTo, resultCode, resultData, map, ordered,
12719 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012720 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012721 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012722 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012723 if (DEBUG_BROADCAST) {
12724 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012725 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012726 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012727 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012728 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012729 queue.enqueueOrderedBroadcastLocked(r);
12730 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012732 }
12733
Dianne Hackborna4972e92012-03-14 10:38:05 -070012734 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012735 }
12736
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012737 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012738 // Refuse possible leaked file descriptors
12739 if (intent != null && intent.hasFileDescriptors() == true) {
12740 throw new IllegalArgumentException("File descriptors passed in Intent");
12741 }
12742
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012743 int flags = intent.getFlags();
12744
12745 if (!mProcessesReady) {
12746 // if the caller really truly claims to know what they're doing, go
12747 // ahead and allow the broadcast without launching any receivers
12748 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12749 intent = new Intent(intent);
12750 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12751 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12752 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12753 + " before boot completion");
12754 throw new IllegalStateException("Cannot broadcast before boot completed");
12755 }
12756 }
12757
12758 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12759 throw new IllegalArgumentException(
12760 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12761 }
12762
12763 return intent;
12764 }
12765
12766 public final int broadcastIntent(IApplicationThread caller,
12767 Intent intent, String resolvedType, IIntentReceiver resultTo,
12768 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012769 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012770 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012771 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012772 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012774 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12775 final int callingPid = Binder.getCallingPid();
12776 final int callingUid = Binder.getCallingUid();
12777 final long origId = Binder.clearCallingIdentity();
12778 int res = broadcastIntentLocked(callerApp,
12779 callerApp != null ? callerApp.info.packageName : null,
12780 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012781 resultCode, resultData, map, requiredPermission, serialized, sticky,
12782 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012783 Binder.restoreCallingIdentity(origId);
12784 return res;
12785 }
12786 }
12787
12788 int broadcastIntentInPackage(String packageName, int uid,
12789 Intent intent, String resolvedType, IIntentReceiver resultTo,
12790 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012791 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012792 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012793 intent = verifyBroadcastLocked(intent);
12794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012795 final long origId = Binder.clearCallingIdentity();
12796 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12797 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012798 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012799 Binder.restoreCallingIdentity(origId);
12800 return res;
12801 }
12802 }
12803
Amith Yamasani742a6712011-05-04 14:49:28 -070012804 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12805 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012806 // Refuse possible leaked file descriptors
12807 if (intent != null && intent.hasFileDescriptors() == true) {
12808 throw new IllegalArgumentException("File descriptors passed in Intent");
12809 }
12810
12811 synchronized(this) {
12812 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12813 != PackageManager.PERMISSION_GRANTED) {
12814 String msg = "Permission Denial: unbroadcastIntent() from pid="
12815 + Binder.getCallingPid()
12816 + ", uid=" + Binder.getCallingUid()
12817 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012818 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012819 throw new SecurityException(msg);
12820 }
12821 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12822 if (list != null) {
12823 int N = list.size();
12824 int i;
12825 for (i=0; i<N; i++) {
12826 if (intent.filterEquals(list.get(i))) {
12827 list.remove(i);
12828 break;
12829 }
12830 }
12831 }
12832 }
12833 }
12834
12835 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12836 String resultData, Bundle resultExtras, boolean resultAbort,
12837 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012838 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12839 if (r == null) {
12840 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012841 return false;
12842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012843
Christopher Tatef46723b2012-01-26 14:19:24 -080012844 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12845 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012846 }
12847
12848 public void finishReceiver(IBinder who, int resultCode, String resultData,
12849 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012850 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012851
12852 // Refuse possible leaked file descriptors
12853 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12854 throw new IllegalArgumentException("File descriptors passed in Bundle");
12855 }
12856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012857 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012858 try {
12859 boolean doNext = false;
12860 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012861
Christopher Tatef46723b2012-01-26 14:19:24 -080012862 synchronized(this) {
12863 r = broadcastRecordForReceiverLocked(who);
12864 if (r != null) {
12865 doNext = r.queue.finishReceiverLocked(r, resultCode,
12866 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012868 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012869
Christopher Tatef46723b2012-01-26 14:19:24 -080012870 if (doNext) {
12871 r.queue.processNextBroadcast(false);
12872 }
12873 trimApplications();
12874 } finally {
12875 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012879 // =========================================================
12880 // INSTRUMENTATION
12881 // =========================================================
12882
12883 public boolean startInstrumentation(ComponentName className,
12884 String profileFile, int flags, Bundle arguments,
12885 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012886 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012887 // Refuse possible leaked file descriptors
12888 if (arguments != null && arguments.hasFileDescriptors()) {
12889 throw new IllegalArgumentException("File descriptors passed in Bundle");
12890 }
12891
12892 synchronized(this) {
12893 InstrumentationInfo ii = null;
12894 ApplicationInfo ai = null;
12895 try {
12896 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012897 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012898 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012899 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012900 } catch (PackageManager.NameNotFoundException e) {
12901 }
12902 if (ii == null) {
12903 reportStartInstrumentationFailure(watcher, className,
12904 "Unable to find instrumentation info for: " + className);
12905 return false;
12906 }
12907 if (ai == null) {
12908 reportStartInstrumentationFailure(watcher, className,
12909 "Unable to find instrumentation target package: " + ii.targetPackage);
12910 return false;
12911 }
12912
12913 int match = mContext.getPackageManager().checkSignatures(
12914 ii.targetPackage, ii.packageName);
12915 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12916 String msg = "Permission Denial: starting instrumentation "
12917 + className + " from pid="
12918 + Binder.getCallingPid()
12919 + ", uid=" + Binder.getCallingPid()
12920 + " not allowed because package " + ii.packageName
12921 + " does not have a signature matching the target "
12922 + ii.targetPackage;
12923 reportStartInstrumentationFailure(watcher, className, msg);
12924 throw new SecurityException(msg);
12925 }
12926
Amith Yamasani483f3b02012-03-13 16:08:00 -070012927 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012929 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012930 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012931 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012932 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012933 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012934 app.instrumentationProfileFile = profileFile;
12935 app.instrumentationArguments = arguments;
12936 app.instrumentationWatcher = watcher;
12937 app.instrumentationResultClass = className;
12938 Binder.restoreCallingIdentity(origId);
12939 }
12940
12941 return true;
12942 }
12943
12944 /**
12945 * Report errors that occur while attempting to start Instrumentation. Always writes the
12946 * error to the logs, but if somebody is watching, send the report there too. This enables
12947 * the "am" command to report errors with more information.
12948 *
12949 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12950 * @param cn The component name of the instrumentation.
12951 * @param report The error report.
12952 */
12953 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12954 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012955 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012956 try {
12957 if (watcher != null) {
12958 Bundle results = new Bundle();
12959 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12960 results.putString("Error", report);
12961 watcher.instrumentationStatus(cn, -1, results);
12962 }
12963 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012964 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012965 }
12966 }
12967
12968 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12969 if (app.instrumentationWatcher != null) {
12970 try {
12971 // NOTE: IInstrumentationWatcher *must* be oneway here
12972 app.instrumentationWatcher.instrumentationFinished(
12973 app.instrumentationClass,
12974 resultCode,
12975 results);
12976 } catch (RemoteException e) {
12977 }
12978 }
12979 app.instrumentationWatcher = null;
12980 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012981 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012982 app.instrumentationProfileFile = null;
12983 app.instrumentationArguments = null;
12984
Amith Yamasani483f3b02012-03-13 16:08:00 -070012985 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012986 }
12987
12988 public void finishInstrumentation(IApplicationThread target,
12989 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012990 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012991 // Refuse possible leaked file descriptors
12992 if (results != null && results.hasFileDescriptors()) {
12993 throw new IllegalArgumentException("File descriptors passed in Intent");
12994 }
12995
12996 synchronized(this) {
12997 ProcessRecord app = getRecordForAppLocked(target);
12998 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012999 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013000 return;
13001 }
13002 final long origId = Binder.clearCallingIdentity();
13003 finishInstrumentationLocked(app, resultCode, results);
13004 Binder.restoreCallingIdentity(origId);
13005 }
13006 }
13007
13008 // =========================================================
13009 // CONFIGURATION
13010 // =========================================================
13011
13012 public ConfigurationInfo getDeviceConfigurationInfo() {
13013 ConfigurationInfo config = new ConfigurationInfo();
13014 synchronized (this) {
13015 config.reqTouchScreen = mConfiguration.touchscreen;
13016 config.reqKeyboardType = mConfiguration.keyboard;
13017 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013018 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13019 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013020 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13021 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013022 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13023 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013024 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13025 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013026 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013027 }
13028 return config;
13029 }
13030
13031 public Configuration getConfiguration() {
13032 Configuration ci;
13033 synchronized(this) {
13034 ci = new Configuration(mConfiguration);
13035 }
13036 return ci;
13037 }
13038
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013039 public void updatePersistentConfiguration(Configuration values) {
13040 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13041 "updateConfiguration()");
13042 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13043 "updateConfiguration()");
13044 if (values == null) {
13045 throw new NullPointerException("Configuration must not be null");
13046 }
13047
13048 synchronized(this) {
13049 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013050 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013051 Binder.restoreCallingIdentity(origId);
13052 }
13053 }
13054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013055 public void updateConfiguration(Configuration values) {
13056 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13057 "updateConfiguration()");
13058
13059 synchronized(this) {
13060 if (values == null && mWindowManager != null) {
13061 // sentinel: fetch the current configuration from the window manager
13062 values = mWindowManager.computeNewConfiguration();
13063 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013064
13065 if (mWindowManager != null) {
13066 mProcessList.applyDisplaySize(mWindowManager);
13067 }
13068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013069 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013070 if (values != null) {
13071 Settings.System.clearConfiguration(values);
13072 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013073 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013074 Binder.restoreCallingIdentity(origId);
13075 }
13076 }
13077
13078 /**
13079 * Do either or both things: (1) change the current configuration, and (2)
13080 * make sure the given activity is running with the (now) current
13081 * configuration. Returns true if the activity has been left running, or
13082 * false if <var>starting</var> is being destroyed to match the new
13083 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013084 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013085 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013086 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013087 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013088 // do nothing if we are headless
13089 if (mHeadless) return true;
13090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013091 int changes = 0;
13092
13093 boolean kept = true;
13094
13095 if (values != null) {
13096 Configuration newConfig = new Configuration(mConfiguration);
13097 changes = newConfig.updateFrom(values);
13098 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013099 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013100 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013101 }
13102
Doug Zongker2bec3d42009-12-04 12:52:44 -080013103 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013104
Dianne Hackborn813075a62011-11-14 17:45:19 -080013105 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013106 saveLocaleLocked(values.locale,
13107 !values.locale.equals(mConfiguration.locale),
13108 values.userSetLocale);
13109 }
13110
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013111 mConfigurationSeq++;
13112 if (mConfigurationSeq <= 0) {
13113 mConfigurationSeq = 1;
13114 }
13115 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013116 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013117 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013118
13119 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013120
13121 // TODO: If our config changes, should we auto dismiss any currently
13122 // showing dialogs?
13123 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013124
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013125 AttributeCache ac = AttributeCache.instance();
13126 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013127 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013129
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013130 // Make sure all resources in our process are updated
13131 // right now, so that anyone who is going to retrieve
13132 // resource values after we return will be sure to get
13133 // the new ones. This is especially important during
13134 // boot, where the first config change needs to guarantee
13135 // all resources have that config before following boot
13136 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013137 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013138
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013139 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013140 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013141 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013142 mHandler.sendMessage(msg);
13143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013144
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013145 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13146 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013147 try {
13148 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013149 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013150 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013151 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013152 }
13153 } catch (Exception e) {
13154 }
13155 }
13156 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013157 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13158 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013159 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013160 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013161 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13162 broadcastIntentLocked(null, null,
13163 new Intent(Intent.ACTION_LOCALE_CHANGED),
13164 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013165 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013167 }
13168 }
13169
13170 if (changes != 0 && starting == null) {
13171 // If the configuration changed, and the caller is not already
13172 // in the process of starting an activity, then find the top
13173 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013174 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013175 }
13176
13177 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013178 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013179 // And we need to make sure at this point that all other activities
13180 // are made visible with the correct configuration.
13181 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013182 }
13183
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013184 if (values != null && mWindowManager != null) {
13185 mWindowManager.setNewConfiguration(mConfiguration);
13186 }
13187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013188 return kept;
13189 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013190
13191 /**
13192 * Decide based on the configuration whether we should shouw the ANR,
13193 * crash, etc dialogs. The idea is that if there is no affordnace to
13194 * press the on-screen buttons, we shouldn't show the dialog.
13195 *
13196 * A thought: SystemUI might also want to get told about this, the Power
13197 * dialog / global actions also might want different behaviors.
13198 */
13199 private static final boolean shouldShowDialogs(Configuration config) {
13200 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13201 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013203
13204 /**
13205 * Save the locale. You must be inside a synchronized (this) block.
13206 */
13207 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13208 if(isDiff) {
13209 SystemProperties.set("user.language", l.getLanguage());
13210 SystemProperties.set("user.region", l.getCountry());
13211 }
13212
13213 if(isPersist) {
13214 SystemProperties.set("persist.sys.language", l.getLanguage());
13215 SystemProperties.set("persist.sys.country", l.getCountry());
13216 SystemProperties.set("persist.sys.localevar", l.getVariant());
13217 }
13218 }
13219
13220 // =========================================================
13221 // LIFETIME MANAGEMENT
13222 // =========================================================
13223
Christopher Tatef46723b2012-01-26 14:19:24 -080013224 // Returns which broadcast queue the app is the current [or imminent] receiver
13225 // on, or 'null' if the app is not an active broadcast recipient.
13226 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13227 BroadcastRecord r = app.curReceiver;
13228 if (r != null) {
13229 return r.queue;
13230 }
13231
13232 // It's not the current receiver, but it might be starting up to become one
13233 synchronized (this) {
13234 for (BroadcastQueue queue : mBroadcastQueues) {
13235 r = queue.mPendingBroadcast;
13236 if (r != null && r.curApp == app) {
13237 // found it; report which queue it's in
13238 return queue;
13239 }
13240 }
13241 }
13242
13243 return null;
13244 }
13245
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013246 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013247 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013248 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013249 // This adjustment has already been computed. If we are calling
13250 // from the top, we may have already computed our adjustment with
13251 // an earlier hidden adjustment that isn't really for us... if
13252 // so, use the new hidden adjustment.
13253 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013254 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013255 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013256 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013257 }
13258
13259 if (app.thread == null) {
13260 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013261 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013262 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013263 }
13264
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013265 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13266 app.adjSource = null;
13267 app.adjTarget = null;
13268 app.empty = false;
13269 app.hidden = false;
13270
13271 final int activitiesSize = app.activities.size();
13272
Dianne Hackborn7d608422011-08-07 16:24:18 -070013273 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013274 // The max adjustment doesn't allow this app to be anything
13275 // below foreground, so it is not worth doing work for it.
13276 app.adjType = "fixed";
13277 app.adjSeq = mAdjSeq;
13278 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013279 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013280 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013281 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013282 // System process can do UI, and when they do we want to have
13283 // them trim their memory after the user leaves the UI. To
13284 // facilitate this, here we need to determine whether or not it
13285 // is currently showing UI.
13286 app.systemNoUi = true;
13287 if (app == TOP_APP) {
13288 app.systemNoUi = false;
13289 } else if (activitiesSize > 0) {
13290 for (int j = 0; j < activitiesSize; j++) {
13291 final ActivityRecord r = app.activities.get(j);
13292 if (r.visible) {
13293 app.systemNoUi = false;
13294 break;
13295 }
13296 }
13297 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013298 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013299 }
13300
13301 final boolean hadForegroundActivities = app.foregroundActivities;
13302
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013303 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013304 app.keeping = false;
13305 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013306
The Android Open Source Project4df24232009-03-05 14:34:35 -080013307 // Determine the importance of the process, starting with most
13308 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013309 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013310 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013311 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013312 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013313 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013314 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013315 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013316 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013317 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013318 } else if (app.instrumentationClass != null) {
13319 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013320 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013321 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013322 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013323 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013324 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013325 // counts as being in the foreground for OOM killer purposes.
13326 // It's placed in a sched group based on the nature of the
13327 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013328 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013329 schedGroup = (queue == mFgBroadcastQueue)
13330 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013331 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013332 } else if (app.executingServices.size() > 0) {
13333 // An app that is currently executing a service callback also
13334 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013335 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013336 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013337 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013338 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013339 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013340 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013341 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013342 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013343 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013344 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013345 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013346 // A very not-needed process. If this is lower in the lru list,
13347 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013348 adj = hiddenAdj;
13349 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013350 app.hidden = true;
13351 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013352 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013353 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013354
13355 // Examine all activities if not already foreground.
13356 if (!app.foregroundActivities && activitiesSize > 0) {
13357 for (int j = 0; j < activitiesSize; j++) {
13358 final ActivityRecord r = app.activities.get(j);
13359 if (r.visible) {
13360 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013361 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13362 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013363 app.adjType = "visible";
13364 }
13365 schedGroup = Process.THREAD_GROUP_DEFAULT;
13366 app.hidden = false;
13367 app.foregroundActivities = true;
13368 break;
13369 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13370 || r.state == ActivityState.STOPPING) {
13371 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013372 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13373 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013374 app.adjType = "stopping";
13375 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013376 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013377 app.foregroundActivities = true;
13378 }
13379 }
13380 }
13381
Dianne Hackborn7d608422011-08-07 16:24:18 -070013382 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013383 if (app.foregroundServices) {
13384 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013385 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013386 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013387 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013388 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013389 } else if (app.forcingToForeground != null) {
13390 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013391 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013392 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013393 app.adjType = "force-foreground";
13394 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013395 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013396 }
13397 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013398
Dianne Hackborn7d608422011-08-07 16:24:18 -070013399 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013400 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013401 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013402 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013403 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013404 app.adjType = "heavy";
13405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013406
Dianne Hackborn7d608422011-08-07 16:24:18 -070013407 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013408 // This process is hosting what we currently consider to be the
13409 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013410 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013411 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013412 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013413 app.adjType = "home";
13414 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013415
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013416 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13417 && app.activities.size() > 0) {
13418 // This was the previous process that showed UI to the user.
13419 // We want to try to keep it around more aggressively, to give
13420 // a good experience around switching between two apps.
13421 adj = ProcessList.PREVIOUS_APP_ADJ;
13422 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13423 app.hidden = false;
13424 app.adjType = "previous";
13425 }
13426
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013427 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13428 + " reason=" + app.adjType);
13429
The Android Open Source Project4df24232009-03-05 14:34:35 -080013430 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013431 // there are applications dependent on our services or providers, but
13432 // this gives us a baseline and makes sure we don't get into an
13433 // infinite recursion.
13434 app.adjSeq = mAdjSeq;
13435 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013436
Christopher Tate6fa95972009-06-05 18:43:55 -070013437 if (mBackupTarget != null && app == mBackupTarget.app) {
13438 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013439 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013440 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013441 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013442 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013443 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013444 }
13445 }
13446
Dianne Hackborn7d608422011-08-07 16:24:18 -070013447 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013448 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013449 final long now = SystemClock.uptimeMillis();
13450 // This process is more important if the top activity is
13451 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013452 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013453 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013454 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013455 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013456 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013457 // If this process has shown some UI, let it immediately
13458 // go to the LRU list because it may be pretty heavy with
13459 // UI stuff. We'll tag it with a label just to help
13460 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013461 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013462 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013463 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013464 } else {
13465 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13466 // This service has seen some activity within
13467 // recent memory, so we will keep its process ahead
13468 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013469 if (adj > ProcessList.SERVICE_ADJ) {
13470 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013471 app.adjType = "started-services";
13472 app.hidden = false;
13473 }
13474 }
13475 // If we have let the service slide into the background
13476 // state, still have some text describing what it is doing
13477 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013478 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013479 app.adjType = "started-bg-services";
13480 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013481 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013482 // Don't kill this process because it is doing work; it
13483 // has said it is doing work.
13484 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013485 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013486 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013487 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013488 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013489 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013490 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013491 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013492 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013493 // XXX should compute this based on the max of
13494 // all connected clients.
13495 ConnectionRecord cr = clist.get(i);
13496 if (cr.binding.client == app) {
13497 // Binding to ourself is not interesting.
13498 continue;
13499 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013500 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013501 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013502 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013503 int myHiddenAdj = hiddenAdj;
13504 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013505 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013506 myHiddenAdj = client.hiddenAdj;
13507 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013508 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013509 }
13510 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013511 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013512 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013513 String adjType = null;
13514 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13515 // Not doing bind OOM management, so treat
13516 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013517 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013518 // If this process has shown some UI, let it immediately
13519 // go to the LRU list because it may be pretty heavy with
13520 // UI stuff. We'll tag it with a label just to help
13521 // debug and understand what is going on.
13522 if (adj > clientAdj) {
13523 adjType = "bound-bg-ui-services";
13524 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013525 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013526 clientAdj = adj;
13527 } else {
13528 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13529 // This service has not seen activity within
13530 // recent memory, so allow it to drop to the
13531 // LRU list if there is no other reason to keep
13532 // it around. We'll also tag it with a label just
13533 // to help debug and undertand what is going on.
13534 if (adj > clientAdj) {
13535 adjType = "bound-bg-services";
13536 }
13537 clientAdj = adj;
13538 }
13539 }
13540 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013541 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013542 // If this process has recently shown UI, and
13543 // the process that is binding to it is less
13544 // important than being visible, then we don't
13545 // care about the binding as much as we care
13546 // about letting this process get into the LRU
13547 // list to be killed and restarted if needed for
13548 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013549 if (app.hasShownUi && app != mHomeProcess
13550 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013551 adjType = "bound-bg-ui-services";
13552 } else {
13553 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13554 |Context.BIND_IMPORTANT)) != 0) {
13555 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013556 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13557 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13558 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13559 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13560 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013561 adj = clientAdj;
13562 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013563 app.pendingUiClean = true;
13564 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13565 adj = ProcessList.VISIBLE_APP_ADJ;
13566 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013567 }
13568 if (!client.hidden) {
13569 app.hidden = false;
13570 }
13571 if (client.keeping) {
13572 app.keeping = true;
13573 }
13574 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013575 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013576 }
13577 if (adjType != null) {
13578 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013579 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13580 .REASON_SERVICE_IN_USE;
13581 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013582 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013583 app.adjTarget = s.name;
13584 }
13585 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13586 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13587 schedGroup = Process.THREAD_GROUP_DEFAULT;
13588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013589 }
13590 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013591 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13592 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013593 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013594 (a.visible || a.state == ActivityState.RESUMED
13595 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013596 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013597 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13598 schedGroup = Process.THREAD_GROUP_DEFAULT;
13599 }
13600 app.hidden = false;
13601 app.adjType = "service";
13602 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13603 .REASON_SERVICE_IN_USE;
13604 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013605 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013606 app.adjTarget = s.name;
13607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013609 }
13610 }
13611 }
13612 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013613
Dianne Hackborn287952c2010-09-22 22:34:31 -070013614 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013615 // would like to avoid killing it unless it would prevent the current
13616 // application from running. By default we put the process in
13617 // with the rest of the background processes; as we scan through
13618 // its services we may bump it up from there.
13619 if (adj > hiddenAdj) {
13620 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013621 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013622 app.adjType = "bg-services";
13623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013624 }
13625
Dianne Hackborn7d608422011-08-07 16:24:18 -070013626 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013627 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013628 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013629 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013630 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013631 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013632 if (cpr.clients.size() != 0) {
13633 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013634 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013635 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013636 if (client == app) {
13637 // Being our own client is not interesting.
13638 continue;
13639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013640 int myHiddenAdj = hiddenAdj;
13641 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013642 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013643 myHiddenAdj = client.hiddenAdj;
13644 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013645 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013646 }
13647 }
13648 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013649 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013650 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013651 if (app.hasShownUi && app != mHomeProcess
13652 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013653 app.adjType = "bg-ui-provider";
13654 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013655 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13656 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013657 app.adjType = "provider";
13658 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013659 if (!client.hidden) {
13660 app.hidden = false;
13661 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013662 if (client.keeping) {
13663 app.keeping = true;
13664 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013665 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13666 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013667 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013668 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013669 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013670 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013671 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13672 schedGroup = Process.THREAD_GROUP_DEFAULT;
13673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013674 }
13675 }
13676 // If the provider has external (non-framework) process
13677 // dependencies, ensure that its adjustment is at least
13678 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013679 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013680 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13681 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013682 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013683 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013684 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013685 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013686 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013687 }
13688 }
13689 }
13690 }
13691
13692 app.curRawAdj = adj;
13693
Joe Onorato8a9b2202010-02-26 18:56:32 -080013694 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013695 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13696 if (adj > app.maxAdj) {
13697 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013698 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013699 schedGroup = Process.THREAD_GROUP_DEFAULT;
13700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013701 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013702 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013703 app.keeping = true;
13704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013705
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013706 if (app.hasAboveClient) {
13707 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13708 // then we need to drop its adjustment to be lower than the service's
13709 // in order to honor the request. We want to drop it by one adjustment
13710 // level... but there is special meaning applied to various levels so
13711 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013712 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013713 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013714 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13715 adj = ProcessList.VISIBLE_APP_ADJ;
13716 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13717 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13718 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13719 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013720 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013721 adj++;
13722 }
13723 }
13724
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013725 if (adj == ProcessList.SERVICE_ADJ) {
13726 if (doingAll) {
13727 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13728 mNewNumServiceProcs++;
13729 }
13730 if (app.serviceb) {
13731 adj = ProcessList.SERVICE_B_ADJ;
13732 }
13733 } else {
13734 app.serviceb = false;
13735 }
13736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013737 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013738 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013739
13740 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013741 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13742 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013743 }
13744
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013745 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013746 }
13747
13748 /**
13749 * Ask a given process to GC right now.
13750 */
13751 final void performAppGcLocked(ProcessRecord app) {
13752 try {
13753 app.lastRequestedGc = SystemClock.uptimeMillis();
13754 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013755 if (app.reportLowMemory) {
13756 app.reportLowMemory = false;
13757 app.thread.scheduleLowMemory();
13758 } else {
13759 app.thread.processInBackground();
13760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013761 }
13762 } catch (Exception e) {
13763 // whatever.
13764 }
13765 }
13766
13767 /**
13768 * Returns true if things are idle enough to perform GCs.
13769 */
Josh Bartel7f208742010-02-25 11:01:44 -060013770 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013771 boolean processingBroadcasts = false;
13772 for (BroadcastQueue q : mBroadcastQueues) {
13773 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13774 processingBroadcasts = true;
13775 }
13776 }
13777 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013778 && (mSleeping || (mMainStack.mResumedActivity != null &&
13779 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013780 }
13781
13782 /**
13783 * Perform GCs on all processes that are waiting for it, but only
13784 * if things are idle.
13785 */
13786 final void performAppGcsLocked() {
13787 final int N = mProcessesToGc.size();
13788 if (N <= 0) {
13789 return;
13790 }
Josh Bartel7f208742010-02-25 11:01:44 -060013791 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013792 while (mProcessesToGc.size() > 0) {
13793 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013794 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013795 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13796 <= SystemClock.uptimeMillis()) {
13797 // To avoid spamming the system, we will GC processes one
13798 // at a time, waiting a few seconds between each.
13799 performAppGcLocked(proc);
13800 scheduleAppGcsLocked();
13801 return;
13802 } else {
13803 // It hasn't been long enough since we last GCed this
13804 // process... put it in the list to wait for its time.
13805 addProcessToGcListLocked(proc);
13806 break;
13807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013808 }
13809 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013810
13811 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013812 }
13813 }
13814
13815 /**
13816 * If all looks good, perform GCs on all processes waiting for them.
13817 */
13818 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013819 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013820 performAppGcsLocked();
13821 return;
13822 }
13823 // Still not idle, wait some more.
13824 scheduleAppGcsLocked();
13825 }
13826
13827 /**
13828 * Schedule the execution of all pending app GCs.
13829 */
13830 final void scheduleAppGcsLocked() {
13831 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013832
13833 if (mProcessesToGc.size() > 0) {
13834 // Schedule a GC for the time to the next process.
13835 ProcessRecord proc = mProcessesToGc.get(0);
13836 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13837
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013838 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013839 long now = SystemClock.uptimeMillis();
13840 if (when < (now+GC_TIMEOUT)) {
13841 when = now + GC_TIMEOUT;
13842 }
13843 mHandler.sendMessageAtTime(msg, when);
13844 }
13845 }
13846
13847 /**
13848 * Add a process to the array of processes waiting to be GCed. Keeps the
13849 * list in sorted order by the last GC time. The process can't already be
13850 * on the list.
13851 */
13852 final void addProcessToGcListLocked(ProcessRecord proc) {
13853 boolean added = false;
13854 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13855 if (mProcessesToGc.get(i).lastRequestedGc <
13856 proc.lastRequestedGc) {
13857 added = true;
13858 mProcessesToGc.add(i+1, proc);
13859 break;
13860 }
13861 }
13862 if (!added) {
13863 mProcessesToGc.add(0, proc);
13864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013865 }
13866
13867 /**
13868 * Set up to ask a process to GC itself. This will either do it
13869 * immediately, or put it on the list of processes to gc the next
13870 * time things are idle.
13871 */
13872 final void scheduleAppGcLocked(ProcessRecord app) {
13873 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013874 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013875 return;
13876 }
13877 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013878 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013879 scheduleAppGcsLocked();
13880 }
13881 }
13882
Dianne Hackborn287952c2010-09-22 22:34:31 -070013883 final void checkExcessivePowerUsageLocked(boolean doKills) {
13884 updateCpuStatsNow();
13885
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013886 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013887 boolean doWakeKills = doKills;
13888 boolean doCpuKills = doKills;
13889 if (mLastPowerCheckRealtime == 0) {
13890 doWakeKills = false;
13891 }
13892 if (mLastPowerCheckUptime == 0) {
13893 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013894 }
13895 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013896 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013897 }
13898 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013899 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13900 final long curUptime = SystemClock.uptimeMillis();
13901 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13902 mLastPowerCheckRealtime = curRealtime;
13903 mLastPowerCheckUptime = curUptime;
13904 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13905 doWakeKills = false;
13906 }
13907 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13908 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013909 }
13910 int i = mLruProcesses.size();
13911 while (i > 0) {
13912 i--;
13913 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013914 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013915 long wtime;
13916 synchronized (stats) {
13917 wtime = stats.getProcessWakeTime(app.info.uid,
13918 app.pid, curRealtime);
13919 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013920 long wtimeUsed = wtime - app.lastWakeTime;
13921 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13922 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013923 StringBuilder sb = new StringBuilder(128);
13924 sb.append("Wake for ");
13925 app.toShortString(sb);
13926 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013927 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013928 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013929 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013930 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013931 sb.append((wtimeUsed*100)/realtimeSince);
13932 sb.append("%)");
13933 Slog.i(TAG, sb.toString());
13934 sb.setLength(0);
13935 sb.append("CPU for ");
13936 app.toShortString(sb);
13937 sb.append(": over ");
13938 TimeUtils.formatDuration(uptimeSince, sb);
13939 sb.append(" used ");
13940 TimeUtils.formatDuration(cputimeUsed, sb);
13941 sb.append(" (");
13942 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013943 sb.append("%)");
13944 Slog.i(TAG, sb.toString());
13945 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013946 // If a process has held a wake lock for more
13947 // than 50% of the time during this period,
13948 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013949 if (doWakeKills && realtimeSince > 0
13950 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13951 synchronized (stats) {
13952 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13953 realtimeSince, wtimeUsed);
13954 }
13955 Slog.w(TAG, "Excessive wake lock in " + app.processName
13956 + " (pid " + app.pid + "): held " + wtimeUsed
13957 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013958 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13959 app.processName, app.setAdj, "excessive wake lock");
13960 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013961 } else if (doCpuKills && uptimeSince > 0
13962 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13963 synchronized (stats) {
13964 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13965 uptimeSince, cputimeUsed);
13966 }
13967 Slog.w(TAG, "Excessive CPU in " + app.processName
13968 + " (pid " + app.pid + "): used " + cputimeUsed
13969 + " during " + uptimeSince);
13970 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13971 app.processName, app.setAdj, "excessive cpu");
13972 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013973 } else {
13974 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013975 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013976 }
13977 }
13978 }
13979 }
13980
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013981 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013982 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013983 app.hiddenAdj = hiddenAdj;
13984
13985 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013986 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013987 }
13988
Dianne Hackborn287952c2010-09-22 22:34:31 -070013989 final boolean wasKeeping = app.keeping;
13990
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013991 boolean success = true;
13992
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013993 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013994
Jeff Brown10e89712011-07-08 18:52:57 -070013995 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013996 if (false) {
13997 // Removing for now. Forcing GCs is not so useful anymore
13998 // with Dalvik, and the new memory level hint facility is
13999 // better for what we need to do these days.
14000 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14001 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14002 // If this app is transitioning from foreground to
14003 // non-foreground, have it do a gc.
14004 scheduleAppGcLocked(app);
14005 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14006 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14007 // Likewise do a gc when an app is moving in to the
14008 // background (such as a service stopping).
14009 scheduleAppGcLocked(app);
14010 }
Jeff Brown10e89712011-07-08 18:52:57 -070014011 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014012
Jeff Brown10e89712011-07-08 18:52:57 -070014013 if (wasKeeping && !app.keeping) {
14014 // This app is no longer something we want to keep. Note
14015 // its current wake lock time to later know to kill it if
14016 // it is not behaving well.
14017 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14018 synchronized (stats) {
14019 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14020 app.pid, SystemClock.elapsedRealtime());
14021 }
14022 app.lastCpuTime = app.curCpuTime;
14023 }
14024
14025 app.setRawAdj = app.curRawAdj;
14026 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014027
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014028 if (app.curAdj != app.setAdj) {
14029 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014030 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014031 TAG, "Set " + app.pid + " " + app.processName +
14032 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014033 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014034 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014035 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014036 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014037 }
14038 }
14039 if (app.setSchedGroup != app.curSchedGroup) {
14040 app.setSchedGroup = app.curSchedGroup;
14041 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14042 "Setting process group of " + app.processName
14043 + " to " + app.curSchedGroup);
14044 if (app.waitingToKill != null &&
14045 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14046 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14047 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14048 app.processName, app.setAdj, app.waitingToKill);
14049 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014050 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014051 } else {
14052 if (true) {
14053 long oldId = Binder.clearCallingIdentity();
14054 try {
14055 Process.setProcessGroup(app.pid, app.curSchedGroup);
14056 } catch (Exception e) {
14057 Slog.w(TAG, "Failed setting process group of " + app.pid
14058 + " to " + app.curSchedGroup);
14059 e.printStackTrace();
14060 } finally {
14061 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014062 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014063 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014064 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014065 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014066 app.thread.setSchedulingGroup(app.curSchedGroup);
14067 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014068 }
14069 }
14070 }
14071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014072 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014073 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014074 }
14075
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014076 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014077 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014078 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014079 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014080 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014081 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014082 }
14083 }
14084 return resumedActivity;
14085 }
14086
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014087 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014088 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014089 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14090 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014091 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14092 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014093
14094 mAdjSeq++;
14095
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014096 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014097 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14098 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014099 if (nowHidden != wasHidden) {
14100 // Changed to/from hidden state, so apps after it in the LRU
14101 // list may also be changed.
14102 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014103 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014104 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014105 }
14106
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014107 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014108 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014109 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14110
14111 if (false) {
14112 RuntimeException e = new RuntimeException();
14113 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014114 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014115 }
14116
14117 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014118 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014119
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014120 // Let's determine how many processes we have running vs.
14121 // how many slots we have for background processes; we may want
14122 // to put multiple processes in a slot of there are enough of
14123 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014124 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014125 int factor = (mLruProcesses.size()-4)/numSlots;
14126 if (factor < 1) factor = 1;
14127 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014128 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014129
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014130 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014131 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014132 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014133 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014134 while (i > 0) {
14135 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014136 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014137 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014138 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14139 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014140 && app.curAdj == curHiddenAdj) {
14141 step++;
14142 if (step >= factor) {
14143 step = 0;
14144 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014145 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014146 }
14147 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014148 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014149 numHidden++;
14150 if (numHidden > mProcessLimit) {
14151 Slog.i(TAG, "No longer want " + app.processName
14152 + " (pid " + app.pid + "): hidden #" + numHidden);
14153 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14154 app.processName, app.setAdj, "too many background");
14155 app.killedBackground = true;
14156 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014157 }
14158 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014159 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14160 // If this is an isolated process, and there are no
14161 // services running in it, then the process is no longer
14162 // needed. We agressively kill these because we can by
14163 // definition not re-use the same process again, and it is
14164 // good to avoid having whatever code was running in them
14165 // left sitting around after no longer needed.
14166 Slog.i(TAG, "Isolated process " + app.processName
14167 + " (pid " + app.pid + ") no longer needed");
14168 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14169 app.processName, app.setAdj, "isolated not needed");
14170 app.killedBackground = true;
14171 Process.killProcessQuiet(app.pid);
14172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014173 }
14174 }
14175
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014176 mNumServiceProcs = mNewNumServiceProcs;
14177
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014178 // Now determine the memory trimming level of background processes.
14179 // Unfortunately we need to start at the back of the list to do this
14180 // properly. We only do this if the number of background apps we
14181 // are managing to keep around is less than half the maximum we desire;
14182 // if we are keeping a good number around, we'll let them use whatever
14183 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014184 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014185 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014186 factor = numHidden/3;
14187 int minFactor = 2;
14188 if (mHomeProcess != null) minFactor++;
14189 if (mPreviousProcess != null) minFactor++;
14190 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014191 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014192 int fgTrimLevel;
14193 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14194 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14195 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14196 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14197 } else {
14198 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14199 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014200 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014201 for (i=0; i<N; i++) {
14202 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014203 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14204 && app.curAdj != ProcessList.SERVICE_B_ADJ
14205 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014206 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14207 try {
14208 app.thread.scheduleTrimMemory(curLevel);
14209 } catch (RemoteException e) {
14210 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014211 if (false) {
14212 // For now we won't do this; our memory trimming seems
14213 // to be good enough at this point that destroying
14214 // activities causes more harm than good.
14215 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14216 && app != mHomeProcess && app != mPreviousProcess) {
14217 // For these apps we will also finish their activities
14218 // to help them free memory.
14219 mMainStack.destroyActivitiesLocked(app, false, "trim");
14220 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014221 }
14222 }
14223 app.trimMemoryLevel = curLevel;
14224 step++;
14225 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014226 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014227 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014228 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14229 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014230 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014231 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14232 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014233 break;
14234 }
14235 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014236 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014237 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014238 && app.thread != null) {
14239 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014240 app.thread.scheduleTrimMemory(
14241 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014242 } catch (RemoteException e) {
14243 }
14244 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014245 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014246 } else {
14247 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14248 && app.pendingUiClean) {
14249 // If this application is now in the background and it
14250 // had done UI, then give it the special trim level to
14251 // have it free UI resources.
14252 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14253 if (app.trimMemoryLevel < level && app.thread != null) {
14254 try {
14255 app.thread.scheduleTrimMemory(level);
14256 } catch (RemoteException e) {
14257 }
14258 }
14259 app.pendingUiClean = false;
14260 }
14261 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014262 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014263 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014264 } catch (RemoteException e) {
14265 }
14266 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014267 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014268 }
14269 }
14270 } else {
14271 final int N = mLruProcesses.size();
14272 for (i=0; i<N; i++) {
14273 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014274 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014275 && app.pendingUiClean) {
14276 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14277 && app.thread != null) {
14278 try {
14279 app.thread.scheduleTrimMemory(
14280 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14281 } catch (RemoteException e) {
14282 }
14283 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014284 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014285 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014286 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014287 }
14288 }
14289
14290 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014291 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014293 }
14294
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014295 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014296 synchronized (this) {
14297 int i;
14298
14299 // First remove any unused application processes whose package
14300 // has been removed.
14301 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14302 final ProcessRecord app = mRemovedProcesses.get(i);
14303 if (app.activities.size() == 0
14304 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014305 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014306 TAG, "Exiting empty application process "
14307 + app.processName + " ("
14308 + (app.thread != null ? app.thread.asBinder() : null)
14309 + ")\n");
14310 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014311 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14312 app.processName, app.setAdj, "empty");
14313 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014314 } else {
14315 try {
14316 app.thread.scheduleExit();
14317 } catch (Exception e) {
14318 // Ignore exceptions.
14319 }
14320 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014321 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014322 mRemovedProcesses.remove(i);
14323
14324 if (app.persistent) {
14325 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014326 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014327 }
14328 }
14329 }
14330 }
14331
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014332 // Now update the oom adj for all processes.
14333 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014334 }
14335 }
14336
14337 /** This method sends the specified signal to each of the persistent apps */
14338 public void signalPersistentProcesses(int sig) throws RemoteException {
14339 if (sig != Process.SIGNAL_USR1) {
14340 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14341 }
14342
14343 synchronized (this) {
14344 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14345 != PackageManager.PERMISSION_GRANTED) {
14346 throw new SecurityException("Requires permission "
14347 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14348 }
14349
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014350 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14351 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014352 if (r.thread != null && r.persistent) {
14353 Process.sendSignal(r.pid, sig);
14354 }
14355 }
14356 }
14357 }
14358
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014359 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14360 if (proc == null || proc == mProfileProc) {
14361 proc = mProfileProc;
14362 path = mProfileFile;
14363 profileType = mProfileType;
14364 clearProfilerLocked();
14365 }
14366 if (proc == null) {
14367 return;
14368 }
14369 try {
14370 proc.thread.profilerControl(false, path, null, profileType);
14371 } catch (RemoteException e) {
14372 throw new IllegalStateException("Process disappeared");
14373 }
14374 }
14375
14376 private void clearProfilerLocked() {
14377 if (mProfileFd != null) {
14378 try {
14379 mProfileFd.close();
14380 } catch (IOException e) {
14381 }
14382 }
14383 mProfileApp = null;
14384 mProfileProc = null;
14385 mProfileFile = null;
14386 mProfileType = 0;
14387 mAutoStopProfiler = false;
14388 }
14389
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014390 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014391 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014392
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014393 try {
14394 synchronized (this) {
14395 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14396 // its own permission.
14397 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14398 != PackageManager.PERMISSION_GRANTED) {
14399 throw new SecurityException("Requires permission "
14400 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014401 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014402
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014403 if (start && fd == null) {
14404 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014405 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014406
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014407 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014408 if (process != null) {
14409 try {
14410 int pid = Integer.parseInt(process);
14411 synchronized (mPidsSelfLocked) {
14412 proc = mPidsSelfLocked.get(pid);
14413 }
14414 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014415 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014416
14417 if (proc == null) {
14418 HashMap<String, SparseArray<ProcessRecord>> all
14419 = mProcessNames.getMap();
14420 SparseArray<ProcessRecord> procs = all.get(process);
14421 if (procs != null && procs.size() > 0) {
14422 proc = procs.valueAt(0);
14423 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014424 }
14425 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014426
14427 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014428 throw new IllegalArgumentException("Unknown process: " + process);
14429 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014430
14431 if (start) {
14432 stopProfilerLocked(null, null, 0);
14433 setProfileApp(proc.info, proc.processName, path, fd, false);
14434 mProfileProc = proc;
14435 mProfileType = profileType;
14436 try {
14437 fd = fd.dup();
14438 } catch (IOException e) {
14439 fd = null;
14440 }
14441 proc.thread.profilerControl(start, path, fd, profileType);
14442 fd = null;
14443 mProfileFd = null;
14444 } else {
14445 stopProfilerLocked(proc, path, profileType);
14446 if (fd != null) {
14447 try {
14448 fd.close();
14449 } catch (IOException e) {
14450 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014451 }
14452 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014453
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014454 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014455 }
14456 } catch (RemoteException e) {
14457 throw new IllegalStateException("Process disappeared");
14458 } finally {
14459 if (fd != null) {
14460 try {
14461 fd.close();
14462 } catch (IOException e) {
14463 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014464 }
14465 }
14466 }
Andy McFadden824c5102010-07-09 16:26:57 -070014467
14468 public boolean dumpHeap(String process, boolean managed,
14469 String path, ParcelFileDescriptor fd) throws RemoteException {
14470
14471 try {
14472 synchronized (this) {
14473 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14474 // its own permission (same as profileControl).
14475 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14476 != PackageManager.PERMISSION_GRANTED) {
14477 throw new SecurityException("Requires permission "
14478 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14479 }
14480
14481 if (fd == null) {
14482 throw new IllegalArgumentException("null fd");
14483 }
14484
14485 ProcessRecord proc = null;
14486 try {
14487 int pid = Integer.parseInt(process);
14488 synchronized (mPidsSelfLocked) {
14489 proc = mPidsSelfLocked.get(pid);
14490 }
14491 } catch (NumberFormatException e) {
14492 }
14493
14494 if (proc == null) {
14495 HashMap<String, SparseArray<ProcessRecord>> all
14496 = mProcessNames.getMap();
14497 SparseArray<ProcessRecord> procs = all.get(process);
14498 if (procs != null && procs.size() > 0) {
14499 proc = procs.valueAt(0);
14500 }
14501 }
14502
14503 if (proc == null || proc.thread == null) {
14504 throw new IllegalArgumentException("Unknown process: " + process);
14505 }
14506
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014507 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14508 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014509 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14510 throw new SecurityException("Process not debuggable: " + proc);
14511 }
14512 }
14513
14514 proc.thread.dumpHeap(managed, path, fd);
14515 fd = null;
14516 return true;
14517 }
14518 } catch (RemoteException e) {
14519 throw new IllegalStateException("Process disappeared");
14520 } finally {
14521 if (fd != null) {
14522 try {
14523 fd.close();
14524 } catch (IOException e) {
14525 }
14526 }
14527 }
14528 }
14529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014530 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14531 public void monitor() {
14532 synchronized (this) { }
14533 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014534
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014535 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014536 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14537 ProcessRecord processRecord = mLruProcesses.get(i);
14538 try {
14539 if (processRecord.thread != null) {
14540 processRecord.thread.setCoreSettings(settings);
14541 }
14542 } catch (RemoteException re) {
14543 /* ignore */
14544 }
14545 }
14546 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014547
14548 // Multi-user methods
14549
Amith Yamasani742a6712011-05-04 14:49:28 -070014550 private int mCurrentUserId;
14551 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014552 private ArrayList<UserListener> mUserListeners = new ArrayList<UserListener>(3);
14553
14554 public interface UserListener {
14555 public void onUserChanged(int userId);
14556
14557 public void onUserAdded(int userId);
14558
14559 public void onUserRemoved(int userId);
14560
14561 public void onUserLoggedOut(int userId);
14562 }
14563
14564 public void addUserListener(UserListener listener) {
14565 synchronized (this) {
14566 if (!mUserListeners.contains(listener)) {
14567 mUserListeners.add(listener);
14568 }
14569 }
14570 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014571
14572 public boolean switchUser(int userId) {
14573 final int callingUid = Binder.getCallingUid();
14574 if (callingUid != 0 && callingUid != Process.myUid()) {
14575 Slog.e(TAG, "Trying to switch user from unauthorized app");
14576 return false;
14577 }
14578 if (mCurrentUserId == userId)
14579 return true;
14580
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014581 ArrayList<UserListener> listeners;
14582
Amith Yamasani742a6712011-05-04 14:49:28 -070014583 synchronized (this) {
14584 // Check if user is already logged in, otherwise check if user exists first before
14585 // adding to the list of logged in users.
14586 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14587 if (!userExists(userId)) {
14588 return false;
14589 }
14590 mLoggedInUsers.append(userId, userId);
14591 }
14592
14593 mCurrentUserId = userId;
14594 boolean haveActivities = mMainStack.switchUser(userId);
14595 if (!haveActivities) {
14596 startHomeActivityLocked(userId);
14597 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014598
14599 listeners = (ArrayList<UserListener>) mUserListeners.clone();
14600 }
14601 // Inform the listeners
14602 for (UserListener listener : listeners) {
14603 listener.onUserChanged(userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070014604 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014605 return true;
14606 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014607
14608 private boolean userExists(int userId) {
14609 try {
14610 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14611 for (UserInfo user : users) {
14612 if (user.id == userId) {
14613 return true;
14614 }
14615 }
14616 } catch (RemoteException re) {
14617 // Won't happen, in same process
14618 }
14619
14620 return false;
14621 }
14622
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014623 private void checkValidCaller(int uid, int userId) {
14624 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14625
14626 throw new SecurityException("Caller uid=" + uid
14627 + " is not privileged to communicate with user=" + userId);
14628 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014629
14630 private int applyUserId(int uid, int userId) {
14631 return UserId.getUid(userId, uid);
14632 }
14633
14634 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014635 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014636 ApplicationInfo newInfo = new ApplicationInfo(info);
14637 newInfo.uid = applyUserId(info.uid, userId);
14638 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14639 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14640 + info.packageName;
14641 }
14642 return newInfo;
14643 }
14644
14645 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014646 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014647 || userId < 1) {
14648 return aInfo;
14649 }
14650
14651 ActivityInfo info = new ActivityInfo(aInfo);
14652 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14653 return info;
14654 }
14655
14656 static class ServiceMap {
14657
14658 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14659 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14660 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14661 mServicesByIntentPerUser = new SparseArray<
14662 HashMap<Intent.FilterComparison, ServiceRecord>>();
14663
14664 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14665 // TODO: Deal with global services
14666 if (DEBUG_MU)
14667 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14668 return getServices(callingUser).get(name);
14669 }
14670
14671 ServiceRecord getServiceByName(ComponentName name) {
14672 return getServiceByName(name, -1);
14673 }
14674
14675 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14676 // TODO: Deal with global services
14677 if (DEBUG_MU)
14678 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14679 return getServicesByIntent(callingUser).get(filter);
14680 }
14681
14682 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14683 return getServiceByIntent(filter, -1);
14684 }
14685
14686 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14687 // TODO: Deal with global services
14688 getServices(callingUser).put(name, value);
14689 }
14690
14691 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14692 ServiceRecord value) {
14693 // TODO: Deal with global services
14694 getServicesByIntent(callingUser).put(filter, value);
14695 }
14696
14697 void removeServiceByName(ComponentName name, int callingUser) {
14698 // TODO: Deal with global services
14699 ServiceRecord removed = getServices(callingUser).remove(name);
14700 if (DEBUG_MU)
14701 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14702 + " removed=" + removed);
14703 }
14704
14705 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14706 // TODO: Deal with global services
14707 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14708 if (DEBUG_MU)
14709 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14710 + " removed=" + removed);
14711 }
14712
14713 Collection<ServiceRecord> getAllServices(int callingUser) {
14714 // TODO: Deal with global services
14715 return getServices(callingUser).values();
14716 }
14717
14718 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14719 HashMap map = mServicesByNamePerUser.get(callingUser);
14720 if (map == null) {
14721 map = new HashMap<ComponentName, ServiceRecord>();
14722 mServicesByNamePerUser.put(callingUser, map);
14723 }
14724 return map;
14725 }
14726
14727 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14728 int callingUser) {
14729 HashMap map = mServicesByIntentPerUser.get(callingUser);
14730 if (map == null) {
14731 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14732 mServicesByIntentPerUser.put(callingUser, map);
14733 }
14734 return map;
14735 }
14736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014737}