blob: 0a4c6acb2fa1da24d6f8973eb723066901ddc866 [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
Dianne Hackborn860755f2010-06-03 18:47:52 -070019import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070021import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070022import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import com.android.server.IntentResolver;
24import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.SystemServer;
26import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070027import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080028import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029
Dianne Hackborndd71fc82009-12-16 19:24:32 -080030import dalvik.system.Zygote;
31
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.app.Activity;
33import android.app.ActivityManager;
34import android.app.ActivityManagerNative;
35import android.app.ActivityThread;
36import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070037import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020038import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070040import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.IActivityWatcher;
42import android.app.IApplicationThread;
43import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070044import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070045import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.app.IServiceConnection;
47import android.app.IThumbnailReceiver;
48import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070049import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070050import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070052import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080053import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020054import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080055import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070056import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.content.ComponentName;
58import android.content.ContentResolver;
59import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020060import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.Intent;
62import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070063import android.content.IIntentReceiver;
64import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070065import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.content.pm.ActivityInfo;
67import android.content.pm.ApplicationInfo;
68import android.content.pm.ConfigurationInfo;
69import android.content.pm.IPackageDataObserver;
70import android.content.pm.IPackageManager;
71import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080072import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070074import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.content.pm.ProviderInfo;
76import android.content.pm.ResolveInfo;
77import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070078import android.content.pm.UserInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070079import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040080import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.content.res.Configuration;
82import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070083import android.net.Proxy;
84import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.net.Uri;
86import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080087import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080088import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070089import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080090import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080092import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.os.FileUtils;
94import android.os.Handler;
95import android.os.IBinder;
96import android.os.IPermissionController;
97import android.os.Looper;
98import android.os.Message;
99import android.os.Parcel;
100import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700102import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.os.RemoteException;
104import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700105import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.SystemClock;
107import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700108import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700111import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800112import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800113import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.util.PrintWriterPrinter;
115import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700116import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700117import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.view.Gravity;
119import android.view.LayoutInflater;
120import android.view.View;
121import android.view.WindowManager;
122import android.view.WindowManagerPolicy;
123
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700124import java.io.BufferedInputStream;
125import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700126import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700127import java.io.DataInputStream;
128import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import java.io.File;
130import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700131import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700133import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200134import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800135import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700137import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import java.lang.IllegalStateException;
139import java.lang.ref.WeakReference;
140import java.util.ArrayList;
Dianne Hackborncbb722e2012-02-07 18:33:49 -0800141import java.util.Arrays;
Amith Yamasani742a6712011-05-04 14:49:28 -0700142import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700143import java.util.Collections;
144import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.util.HashMap;
146import java.util.HashSet;
147import java.util.Iterator;
148import java.util.List;
149import java.util.Locale;
150import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700151import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700152import java.util.concurrent.atomic.AtomicBoolean;
153import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700155public final class ActivityManagerService extends ActivityManagerNative
156 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700157 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700159 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400161 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final boolean DEBUG_SWITCH = localLOGV || false;
163 static final boolean DEBUG_TASKS = localLOGV || false;
164 static final boolean DEBUG_PAUSE = localLOGV || false;
165 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
166 static final boolean DEBUG_TRANSITION = localLOGV || false;
167 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800168 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700169 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700171 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 static final boolean DEBUG_VISBILITY = localLOGV || false;
173 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700174 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800175 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700177 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700178 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700179 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700180 static final boolean DEBUG_POWER = localLOGV || false;
181 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700182 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 static final boolean VALIDATE_TOKENS = false;
184 static final boolean SHOW_ACTIVITY_START_TIME = true;
185
186 // Control over CPU and battery monitoring.
187 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
188 static final boolean MONITOR_CPU_USAGE = true;
189 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
190 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
191 static final boolean MONITOR_THREAD_CPU_USAGE = false;
192
Dianne Hackborn1655be42009-05-08 14:29:01 -0700193 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700194 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700195
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800196 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 // Maximum number of recent tasks that we can remember.
199 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700200
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700201 // Amount of time after a call to stopAppSwitches() during which we will
202 // prevent further untrusted switches from happening.
203 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
205 // How long we wait for a launched process to attach to the activity manager
206 // before we decide it's never going to come up for real.
207 static final int PROC_START_TIMEOUT = 10*1000;
208
Jeff Brown3f9dd282011-07-08 20:02:19 -0700209 // How long we wait for a launched process to attach to the activity manager
210 // before we decide it's never going to come up for real, when the process was
211 // started with a wrapper for instrumentation (such as Valgrind) because it
212 // could take much longer than usual.
213 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 // How long to wait after going idle before forcing apps to GC.
216 static final int GC_TIMEOUT = 5*1000;
217
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700218 // The minimum amount of time between successive GC requests for a process.
219 static final int GC_MIN_INTERVAL = 60*1000;
220
Dianne Hackborn287952c2010-09-22 22:34:31 -0700221 // The rate at which we check for apps using excessive power -- 15 mins.
222 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
223
224 // The minimum sample duration we will allow before deciding we have
225 // enough data on wake locks to start killing things.
226 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
227
228 // The minimum sample duration we will allow before deciding we have
229 // enough data on CPU usage to start killing things.
230 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800233 static final int BROADCAST_FG_TIMEOUT = 10*1000;
234 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
236 // How long we wait for a service to finish executing.
237 static final int SERVICE_TIMEOUT = 20*1000;
238
239 // How long a service needs to be running until restarting its process
240 // is no longer considered to be a relaunch of the service.
241 static final int SERVICE_RESTART_DURATION = 5*1000;
242
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700243 // How long a service needs to be running until it will start back at
244 // SERVICE_RESTART_DURATION after being killed.
245 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
246
247 // Multiplying factor to increase restart duration time by, for each time
248 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
249 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
250
251 // The minimum amount of time between restarting services that we allow.
252 // That is, when multiple services are restarting, we won't allow each
253 // to restart less than this amount of time from the last one.
254 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 // Maximum amount of time for there to be no activity on a service before
257 // we consider it non-essential and allow its process to go on the
258 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700259 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260
261 // How long we wait until we timeout on key dispatching.
262 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 // How long we wait until we timeout on key dispatching during instrumentation.
265 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
266
Dan Egnor42471dd2010-01-07 17:25:22 -0800267 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
269 static final String[] EMPTY_STRING_ARRAY = new String[0];
270
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700271 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700272
273 private final boolean mHeadless;
274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700276 * Description of a request to start a new activity, which has been held
277 * due to app switches being disabled.
278 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700279 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700280 ActivityRecord r;
281 ActivityRecord sourceRecord;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700282 Uri[] grantedUriPermissions;
283 int grantedMode;
284 boolean onlyIfNeeded;
285 }
286
287 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
288 = new ArrayList<PendingActivityLaunch>();
289
290 /**
Christopher Tatef46723b2012-01-26 14:19:24 -0800291 * BROADCASTS
292 *
293 * We keep two broadcast queues and associated bookkeeping, one for those at
294 * foreground priority, and one for normal (background-priority) broadcasts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 */
Christopher Tatef46723b2012-01-26 14:19:24 -0800296 public class BroadcastQueue {
297 static final String TAG = "BroadcastQueue";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298
Christopher Tatef46723b2012-01-26 14:19:24 -0800299 static final int MAX_BROADCAST_HISTORY = 25;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300
Christopher Tatef46723b2012-01-26 14:19:24 -0800301 /**
302 * Recognizable moniker for this queue
303 */
304 String mQueueName;
Dianne Hackborn12527f92009-11-11 17:39:50 -0800305
Christopher Tatef46723b2012-01-26 14:19:24 -0800306 /**
307 * Timeout period for this queue's broadcasts
308 */
309 long mTimeoutPeriod;
310
311 /**
312 * Lists of all active broadcasts that are to be executed immediately
313 * (without waiting for another broadcast to finish). Currently this only
314 * contains broadcasts to registered receivers, to avoid spinning up
315 * a bunch of processes to execute IntentReceiver components. Background-
316 * and foreground-priority broadcasts are queued separately.
317 */
318 final ArrayList<BroadcastRecord> mParallelBroadcasts
319 = new ArrayList<BroadcastRecord>();
320 /**
321 * List of all active broadcasts that are to be executed one at a time.
322 * The object at the top of the list is the currently activity broadcasts;
323 * those after it are waiting for the top to finish. As with parallel
324 * broadcasts, separate background- and foreground-priority queues are
325 * maintained.
326 */
327 final ArrayList<BroadcastRecord> mOrderedBroadcasts
328 = new ArrayList<BroadcastRecord>();
329
330 /**
331 * Historical data of past broadcasts, for debugging.
332 */
333 final BroadcastRecord[] mBroadcastHistory
334 = new BroadcastRecord[MAX_BROADCAST_HISTORY];
335
336 /**
337 * Set when we current have a BROADCAST_INTENT_MSG in flight.
338 */
339 boolean mBroadcastsScheduled = false;
340
341 /**
342 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
343 */
344 boolean mPendingBroadcastTimeoutMessage;
345
346 /**
347 * Intent broadcasts that we have tried to start, but are
348 * waiting for the application's process to be created. We only
349 * need one per scheduling class (instead of a list) because we always
350 * process broadcasts one at a time, so no others can be started while
351 * waiting for this one.
352 */
353 BroadcastRecord mPendingBroadcast = null;
354
355 /**
356 * The receiver index that is pending, to restart the broadcast if needed.
357 */
358 int mPendingBroadcastRecvIndex;
359
360 BroadcastQueue(String name, long timeoutPeriod) {
361 mQueueName = name;
362 mTimeoutPeriod = timeoutPeriod;
363 }
364
365 public boolean isPendingBroadcastProcessLocked(int pid) {
366 return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
367 }
368
369 public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
370 mParallelBroadcasts.add(r);
371 }
372
373 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
374 mOrderedBroadcasts.add(r);
375 }
376
377 public final boolean replaceParallelBroadcastLocked(BroadcastRecord r) {
378 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
379 if (r.intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
380 if (DEBUG_BROADCAST) Slog.v(TAG,
381 "***** DROPPING PARALLEL ["
382 + mQueueName + "]: " + r.intent);
383 mParallelBroadcasts.set(i, r);
384 return true;
385 }
386 }
387 return false;
388 }
389
390 public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
391 for (int i=mOrderedBroadcasts.size()-1; i>0; i--) {
392 if (r.intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
393 if (DEBUG_BROADCAST) Slog.v(TAG,
394 "***** DROPPING ORDERED ["
395 + mQueueName + "]: " + r.intent);
396 mOrderedBroadcasts.set(i, r);
397 return true;
398 }
399 }
400 return false;
401 }
402
403 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
404 boolean didSomething = false;
405 final BroadcastRecord br = mPendingBroadcast;
406 if (br != null && br.curApp.pid == app.pid) {
407 try {
408 mPendingBroadcast = null;
409 processCurBroadcastLocked(br, app);
410 didSomething = true;
411 } catch (Exception e) {
412 Slog.w(TAG, "Exception in new application when starting receiver "
413 + br.curComponent.flattenToShortString(), e);
414 logBroadcastReceiverDiscardLocked(br);
415 finishReceiverLocked(br, br.resultCode, br.resultData,
416 br.resultExtras, br.resultAbort, true);
417 scheduleBroadcastsLocked();
418 // We need to reset the state if we fails to start the receiver.
419 br.state = BroadcastRecord.IDLE;
420 throw new RuntimeException(e.getMessage());
421 }
422 }
423 return didSomething;
424 }
425
426 public void skipPendingBroadcastLocked(int pid) {
427 final BroadcastRecord br = mPendingBroadcast;
428 if (br != null && br.curApp.pid == pid) {
429 br.state = BroadcastRecord.IDLE;
430 br.nextReceiver = mPendingBroadcastRecvIndex;
431 mPendingBroadcast = null;
432 scheduleBroadcastsLocked();
433 }
434 }
435
436 public void skipCurrentReceiverLocked(ProcessRecord app) {
437 boolean reschedule = false;
438 BroadcastRecord r = app.curReceiver;
439 if (r != null) {
440 // The current broadcast is waiting for this app's receiver
441 // to be finished. Looks like that's not going to happen, so
442 // let the broadcast continue.
443 logBroadcastReceiverDiscardLocked(r);
444 finishReceiverLocked(r, r.resultCode, r.resultData,
445 r.resultExtras, r.resultAbort, true);
446 reschedule = true;
447 }
448
449 r = mPendingBroadcast;
450 if (r != null && r.curApp == app) {
451 if (DEBUG_BROADCAST) Slog.v(TAG,
452 "[" + mQueueName + "] skip & discard pending app " + r);
453 logBroadcastReceiverDiscardLocked(r);
454 finishReceiverLocked(r, r.resultCode, r.resultData,
455 r.resultExtras, r.resultAbort, true);
456 reschedule = true;
457 }
458 if (reschedule) {
459 scheduleBroadcastsLocked();
460 }
461 }
462
463 public void scheduleBroadcastsLocked() {
464 if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts ["
465 + mQueueName + "]: current="
466 + mBroadcastsScheduled);
467
468 if (mBroadcastsScheduled) {
469 return;
470 }
471 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
472 mBroadcastsScheduled = true;
473 }
474
475 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
476 if (mOrderedBroadcasts.size() > 0) {
477 final BroadcastRecord r = mOrderedBroadcasts.get(0);
478 if (r != null && r.receiver == receiver) {
479 return r;
480 }
481 }
482 return null;
483 }
484
485 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
486 String resultData, Bundle resultExtras, boolean resultAbort,
487 boolean explicit) {
488 int state = r.state;
489 r.state = BroadcastRecord.IDLE;
490 if (state == BroadcastRecord.IDLE) {
491 if (explicit) {
492 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
493 }
494 }
495 r.receiver = null;
496 r.intent.setComponent(null);
497 if (r.curApp != null) {
498 r.curApp.curReceiver = null;
499 }
500 if (r.curFilter != null) {
501 r.curFilter.receiverList.curBroadcast = null;
502 }
503 r.curFilter = null;
504 r.curApp = null;
505 r.curComponent = null;
506 r.curReceiver = null;
507 mPendingBroadcast = null;
508
509 r.resultCode = resultCode;
510 r.resultData = resultData;
511 r.resultExtras = resultExtras;
512 r.resultAbort = resultAbort;
513
514 // We will process the next receiver right now if this is finishing
515 // an app receiver (which is always asynchronous) or after we have
516 // come back from calling a receiver.
517 return state == BroadcastRecord.APP_RECEIVE
518 || state == BroadcastRecord.CALL_DONE_RECEIVE;
519 }
520
521 private final void processNextBroadcast(boolean fromMsg) {
522 synchronized(ActivityManagerService.this) {
523 BroadcastRecord r;
524
525 if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast ["
526 + mQueueName + "]: "
527 + mParallelBroadcasts.size() + " broadcasts, "
528 + mOrderedBroadcasts.size() + " ordered broadcasts");
529
530 updateCpuStats();
531
532 if (fromMsg) {
533 mBroadcastsScheduled = false;
534 }
535
536 // First, deliver any non-serialized broadcasts right away.
537 while (mParallelBroadcasts.size() > 0) {
538 r = mParallelBroadcasts.remove(0);
539 r.dispatchTime = SystemClock.uptimeMillis();
540 r.dispatchClockTime = System.currentTimeMillis();
541 final int N = r.receivers.size();
542 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast ["
543 + mQueueName + "] " + r);
544 for (int i=0; i<N; i++) {
545 Object target = r.receivers.get(i);
546 if (DEBUG_BROADCAST) Slog.v(TAG,
547 "Delivering non-ordered on [" + mQueueName + "] to registered "
548 + target + ": " + r);
549 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
550 }
551 addBroadcastToHistoryLocked(r);
552 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast ["
553 + mQueueName + "] " + r);
554 }
555
556 // Now take care of the next serialized one...
557
558 // If we are waiting for a process to come up to handle the next
559 // broadcast, then do nothing at this point. Just in case, we
560 // check that the process we're waiting for still exists.
561 if (mPendingBroadcast != null) {
562 if (DEBUG_BROADCAST_LIGHT) {
563 Slog.v(TAG, "processNextBroadcast ["
564 + mQueueName + "]: waiting for "
565 + mPendingBroadcast.curApp);
566 }
567
568 boolean isDead;
569 synchronized (mPidsSelfLocked) {
570 isDead = (mPidsSelfLocked.get(mPendingBroadcast.curApp.pid) == null);
571 }
572 if (!isDead) {
573 // It's still alive, so keep waiting
574 return;
575 } else {
576 Slog.w(TAG, "pending app ["
577 + mQueueName + "]" + mPendingBroadcast.curApp
578 + " died before responding to broadcast");
579 mPendingBroadcast.state = BroadcastRecord.IDLE;
580 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
581 mPendingBroadcast = null;
582 }
583 }
584
585 boolean looped = false;
586
587 do {
588 if (mOrderedBroadcasts.size() == 0) {
589 // No more broadcasts pending, so all done!
590 scheduleAppGcsLocked();
591 if (looped) {
592 // If we had finished the last ordered broadcast, then
593 // make sure all processes have correct oom and sched
594 // adjustments.
595 updateOomAdjLocked();
596 }
597 return;
598 }
599 r = mOrderedBroadcasts.get(0);
600 boolean forceReceive = false;
601
602 // Ensure that even if something goes awry with the timeout
603 // detection, we catch "hung" broadcasts here, discard them,
604 // and continue to make progress.
605 //
606 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
607 // receivers don't get executed with timeouts. They're intended for
608 // one time heavy lifting after system upgrades and can take
609 // significant amounts of time.
610 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
611 if (mProcessesReady && r.dispatchTime > 0) {
612 long now = SystemClock.uptimeMillis();
613 if ((numReceivers > 0) &&
614 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
615 Slog.w(TAG, "Hung broadcast ["
616 + mQueueName + "] discarded after timeout failure:"
617 + " now=" + now
618 + " dispatchTime=" + r.dispatchTime
619 + " startTime=" + r.receiverTime
620 + " intent=" + r.intent
621 + " numReceivers=" + numReceivers
622 + " nextReceiver=" + r.nextReceiver
623 + " state=" + r.state);
624 broadcastTimeoutLocked(false); // forcibly finish this broadcast
625 forceReceive = true;
626 r.state = BroadcastRecord.IDLE;
627 }
628 }
629
630 if (r.state != BroadcastRecord.IDLE) {
631 if (DEBUG_BROADCAST) Slog.d(TAG,
632 "processNextBroadcast("
633 + mQueueName + ") called when not idle (state="
634 + r.state + ")");
635 return;
636 }
637
638 if (r.receivers == null || r.nextReceiver >= numReceivers
639 || r.resultAbort || forceReceive) {
640 // No more receivers for this broadcast! Send the final
641 // result if requested...
642 if (r.resultTo != null) {
643 try {
644 if (DEBUG_BROADCAST) {
645 int seq = r.intent.getIntExtra("seq", -1);
646 Slog.i(TAG, "Finishing broadcast ["
647 + mQueueName + "] " + r.intent.getAction()
648 + " seq=" + seq + " app=" + r.callerApp);
649 }
650 performReceiveLocked(r.callerApp, r.resultTo,
651 new Intent(r.intent), r.resultCode,
652 r.resultData, r.resultExtras, false, false);
653 // Set this to null so that the reference
654 // (local and remote) isnt kept in the mBroadcastHistory.
655 r.resultTo = null;
656 } catch (RemoteException e) {
657 Slog.w(TAG, "Failure ["
658 + mQueueName + "] sending broadcast result of "
659 + r.intent, e);
660 }
661 }
662
663 if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
664 cancelBroadcastTimeoutLocked();
665
666 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
667 + r);
668
669 // ... and on to the next...
670 addBroadcastToHistoryLocked(r);
671 mOrderedBroadcasts.remove(0);
672 r = null;
673 looped = true;
674 continue;
675 }
676 } while (r == null);
677
678 // Get the next receiver...
679 int recIdx = r.nextReceiver++;
680
681 // Keep track of when this receiver started, and make sure there
682 // is a timeout message pending to kill it if need be.
683 r.receiverTime = SystemClock.uptimeMillis();
684 if (recIdx == 0) {
685 r.dispatchTime = r.receiverTime;
686 r.dispatchClockTime = System.currentTimeMillis();
687 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast ["
688 + mQueueName + "] " + r);
689 }
690 if (! mPendingBroadcastTimeoutMessage) {
691 long timeoutTime = r.receiverTime + mTimeoutPeriod;
692 if (DEBUG_BROADCAST) Slog.v(TAG,
693 "Submitting BROADCAST_TIMEOUT_MSG ["
694 + mQueueName + "] for " + r + " at " + timeoutTime);
695 setBroadcastTimeoutLocked(timeoutTime);
696 }
697
698 Object nextReceiver = r.receivers.get(recIdx);
699 if (nextReceiver instanceof BroadcastFilter) {
700 // Simple case: this is a registered receiver who gets
701 // a direct call.
702 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
703 if (DEBUG_BROADCAST) Slog.v(TAG,
704 "Delivering ordered ["
705 + mQueueName + "] to registered "
706 + filter + ": " + r);
707 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
708 if (r.receiver == null || !r.ordered) {
709 // The receiver has already finished, so schedule to
710 // process the next one.
711 if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing ["
712 + mQueueName + "]: ordered="
713 + r.ordered + " receiver=" + r.receiver);
714 r.state = BroadcastRecord.IDLE;
715 scheduleBroadcastsLocked();
716 }
717 return;
718 }
719
720 // Hard case: need to instantiate the receiver, possibly
721 // starting its application process to host it.
722
723 ResolveInfo info =
724 (ResolveInfo)nextReceiver;
725
726 boolean skip = false;
727 int perm = checkComponentPermission(info.activityInfo.permission,
728 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
729 info.activityInfo.exported);
730 if (perm != PackageManager.PERMISSION_GRANTED) {
731 if (!info.activityInfo.exported) {
732 Slog.w(TAG, "Permission Denial: broadcasting "
733 + r.intent.toString()
734 + " from " + r.callerPackage + " (pid=" + r.callingPid
735 + ", uid=" + r.callingUid + ")"
736 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
737 + " due to receiver " + info.activityInfo.packageName
738 + "/" + info.activityInfo.name);
739 } else {
740 Slog.w(TAG, "Permission Denial: broadcasting "
741 + r.intent.toString()
742 + " from " + r.callerPackage + " (pid=" + r.callingPid
743 + ", uid=" + r.callingUid + ")"
744 + " requires " + info.activityInfo.permission
745 + " due to receiver " + info.activityInfo.packageName
746 + "/" + info.activityInfo.name);
747 }
748 skip = true;
749 }
750 if (info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
751 r.requiredPermission != null) {
752 try {
753 perm = AppGlobals.getPackageManager().
754 checkPermission(r.requiredPermission,
755 info.activityInfo.applicationInfo.packageName);
756 } catch (RemoteException e) {
757 perm = PackageManager.PERMISSION_DENIED;
758 }
759 if (perm != PackageManager.PERMISSION_GRANTED) {
760 Slog.w(TAG, "Permission Denial: receiving "
761 + r.intent + " to "
762 + info.activityInfo.applicationInfo.packageName
763 + " requires " + r.requiredPermission
764 + " due to sender " + r.callerPackage
765 + " (uid " + r.callingUid + ")");
766 skip = true;
767 }
768 }
769 if (r.curApp != null && r.curApp.crashing) {
770 // If the target process is crashing, just skip it.
771 if (DEBUG_BROADCAST) Slog.v(TAG,
772 "Skipping deliver ordered ["
773 + mQueueName + "] " + r + " to " + r.curApp
774 + ": process crashing");
775 skip = true;
776 }
777
778 if (skip) {
779 if (DEBUG_BROADCAST) Slog.v(TAG,
780 "Skipping delivery of ordered ["
781 + mQueueName + "] " + r + " for whatever reason");
782 r.receiver = null;
783 r.curFilter = null;
784 r.state = BroadcastRecord.IDLE;
785 scheduleBroadcastsLocked();
786 return;
787 }
788
789 r.state = BroadcastRecord.APP_RECEIVE;
790 String targetProcess = info.activityInfo.processName;
791 r.curComponent = new ComponentName(
792 info.activityInfo.applicationInfo.packageName,
793 info.activityInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -0700794 if (r.callingUid != Process.SYSTEM_UID) {
795 info.activityInfo = getActivityInfoForUser(info.activityInfo, UserId
796 .getUserId(r.callingUid));
797 }
Christopher Tatef46723b2012-01-26 14:19:24 -0800798 r.curReceiver = info.activityInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -0700799 if (DEBUG_MU && r.callingUid > UserId.PER_USER_RANGE) {
800 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
801 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
802 + info.activityInfo.applicationInfo.uid);
803 }
Christopher Tatef46723b2012-01-26 14:19:24 -0800804
805 // Broadcast is being executed, its package can't be stopped.
806 try {
807 AppGlobals.getPackageManager().setPackageStoppedState(
808 r.curComponent.getPackageName(), false);
809 } catch (RemoteException e) {
810 } catch (IllegalArgumentException e) {
811 Slog.w(TAG, "Failed trying to unstop package "
812 + r.curComponent.getPackageName() + ": " + e);
813 }
814
815 // Is this receiver's application already running?
816 ProcessRecord app = getProcessRecordLocked(targetProcess,
817 info.activityInfo.applicationInfo.uid);
818 if (app != null && app.thread != null) {
819 try {
820 app.addPackage(info.activityInfo.packageName);
821 processCurBroadcastLocked(r, app);
822 return;
823 } catch (RemoteException e) {
824 Slog.w(TAG, "Exception when sending broadcast to "
825 + r.curComponent, e);
826 }
827
828 // If a dead object exception was thrown -- fall through to
829 // restart the application.
830 }
831
832 // Not running -- get it started, to be executed when the app comes up.
833 if (DEBUG_BROADCAST) Slog.v(TAG,
834 "Need to start app ["
835 + mQueueName + "] " + targetProcess + " for broadcast " + r);
836 if ((r.curApp=startProcessLocked(targetProcess,
837 info.activityInfo.applicationInfo, true,
838 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
839 "broadcast", r.curComponent,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800840 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false))
Christopher Tatef46723b2012-01-26 14:19:24 -0800841 == null) {
842 // Ah, this recipient is unavailable. Finish it if necessary,
843 // and mark the broadcast record as ready for the next.
844 Slog.w(TAG, "Unable to launch app "
845 + info.activityInfo.applicationInfo.packageName + "/"
846 + info.activityInfo.applicationInfo.uid + " for broadcast "
847 + r.intent + ": process is bad");
848 logBroadcastReceiverDiscardLocked(r);
849 finishReceiverLocked(r, r.resultCode, r.resultData,
850 r.resultExtras, r.resultAbort, true);
851 scheduleBroadcastsLocked();
852 r.state = BroadcastRecord.IDLE;
853 return;
854 }
855
856 mPendingBroadcast = r;
857 mPendingBroadcastRecvIndex = recIdx;
858 }
859 }
860
861 final void setBroadcastTimeoutLocked(long timeoutTime) {
862 if (! mPendingBroadcastTimeoutMessage) {
863 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
864 mHandler.sendMessageAtTime(msg, timeoutTime);
865 mPendingBroadcastTimeoutMessage = true;
866 }
867 }
868
869 final void cancelBroadcastTimeoutLocked() {
870 if (mPendingBroadcastTimeoutMessage) {
871 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
872 mPendingBroadcastTimeoutMessage = false;
873 }
874 }
875
876 final void broadcastTimeoutLocked(boolean fromMsg) {
877 if (fromMsg) {
878 mPendingBroadcastTimeoutMessage = false;
879 }
880
881 if (mOrderedBroadcasts.size() == 0) {
882 return;
883 }
884
885 long now = SystemClock.uptimeMillis();
886 BroadcastRecord r = mOrderedBroadcasts.get(0);
887 if (fromMsg) {
888 if (mDidDexOpt) {
889 // Delay timeouts until dexopt finishes.
890 mDidDexOpt = false;
891 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
892 setBroadcastTimeoutLocked(timeoutTime);
893 return;
894 }
895 if (! mProcessesReady) {
896 // Only process broadcast timeouts if the system is ready. That way
897 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
898 // to do heavy lifting for system up.
899 return;
900 }
901
902 long timeoutTime = r.receiverTime + mTimeoutPeriod;
903 if (timeoutTime > now) {
904 // We can observe premature timeouts because we do not cancel and reset the
905 // broadcast timeout message after each receiver finishes. Instead, we set up
906 // an initial timeout then kick it down the road a little further as needed
907 // when it expires.
908 if (DEBUG_BROADCAST) Slog.v(TAG,
909 "Premature timeout ["
910 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
911 + timeoutTime);
912 setBroadcastTimeoutLocked(timeoutTime);
913 return;
914 }
915 }
916
917 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
918 + ", started " + (now - r.receiverTime) + "ms ago");
919 r.receiverTime = now;
920 r.anrCount++;
921
922 // Current receiver has passed its expiration date.
923 if (r.nextReceiver <= 0) {
924 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
925 return;
926 }
927
928 ProcessRecord app = null;
929 String anrMessage = null;
930
931 Object curReceiver = r.receivers.get(r.nextReceiver-1);
932 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
933 logBroadcastReceiverDiscardLocked(r);
934 if (curReceiver instanceof BroadcastFilter) {
935 BroadcastFilter bf = (BroadcastFilter)curReceiver;
936 if (bf.receiverList.pid != 0
937 && bf.receiverList.pid != MY_PID) {
938 synchronized (ActivityManagerService.this.mPidsSelfLocked) {
939 app = ActivityManagerService.this.mPidsSelfLocked.get(
940 bf.receiverList.pid);
941 }
942 }
943 } else {
944 app = r.curApp;
945 }
946
947 if (app != null) {
948 anrMessage = "Broadcast of " + r.intent.toString();
949 }
950
951 if (mPendingBroadcast == r) {
952 mPendingBroadcast = null;
953 }
954
955 // Move on to the next receiver.
956 finishReceiverLocked(r, r.resultCode, r.resultData,
957 r.resultExtras, r.resultAbort, true);
958 scheduleBroadcastsLocked();
959
960 if (anrMessage != null) {
961 // Post the ANR to the handler since we do not want to process ANRs while
962 // potentially holding our lock.
963 mHandler.post(new AppNotResponding(app, anrMessage));
964 }
965 }
966
967 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
968 if (r.callingUid < 0) {
969 // This was from a registerReceiver() call; ignore it.
970 return;
971 }
972 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
973 MAX_BROADCAST_HISTORY-1);
974 r.finishTime = SystemClock.uptimeMillis();
975 mBroadcastHistory[0] = r;
976 }
977
978 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
979 if (r.nextReceiver > 0) {
980 Object curReceiver = r.receivers.get(r.nextReceiver-1);
981 if (curReceiver instanceof BroadcastFilter) {
982 BroadcastFilter bf = (BroadcastFilter) curReceiver;
983 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
984 System.identityHashCode(r),
985 r.intent.getAction(),
986 r.nextReceiver - 1,
987 System.identityHashCode(bf));
988 } else {
989 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
990 System.identityHashCode(r),
991 r.intent.getAction(),
992 r.nextReceiver - 1,
993 ((ResolveInfo)curReceiver).toString());
994 }
995 } else {
996 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
997 + r);
998 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
999 System.identityHashCode(r),
1000 r.intent.getAction(),
1001 r.nextReceiver,
1002 "NONE");
1003 }
1004 }
1005
1006 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1007 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
1008 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1009 || mPendingBroadcast != null) {
1010 boolean printed = false;
1011 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
1012 BroadcastRecord br = mParallelBroadcasts.get(i);
1013 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1014 continue;
1015 }
1016 if (!printed) {
1017 if (needSep) {
1018 pw.println();
1019 needSep = false;
1020 }
1021 printed = true;
1022 pw.println(" Active broadcasts [" + mQueueName + "]:");
1023 }
1024 pw.println(" Broadcast #" + i + ":");
1025 br.dump(pw, " ");
1026 }
1027 printed = false;
1028 needSep = true;
1029 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
1030 BroadcastRecord br = mOrderedBroadcasts.get(i);
1031 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1032 continue;
1033 }
1034 if (!printed) {
1035 if (needSep) {
1036 pw.println();
1037 }
1038 needSep = true;
1039 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1040 }
1041 pw.println(" Ordered Broadcast #" + i + ":");
1042 mOrderedBroadcasts.get(i).dump(pw, " ");
1043 }
1044 if (dumpPackage == null || (mPendingBroadcast != null
1045 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1046 if (needSep) {
1047 pw.println();
1048 }
1049 pw.println(" Pending broadcast [" + mQueueName + "]:");
1050 if (mPendingBroadcast != null) {
1051 mPendingBroadcast.dump(pw, " ");
1052 } else {
1053 pw.println(" (null)");
1054 }
1055 needSep = true;
1056 }
1057 }
1058
1059 boolean printed = false;
1060 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
1061 BroadcastRecord r = mBroadcastHistory[i];
1062 if (r == null) {
1063 break;
1064 }
1065 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1066 continue;
1067 }
1068 if (!printed) {
1069 if (needSep) {
1070 pw.println();
1071 }
1072 needSep = true;
1073 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1074 printed = true;
1075 }
1076 if (dumpAll) {
1077 pw.print(" Historical Broadcast #"); pw.print(i); pw.println(":");
1078 r.dump(pw, " ");
1079 } else {
1080 if (i >= 50) {
1081 pw.println(" ...");
1082 break;
1083 }
1084 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1085 }
1086 }
1087
1088 return needSep;
1089 }
1090 }
1091
1092 final BroadcastQueue mFgBroadcastQueue = new BroadcastQueue("foreground", BROADCAST_FG_TIMEOUT);
1093 final BroadcastQueue mBgBroadcastQueue = new BroadcastQueue("background", BROADCAST_BG_TIMEOUT);
1094 // Convenient for easy iteration over the queues. Foreground is first
1095 // so that dispatch of foreground broadcasts gets precedence.
1096 final BroadcastQueue[] mBroadcastQueues = { mFgBroadcastQueue, mBgBroadcastQueue };
1097
1098 BroadcastQueue broadcastQueueForIntent(Intent intent) {
1099 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
1100 if (DEBUG_BACKGROUND_BROADCAST) {
1101 Slog.i(TAG, "Broadcast intent " + intent + " on "
1102 + (isFg ? "foreground" : "background")
1103 + " queue");
1104 }
1105 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
1106 }
1107
1108 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
1109 for (BroadcastQueue queue : mBroadcastQueues) {
1110 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
1111 if (r != null) {
1112 return r;
1113 }
1114 }
1115 return null;
1116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117
1118 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 * Activity we have told the window manager to have key focus.
1120 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001121 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07001122 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 * List of intents that were used to start the most recent tasks.
1124 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001125 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126
1127 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -07001128 * Process management.
1129 */
1130 final ProcessList mProcessList = new ProcessList();
1131
1132 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 * All of the applications we currently have running organized by name.
1134 * The keys are strings of the application package name (as
1135 * returned by the package manager), and the keys are ApplicationRecord
1136 * objects.
1137 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001138 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139
1140 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001141 * The currently running isolated processes.
1142 */
1143 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
1144
1145 /**
1146 * Counter for assigning isolated process uids, to avoid frequently reusing the
1147 * same ones.
1148 */
1149 int mNextIsolatedProcessUid = 0;
1150
1151 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -07001152 * The currently running heavy-weight process, if any.
1153 */
1154 ProcessRecord mHeavyWeightProcess = null;
1155
1156 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 * The last time that various processes have crashed.
1158 */
1159 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
1160
1161 /**
1162 * Set of applications that we consider to be bad, and will reject
1163 * incoming broadcasts from (which the user has no control over).
1164 * Processes are added to this set when they have crashed twice within
1165 * a minimum amount of time; they are removed from it when they are
1166 * later restarted (hopefully due to some user action). The value is the
1167 * time it was added to the list.
1168 */
1169 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
1170
1171 /**
1172 * All of the processes we currently have running organized by pid.
1173 * The keys are the pid running the application.
1174 *
1175 * <p>NOTE: This object is protected by its own lock, NOT the global
1176 * activity manager lock!
1177 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001178 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179
1180 /**
1181 * All of the processes that have been forced to be foreground. The key
1182 * is the pid of the caller who requested it (we hold a death
1183 * link on it).
1184 */
1185 abstract class ForegroundToken implements IBinder.DeathRecipient {
1186 int pid;
1187 IBinder token;
1188 }
1189 final SparseArray<ForegroundToken> mForegroundProcesses
1190 = new SparseArray<ForegroundToken>();
1191
1192 /**
1193 * List of records for processes that someone had tried to start before the
1194 * system was ready. We don't start them at that point, but ensure they
1195 * are started by the time booting is complete.
1196 */
1197 final ArrayList<ProcessRecord> mProcessesOnHold
1198 = new ArrayList<ProcessRecord>();
1199
1200 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 * List of persistent applications that are in the process
1202 * of being started.
1203 */
1204 final ArrayList<ProcessRecord> mPersistentStartingProcesses
1205 = new ArrayList<ProcessRecord>();
1206
1207 /**
1208 * Processes that are being forcibly torn down.
1209 */
1210 final ArrayList<ProcessRecord> mRemovedProcesses
1211 = new ArrayList<ProcessRecord>();
1212
1213 /**
1214 * List of running applications, sorted by recent usage.
1215 * The first entry in the list is the least recently used.
1216 * It contains ApplicationRecord objects. This list does NOT include
1217 * any persistent application records (since we never want to exit them).
1218 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001219 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 = new ArrayList<ProcessRecord>();
1221
1222 /**
1223 * List of processes that should gc as soon as things are idle.
1224 */
1225 final ArrayList<ProcessRecord> mProcessesToGc
1226 = new ArrayList<ProcessRecord>();
1227
1228 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -08001229 * This is the process holding what we currently consider to be
1230 * the "home" activity.
1231 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001232 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -08001233
1234 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -07001235 * This is the process holding the activity the user last visited that
1236 * is in a different process from the one they are currently in.
1237 */
1238 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -08001239
1240 /**
1241 * The time at which the previous process was last visible.
1242 */
1243 long mPreviousProcessVisibleTime;
1244
Dianne Hackbornf35fe232011-11-01 19:25:20 -07001245 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001246 * Packages that the user has asked to have run in screen size
1247 * compatibility mode instead of filling the screen.
1248 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001249 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001250
1251 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 * Set of PendingResultRecord objects that are currently active.
1253 */
1254 final HashSet mPendingResultRecords = new HashSet();
1255
1256 /**
1257 * Set of IntentSenderRecord objects that are currently active.
1258 */
1259 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
1260 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
1261
1262 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08001263 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07001264 * already logged DropBox entries for. Guarded by itself. If
1265 * something (rogue user app) forces this over
1266 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
1267 */
1268 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
1269 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
1270
1271 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07001272 * Strict Mode background batched logging state.
1273 *
1274 * The string buffer is guarded by itself, and its lock is also
1275 * used to determine if another batched write is already
1276 * in-flight.
1277 */
1278 private final StringBuilder mStrictModeBuffer = new StringBuilder();
1279
1280 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 * Keeps track of all IIntentReceivers that have been registered for
1282 * broadcasts. Hash keys are the receiver IBinder, hash value is
1283 * a ReceiverList.
1284 */
1285 final HashMap mRegisteredReceivers = new HashMap();
1286
1287 /**
1288 * Resolver for broadcast intents to registered receivers.
1289 * Holds BroadcastFilter (subclass of IntentFilter).
1290 */
1291 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
1292 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
1293 @Override
1294 protected boolean allowFilterResult(
1295 BroadcastFilter filter, List<BroadcastFilter> dest) {
1296 IBinder target = filter.receiverList.receiver.asBinder();
1297 for (int i=dest.size()-1; i>=0; i--) {
1298 if (dest.get(i).receiverList.receiver.asBinder() == target) {
1299 return false;
1300 }
1301 }
1302 return true;
1303 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001304
1305 @Override
1306 protected String packageForFilter(BroadcastFilter filter) {
1307 return filter.packageName;
1308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 };
1310
1311 /**
1312 * State of all active sticky broadcasts. Keys are the action of the
1313 * sticky Intent, values are an ArrayList of all broadcasted intents with
1314 * that action (which should usually be one).
1315 */
1316 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
1317 new HashMap<String, ArrayList<Intent>>();
1318
Amith Yamasani742a6712011-05-04 14:49:28 -07001319 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320
1321 /**
1322 * All currently bound service connections. Keys are the IBinder of
1323 * the client's IServiceConnection.
1324 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07001325 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
1326 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327
1328 /**
1329 * List of services that we have been asked to start,
1330 * but haven't yet been able to. It is used to hold start requests
1331 * while waiting for their corresponding application thread to get
1332 * going.
1333 */
1334 final ArrayList<ServiceRecord> mPendingServices
1335 = new ArrayList<ServiceRecord>();
1336
1337 /**
1338 * List of services that are scheduled to restart following a crash.
1339 */
1340 final ArrayList<ServiceRecord> mRestartingServices
1341 = new ArrayList<ServiceRecord>();
1342
1343 /**
1344 * List of services that are in the process of being stopped.
1345 */
1346 final ArrayList<ServiceRecord> mStoppingServices
1347 = new ArrayList<ServiceRecord>();
1348
1349 /**
Christopher Tate181fafa2009-05-14 11:12:14 -07001350 * Backup/restore process management
1351 */
1352 String mBackupAppName = null;
1353 BackupRecord mBackupTarget = null;
1354
1355 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 * List of PendingThumbnailsRecord objects of clients who are still
1357 * waiting to receive all of the thumbnails for a task.
1358 */
1359 final ArrayList mPendingThumbnails = new ArrayList();
1360
1361 /**
1362 * List of HistoryRecord objects that have been finished and must
1363 * still report back to a pending thumbnail receiver.
1364 */
1365 final ArrayList mCancelledThumbnails = new ArrayList();
1366
1367 /**
1368 * All of the currently running global content providers. Keys are a
1369 * string containing the provider name and values are a
1370 * ContentProviderRecord object containing the data about it. Note
1371 * that a single provider may be published under multiple names, so
1372 * there may be multiple entries here for a single one in mProvidersByClass.
1373 */
Dianne Hackborn860755f2010-06-03 18:47:52 -07001374 final HashMap<String, ContentProviderRecord> mProvidersByName
1375 = new HashMap<String, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376
1377 /**
1378 * All of the currently running global content providers. Keys are a
1379 * string containing the provider's implementation class and values are a
1380 * ContentProviderRecord object containing the data about it.
1381 */
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07001382 final HashMap<ComponentName, ContentProviderRecord> mProvidersByClass
1383 = new HashMap<ComponentName, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384
Amith Yamasani742a6712011-05-04 14:49:28 -07001385 final ProviderMap mProviderMap = new ProviderMap();
1386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 /**
1388 * List of content providers who have clients waiting for them. The
1389 * application is currently being launched and the provider will be
1390 * removed from this list once it is published.
1391 */
Dianne Hackborn860755f2010-06-03 18:47:52 -07001392 final ArrayList<ContentProviderRecord> mLaunchingProviders
1393 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394
1395 /**
1396 * Global set of specific Uri permissions that have been granted.
1397 */
1398 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
1399 = new SparseArray<HashMap<Uri, UriPermission>>();
1400
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001401 CoreSettingsObserver mCoreSettingsObserver;
1402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 /**
1404 * Thread-local storage used to carry caller permissions over through
1405 * indirect content-provider access.
1406 * @see #ActivityManagerService.openContentUri()
1407 */
1408 private class Identity {
1409 public int pid;
1410 public int uid;
1411
1412 Identity(int _pid, int _uid) {
1413 pid = _pid;
1414 uid = _uid;
1415 }
1416 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
1419
1420 /**
1421 * All information we have collected about the runtime performance of
1422 * any user id that can impact battery performance.
1423 */
1424 final BatteryStatsService mBatteryStatsService;
1425
1426 /**
1427 * information about component usage
1428 */
1429 final UsageStatsService mUsageStatsService;
1430
1431 /**
1432 * Current configuration information. HistoryRecord objects are given
1433 * a reference to this object to indicate which configuration they are
1434 * currently running in, so this object must be kept immutable.
1435 */
1436 Configuration mConfiguration = new Configuration();
1437
1438 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001439 * Current sequencing integer of the configuration, for skipping old
1440 * configurations.
1441 */
1442 int mConfigurationSeq = 0;
1443
1444 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -07001445 * Hardware-reported OpenGLES version.
1446 */
1447 final int GL_ES_VERSION;
1448
1449 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 * List of initialization arguments to pass to all processes when binding applications to them.
1451 * For example, references to the commonly used services.
1452 */
1453 HashMap<String, IBinder> mAppBindArgs;
1454
1455 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07001456 * Temporary to avoid allocations. Protected by main lock.
1457 */
1458 final StringBuilder mStringBuilder = new StringBuilder(256);
1459
1460 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 * Used to control how we initialize the service.
1462 */
1463 boolean mStartRunning = false;
1464 ComponentName mTopComponent;
1465 String mTopAction;
1466 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001467 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 boolean mSystemReady = false;
1469 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001470 boolean mWaitingUpdate = false;
1471 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001472 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001473 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474
1475 Context mContext;
1476
1477 int mFactoryTest;
1478
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001479 boolean mCheckedForSetup;
1480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001482 * The time at which we will allow normal application switches again,
1483 * after a call to {@link #stopAppSwitches()}.
1484 */
1485 long mAppSwitchesAllowedTime;
1486
1487 /**
1488 * This is set to true after the first switch after mAppSwitchesAllowedTime
1489 * is set; any switches after that will clear the time.
1490 */
1491 boolean mDidAppSwitch;
1492
1493 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -07001494 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001495 */
Dianne Hackborn287952c2010-09-22 22:34:31 -07001496 long mLastPowerCheckRealtime;
1497
1498 /**
1499 * Last time (in uptime) at which we checked for power usage.
1500 */
1501 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001502
1503 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 * Set while we are wanting to sleep, to prevent any
1505 * activities from being started/resumed.
1506 */
1507 boolean mSleeping = false;
1508
1509 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -07001510 * Set if we are shutting down the system, similar to sleeping.
1511 */
1512 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513
1514 /**
1515 * Task identifier that activities are currently being started
1516 * in. Incremented each time a new task is created.
1517 * todo: Replace this with a TokenSpace class that generates non-repeating
1518 * integers that won't wrap.
1519 */
1520 int mCurTask = 1;
1521
1522 /**
1523 * Current sequence id for oom_adj computation traversal.
1524 */
1525 int mAdjSeq = 0;
1526
1527 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -07001528 * Current sequence id for process LRU updating.
1529 */
1530 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531
1532 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -07001533 * Keep track of the number of service processes we last found, to
1534 * determine on the next iteration which should be B services.
1535 */
1536 int mNumServiceProcs = 0;
1537 int mNewNumServiceProcs = 0;
1538
1539 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 * System monitoring: number of processes that died since the last
1541 * N procs were started.
1542 */
1543 int[] mProcDeaths = new int[20];
1544
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001545 /**
1546 * This is set if we had to do a delayed dexopt of an app before launching
1547 * it, to increasing the ANR timeouts in that case.
1548 */
1549 boolean mDidDexOpt;
1550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 String mDebugApp = null;
1552 boolean mWaitForDebugger = false;
1553 boolean mDebugTransient = false;
1554 String mOrigDebugApp = null;
1555 boolean mOrigWaitForDebugger = false;
1556 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001557 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001558 String mProfileApp = null;
1559 ProcessRecord mProfileProc = null;
1560 String mProfileFile;
1561 ParcelFileDescriptor mProfileFd;
1562 int mProfileType = 0;
1563 boolean mAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001565 final RemoteCallbackList<IActivityWatcher> mWatchers
1566 = new RemoteCallbackList<IActivityWatcher>();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001567
1568 final RemoteCallbackList<IProcessObserver> mProcessObservers
1569 = new RemoteCallbackList<IProcessObserver>();
1570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 /**
1572 * Callback of last caller to {@link #requestPss}.
1573 */
1574 Runnable mRequestPssCallback;
1575
1576 /**
1577 * Remaining processes for which we are waiting results from the last
1578 * call to {@link #requestPss}.
1579 */
1580 final ArrayList<ProcessRecord> mRequestPssList
1581 = new ArrayList<ProcessRecord>();
1582
1583 /**
1584 * Runtime statistics collection thread. This object's lock is used to
1585 * protect all related state.
1586 */
1587 final Thread mProcessStatsThread;
1588
1589 /**
1590 * Used to collect process stats when showing not responding dialog.
1591 * Protected by mProcessStatsThread.
1592 */
1593 final ProcessStats mProcessStats = new ProcessStats(
1594 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001595 final AtomicLong mLastCpuTime = new AtomicLong(0);
1596 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
1597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 long mLastWriteTime = 0;
1599
1600 /**
1601 * Set to true after the system has finished booting.
1602 */
1603 boolean mBooted = false;
1604
Dianne Hackborn7d608422011-08-07 16:24:18 -07001605 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001606 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607
1608 WindowManagerService mWindowManager;
1609
1610 static ActivityManagerService mSelf;
1611 static ActivityThread mSystemThread;
1612
1613 private final class AppDeathRecipient implements IBinder.DeathRecipient {
1614 final ProcessRecord mApp;
1615 final int mPid;
1616 final IApplicationThread mAppThread;
1617
1618 AppDeathRecipient(ProcessRecord app, int pid,
1619 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001620 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 TAG, "New death recipient " + this
1622 + " for thread " + thread.asBinder());
1623 mApp = app;
1624 mPid = pid;
1625 mAppThread = thread;
1626 }
1627
1628 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001629 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 TAG, "Death received in " + this
1631 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 synchronized(ActivityManagerService.this) {
1633 appDiedLocked(mApp, mPid, mAppThread);
1634 }
1635 }
1636 }
1637
1638 static final int SHOW_ERROR_MSG = 1;
1639 static final int SHOW_NOT_RESPONDING_MSG = 2;
1640 static final int SHOW_FACTORY_ERROR_MSG = 3;
1641 static final int UPDATE_CONFIGURATION_MSG = 4;
1642 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1643 static final int WAIT_FOR_DEBUGGER_MSG = 6;
1644 static final int BROADCAST_INTENT_MSG = 7;
1645 static final int BROADCAST_TIMEOUT_MSG = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 static final int SERVICE_TIMEOUT_MSG = 12;
1647 static final int UPDATE_TIME_ZONE = 13;
1648 static final int SHOW_UID_ERROR_MSG = 14;
1649 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001651 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001652 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001653 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001654 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
1655 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001656 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001657 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001658 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001659 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001660 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001661 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
1662 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001663 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664
1665 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001666 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001667 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668
1669 final Handler mHandler = new Handler() {
1670 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001671 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 //}
1673
1674 public void handleMessage(Message msg) {
1675 switch (msg.what) {
1676 case SHOW_ERROR_MSG: {
1677 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 synchronized (ActivityManagerService.this) {
1679 ProcessRecord proc = (ProcessRecord)data.get("app");
1680 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001681 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 return;
1683 }
1684 AppErrorResult res = (AppErrorResult) data.get("result");
Dianne Hackborn55280a92009-05-07 15:53:46 -07001685 if (!mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -08001686 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 d.show();
1688 proc.crashDialog = d;
1689 } else {
1690 // The device is asleep, so just pretend that the user
1691 // saw a crash dialog and hit "force quit".
1692 res.set(0);
1693 }
1694 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001695
1696 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 } break;
1698 case SHOW_NOT_RESPONDING_MSG: {
1699 synchronized (ActivityManagerService.this) {
1700 HashMap data = (HashMap) msg.obj;
1701 ProcessRecord proc = (ProcessRecord)data.get("app");
1702 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001703 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 return;
1705 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001706
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001707 Intent intent = new Intent("android.intent.action.ANR");
1708 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -08001709 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1710 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001711 }
1712 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -08001713 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07001714 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -08001715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001717 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 d.show();
1719 proc.anrDialog = d;
1720 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001721
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001722 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001724 case SHOW_STRICT_MODE_VIOLATION_MSG: {
1725 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1726 synchronized (ActivityManagerService.this) {
1727 ProcessRecord proc = (ProcessRecord) data.get("app");
1728 if (proc == null) {
1729 Slog.e(TAG, "App not found when showing strict mode dialog.");
1730 break;
1731 }
1732 if (proc.crashDialog != null) {
1733 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1734 return;
1735 }
1736 AppErrorResult res = (AppErrorResult) data.get("result");
1737 if (!mSleeping && !mShuttingDown) {
1738 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
1739 d.show();
1740 proc.crashDialog = d;
1741 } else {
1742 // The device is asleep, so just pretend that the user
1743 // saw a crash dialog and hit "force quit".
1744 res.set(0);
1745 }
1746 }
1747 ensureBootCompleted();
1748 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 case SHOW_FACTORY_ERROR_MSG: {
1750 Dialog d = new FactoryErrorDialog(
1751 mContext, msg.getData().getCharSequence("msg"));
1752 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001753 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 } break;
1755 case UPDATE_CONFIGURATION_MSG: {
1756 final ContentResolver resolver = mContext.getContentResolver();
1757 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1758 } break;
1759 case GC_BACKGROUND_PROCESSES_MSG: {
1760 synchronized (ActivityManagerService.this) {
1761 performAppGcsIfAppropriateLocked();
1762 }
1763 } break;
1764 case WAIT_FOR_DEBUGGER_MSG: {
1765 synchronized (ActivityManagerService.this) {
1766 ProcessRecord app = (ProcessRecord)msg.obj;
1767 if (msg.arg1 != 0) {
1768 if (!app.waitedForDebugger) {
1769 Dialog d = new AppWaitingForDebuggerDialog(
1770 ActivityManagerService.this,
1771 mContext, app);
1772 app.waitDialog = d;
1773 app.waitedForDebugger = true;
1774 d.show();
1775 }
1776 } else {
1777 if (app.waitDialog != null) {
1778 app.waitDialog.dismiss();
1779 app.waitDialog = null;
1780 }
1781 }
1782 }
1783 } break;
1784 case BROADCAST_INTENT_MSG: {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001785 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 TAG, "Received BROADCAST_INTENT_MSG");
Christopher Tatef46723b2012-01-26 14:19:24 -08001787 BroadcastQueue queue = (BroadcastQueue) msg.obj;
1788 queue.processNextBroadcast(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 } break;
1790 case BROADCAST_TIMEOUT_MSG: {
Christopher Tatef46723b2012-01-26 14:19:24 -08001791 final BroadcastQueue queue = (BroadcastQueue) msg.obj;
Jeff Brown4d94a762010-09-23 11:33:28 -07001792 synchronized (ActivityManagerService.this) {
Christopher Tatef46723b2012-01-26 14:19:24 -08001793 queue.broadcastTimeoutLocked(true);
Jeff Hamiltonacf84742010-05-25 22:10:18 -05001794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001797 if (mDidDexOpt) {
1798 mDidDexOpt = false;
1799 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1800 nmsg.obj = msg.obj;
1801 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
1802 return;
1803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 serviceTimeout((ProcessRecord)msg.obj);
1805 } break;
1806 case UPDATE_TIME_ZONE: {
1807 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001808 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1809 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 if (r.thread != null) {
1811 try {
1812 r.thread.updateTimeZone();
1813 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001814 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 }
1816 }
1817 }
1818 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001819 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001820 case CLEAR_DNS_CACHE: {
1821 synchronized (ActivityManagerService.this) {
1822 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1823 ProcessRecord r = mLruProcesses.get(i);
1824 if (r.thread != null) {
1825 try {
1826 r.thread.clearDnsCache();
1827 } catch (RemoteException ex) {
1828 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1829 }
1830 }
1831 }
1832 }
1833 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001834 case UPDATE_HTTP_PROXY: {
1835 ProxyProperties proxy = (ProxyProperties)msg.obj;
1836 String host = "";
1837 String port = "";
1838 String exclList = "";
1839 if (proxy != null) {
1840 host = proxy.getHost();
1841 port = Integer.toString(proxy.getPort());
1842 exclList = proxy.getExclusionList();
1843 }
1844 synchronized (ActivityManagerService.this) {
1845 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1846 ProcessRecord r = mLruProcesses.get(i);
1847 if (r.thread != null) {
1848 try {
1849 r.thread.setHttpProxy(host, port, exclList);
1850 } catch (RemoteException ex) {
1851 Slog.w(TAG, "Failed to update http proxy for: " +
1852 r.info.processName);
1853 }
1854 }
1855 }
1856 }
1857 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 case SHOW_UID_ERROR_MSG: {
1859 // XXX This is a temporary dialog, no need to localize.
1860 AlertDialog d = new BaseErrorDialog(mContext);
1861 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1862 d.setCancelable(false);
1863 d.setTitle("System UIDs Inconsistent");
1864 d.setMessage("UIDs on the system are inconsistent, you need to wipe your data partition or your device will be unstable.");
Christian Mehlmauer7664e202010-07-20 08:46:17 +02001865 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1867 mUidAlert = d;
1868 d.show();
1869 } break;
1870 case IM_FEELING_LUCKY_MSG: {
1871 if (mUidAlert != null) {
1872 mUidAlert.dismiss();
1873 mUidAlert = null;
1874 }
1875 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001877 if (mDidDexOpt) {
1878 mDidDexOpt = false;
1879 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1880 nmsg.obj = msg.obj;
1881 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1882 return;
1883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 ProcessRecord app = (ProcessRecord)msg.obj;
1885 synchronized (ActivityManagerService.this) {
1886 processStartTimedOutLocked(app);
1887 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001888 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001889 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1890 synchronized (ActivityManagerService.this) {
1891 doPendingActivityLaunchesLocked(true);
1892 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001893 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001894 case KILL_APPLICATION_MSG: {
1895 synchronized (ActivityManagerService.this) {
1896 int uid = msg.arg1;
1897 boolean restart = (msg.arg2 == 1);
1898 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001899 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001900 }
1901 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001902 case FINALIZE_PENDING_INTENT_MSG: {
1903 ((PendingIntentRecord)msg.obj).completeFinalize();
1904 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001905 case POST_HEAVY_NOTIFICATION_MSG: {
1906 INotificationManager inm = NotificationManager.getService();
1907 if (inm == null) {
1908 return;
1909 }
1910
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001911 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001912 ProcessRecord process = root.app;
1913 if (process == null) {
1914 return;
1915 }
1916
1917 try {
1918 Context context = mContext.createPackageContext(process.info.packageName, 0);
1919 String text = mContext.getString(R.string.heavy_weight_notification,
1920 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1921 Notification notification = new Notification();
1922 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1923 notification.when = 0;
1924 notification.flags = Notification.FLAG_ONGOING_EVENT;
1925 notification.tickerText = text;
1926 notification.defaults = 0; // please be quiet
1927 notification.sound = null;
1928 notification.vibrate = null;
1929 notification.setLatestEventInfo(context, text,
1930 mContext.getText(R.string.heavy_weight_notification_detail),
1931 PendingIntent.getActivity(mContext, 0, root.intent,
1932 PendingIntent.FLAG_CANCEL_CURRENT));
1933
1934 try {
1935 int[] outId = new int[1];
1936 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1937 notification, outId);
1938 } catch (RuntimeException e) {
1939 Slog.w(ActivityManagerService.TAG,
1940 "Error showing notification for heavy-weight app", e);
1941 } catch (RemoteException e) {
1942 }
1943 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001944 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001945 }
1946 } break;
1947 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1948 INotificationManager inm = NotificationManager.getService();
1949 if (inm == null) {
1950 return;
1951 }
1952 try {
1953 inm.cancelNotification("android",
1954 R.string.heavy_weight_notification);
1955 } catch (RuntimeException e) {
1956 Slog.w(ActivityManagerService.TAG,
1957 "Error canceling notification for service", e);
1958 } catch (RemoteException e) {
1959 }
1960 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001961 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1962 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001963 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001964 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001965 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1966 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001967 }
1968 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001969 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1970 synchronized (ActivityManagerService.this) {
1971 ActivityRecord ar = (ActivityRecord)msg.obj;
1972 if (mCompatModeDialog != null) {
1973 if (mCompatModeDialog.mAppInfo.packageName.equals(
1974 ar.info.applicationInfo.packageName)) {
1975 return;
1976 }
1977 mCompatModeDialog.dismiss();
1978 mCompatModeDialog = null;
1979 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001980 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001981 if (mCompatModePackages.getPackageAskCompatModeLocked(
1982 ar.packageName)) {
1983 int mode = mCompatModePackages.computeCompatModeLocked(
1984 ar.info.applicationInfo);
1985 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1986 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1987 mCompatModeDialog = new CompatModeDialog(
1988 ActivityManagerService.this, mContext,
1989 ar.info.applicationInfo);
1990 mCompatModeDialog.show();
1991 }
1992 }
1993 }
1994 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001995 break;
1996 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001997 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001998 final int pid = msg.arg1;
1999 final int uid = msg.arg2;
2000 final boolean foregroundActivities = (Boolean) msg.obj;
2001 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002002 break;
2003 }
2004 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07002005 final int pid = msg.arg1;
2006 final int uid = msg.arg2;
2007 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002008 break;
2009 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002010 case REPORT_MEM_USAGE: {
2011 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
2012 if (!isDebuggable) {
2013 return;
2014 }
2015 synchronized (ActivityManagerService.this) {
2016 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002017 if (now < (mLastMemUsageReportTime+5*60*1000)) {
2018 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002019 // avoid spamming.
2020 return;
2021 }
2022 mLastMemUsageReportTime = now;
2023 }
2024 Thread thread = new Thread() {
2025 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002026 StringBuilder dropBuilder = new StringBuilder(1024);
2027 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08002028 StringWriter oomSw = new StringWriter();
2029 PrintWriter oomPw = new PrintWriter(oomSw);
2030 StringWriter catSw = new StringWriter();
2031 PrintWriter catPw = new PrintWriter(catSw);
2032 String[] emptyArgs = new String[] { };
2033 StringBuilder tag = new StringBuilder(128);
2034 StringBuilder stack = new StringBuilder(128);
2035 tag.append("Low on memory -- ");
2036 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
2037 tag, stack);
2038 dropBuilder.append(stack);
2039 dropBuilder.append('\n');
2040 dropBuilder.append('\n');
2041 String oomString = oomSw.toString();
2042 dropBuilder.append(oomString);
2043 dropBuilder.append('\n');
2044 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002045 try {
2046 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
2047 "procrank", });
2048 final InputStreamReader converter = new InputStreamReader(
2049 proc.getInputStream());
2050 BufferedReader in = new BufferedReader(converter);
2051 String line;
2052 while (true) {
2053 line = in.readLine();
2054 if (line == null) {
2055 break;
2056 }
2057 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002058 logBuilder.append(line);
2059 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002060 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002061 dropBuilder.append(line);
2062 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002063 }
2064 converter.close();
2065 } catch (IOException e) {
2066 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002067 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08002068 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002069 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002070 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002071 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002072 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002073 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002074 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002075 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08002076 addErrorToDropBox("lowmem", null, "system_server", null,
2077 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002078 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002079 synchronized (ActivityManagerService.this) {
2080 long now = SystemClock.uptimeMillis();
2081 if (mLastMemUsageReportTime < now) {
2082 mLastMemUsageReportTime = now;
2083 }
2084 }
2085 }
2086 };
2087 thread.start();
2088 break;
2089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
2091 }
2092 };
2093
2094 public static void setSystemProcess() {
2095 try {
2096 ActivityManagerService m = mSelf;
2097
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002098 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07002100 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08002101 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 if (MONITOR_CPU_USAGE) {
2103 ServiceManager.addService("cpuinfo", new CpuBinder(m));
2104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 ServiceManager.addService("permission", new PermissionController(m));
2106
2107 ApplicationInfo info =
2108 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07002109 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07002110 mSystemThread.installSystemApplicationInfo(info);
2111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 synchronized (mSelf) {
2113 ProcessRecord app = mSelf.newProcessRecordLocked(
2114 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002115 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08002117 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07002118 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002119 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 synchronized (mSelf.mPidsSelfLocked) {
2121 mSelf.mPidsSelfLocked.put(app.pid, app);
2122 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002123 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 }
2125 } catch (PackageManager.NameNotFoundException e) {
2126 throw new RuntimeException(
2127 "Unable to find android system package", e);
2128 }
2129 }
2130
2131 public void setWindowManager(WindowManagerService wm) {
2132 mWindowManager = wm;
2133 }
2134
2135 public static final Context main(int factoryTest) {
2136 AThread thr = new AThread();
2137 thr.start();
2138
2139 synchronized (thr) {
2140 while (thr.mService == null) {
2141 try {
2142 thr.wait();
2143 } catch (InterruptedException e) {
2144 }
2145 }
2146 }
2147
2148 ActivityManagerService m = thr.mService;
2149 mSelf = m;
2150 ActivityThread at = ActivityThread.systemMain();
2151 mSystemThread = at;
2152 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08002153 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 m.mContext = context;
2155 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002156 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157
2158 m.mBatteryStatsService.publish(context);
2159 m.mUsageStatsService.publish(context);
2160
2161 synchronized (thr) {
2162 thr.mReady = true;
2163 thr.notifyAll();
2164 }
2165
2166 m.startRunning(null, null, null, null);
2167
2168 return context;
2169 }
2170
2171 public static ActivityManagerService self() {
2172 return mSelf;
2173 }
2174
2175 static class AThread extends Thread {
2176 ActivityManagerService mService;
2177 boolean mReady = false;
2178
2179 public AThread() {
2180 super("ActivityManager");
2181 }
2182
2183 public void run() {
2184 Looper.prepare();
2185
2186 android.os.Process.setThreadPriority(
2187 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07002188 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189
2190 ActivityManagerService m = new ActivityManagerService();
2191
2192 synchronized (this) {
2193 mService = m;
2194 notifyAll();
2195 }
2196
2197 synchronized (this) {
2198 while (!mReady) {
2199 try {
2200 wait();
2201 } catch (InterruptedException e) {
2202 }
2203 }
2204 }
2205
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07002206 // For debug builds, log event loop stalls to dropbox for analysis.
2207 if (StrictMode.conditionallyEnableDebugLogging()) {
2208 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
2209 }
2210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 Looper.loop();
2212 }
2213 }
2214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 static class MemBinder extends Binder {
2216 ActivityManagerService mActivityManagerService;
2217 MemBinder(ActivityManagerService activityManagerService) {
2218 mActivityManagerService = activityManagerService;
2219 }
2220
2221 @Override
2222 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002223 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2224 != PackageManager.PERMISSION_GRANTED) {
2225 pw.println("Permission Denial: can't dump meminfo from from pid="
2226 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2227 + " without permission " + android.Manifest.permission.DUMP);
2228 return;
2229 }
2230
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08002231 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08002232 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 }
2234 }
2235
Chet Haase9c1e23b2011-03-24 10:51:31 -07002236 static class GraphicsBinder extends Binder {
2237 ActivityManagerService mActivityManagerService;
2238 GraphicsBinder(ActivityManagerService activityManagerService) {
2239 mActivityManagerService = activityManagerService;
2240 }
2241
2242 @Override
2243 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002244 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2245 != PackageManager.PERMISSION_GRANTED) {
2246 pw.println("Permission Denial: can't dump gfxinfo from from pid="
2247 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2248 + " without permission " + android.Manifest.permission.DUMP);
2249 return;
2250 }
2251
Dianne Hackborne17aeb32011-04-07 15:11:57 -07002252 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07002253 }
2254 }
2255
Jeff Brown6754ba22011-12-14 20:20:01 -08002256 static class DbBinder extends Binder {
2257 ActivityManagerService mActivityManagerService;
2258 DbBinder(ActivityManagerService activityManagerService) {
2259 mActivityManagerService = activityManagerService;
2260 }
2261
2262 @Override
2263 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2264 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2265 != PackageManager.PERMISSION_GRANTED) {
2266 pw.println("Permission Denial: can't dump dbinfo from from pid="
2267 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2268 + " without permission " + android.Manifest.permission.DUMP);
2269 return;
2270 }
2271
2272 mActivityManagerService.dumpDbInfo(fd, pw, args);
2273 }
2274 }
2275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 static class CpuBinder extends Binder {
2277 ActivityManagerService mActivityManagerService;
2278 CpuBinder(ActivityManagerService activityManagerService) {
2279 mActivityManagerService = activityManagerService;
2280 }
2281
2282 @Override
2283 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002284 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2285 != PackageManager.PERMISSION_GRANTED) {
2286 pw.println("Permission Denial: can't dump cpuinfo from from pid="
2287 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2288 + " without permission " + android.Manifest.permission.DUMP);
2289 return;
2290 }
2291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002293 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
2294 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
2295 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 }
2297 }
2298 }
2299
2300 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002301 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07002302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 File dataDir = Environment.getDataDirectory();
2304 File systemDir = new File(dataDir, "system");
2305 systemDir.mkdirs();
2306 mBatteryStatsService = new BatteryStatsService(new File(
2307 systemDir, "batterystats.bin").toString());
2308 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07002309 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07002310 mOnBattery = DEBUG_POWER ? true
2311 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002312 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002314 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07002315 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07002316 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317
Jack Palevichb90d28c2009-07-22 15:35:24 -07002318 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
2319 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
2320
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002321 mConfiguration.setToDefaults();
2322 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08002323 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 mProcessStats.init();
2325
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002326 mCompatModePackages = new CompatModePackages(this, systemDir);
2327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 // Add ourself to the Watchdog monitors.
2329 Watchdog.getInstance().addMonitor(this);
2330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 mProcessStatsThread = new Thread("ProcessStats") {
2332 public void run() {
2333 while (true) {
2334 try {
2335 try {
2336 synchronized(this) {
2337 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002338 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002340 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 // + ", write delay=" + nextWriteDelay);
2342 if (nextWriteDelay < nextCpuDelay) {
2343 nextCpuDelay = nextWriteDelay;
2344 }
2345 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002346 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 this.wait(nextCpuDelay);
2348 }
2349 }
2350 } catch (InterruptedException e) {
2351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 updateCpuStatsNow();
2353 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002354 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 }
2356 }
2357 }
2358 };
2359 mProcessStatsThread.start();
2360 }
2361
2362 @Override
2363 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2364 throws RemoteException {
2365 try {
2366 return super.onTransact(code, data, reply, flags);
2367 } catch (RuntimeException e) {
2368 // The activity manager only throws security exceptions, so let's
2369 // log all others.
2370 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002371 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 }
2373 throw e;
2374 }
2375 }
2376
2377 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002378 final long now = SystemClock.uptimeMillis();
2379 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
2380 return;
2381 }
2382 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
2383 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 mProcessStatsThread.notify();
2385 }
2386 }
2387 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 void updateCpuStatsNow() {
2390 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002391 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 final long now = SystemClock.uptimeMillis();
2393 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07002394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002396 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
2397 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 haveNewCpuStats = true;
2399 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002400 //Slog.i(TAG, mProcessStats.printCurrentState());
2401 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 // + mProcessStats.getTotalCpuPercent() + "%");
2403
Joe Onorato8a9b2202010-02-26 18:56:32 -08002404 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 if ("true".equals(SystemProperties.get("events.cpu"))) {
2406 int user = mProcessStats.getLastUserTime();
2407 int system = mProcessStats.getLastSystemTime();
2408 int iowait = mProcessStats.getLastIoWaitTime();
2409 int irq = mProcessStats.getLastIrqTime();
2410 int softIrq = mProcessStats.getLastSoftIrqTime();
2411 int idle = mProcessStats.getLastIdleTime();
2412
2413 int total = user + system + iowait + irq + softIrq + idle;
2414 if (total == 0) total = 1;
2415
Doug Zongker2bec3d42009-12-04 12:52:44 -08002416 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 ((user+system+iowait+irq+softIrq) * 100) / total,
2418 (user * 100) / total,
2419 (system * 100) / total,
2420 (iowait * 100) / total,
2421 (irq * 100) / total,
2422 (softIrq * 100) / total);
2423 }
2424 }
2425
Amith Yamasanie43530a2009-08-21 13:11:37 -07002426 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07002427 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002428 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 synchronized(mPidsSelfLocked) {
2430 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002431 if (mOnBattery) {
2432 int perc = bstats.startAddingCpuLocked();
2433 int totalUTime = 0;
2434 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07002435 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07002437 ProcessStats.Stats st = mProcessStats.getStats(i);
2438 if (!st.working) {
2439 continue;
2440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002442 int otherUTime = (st.rel_utime*perc)/100;
2443 int otherSTime = (st.rel_stime*perc)/100;
2444 totalUTime += otherUTime;
2445 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 if (pr != null) {
2447 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002448 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
2449 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07002450 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07002451 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002452 } else {
2453 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07002454 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002455 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002456 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
2457 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07002458 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 }
2461 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002462 bstats.finishAddingCpuLocked(perc, totalUTime,
2463 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 }
2465 }
2466 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
2469 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07002470 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 }
2472 }
2473 }
2474 }
2475
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002476 @Override
2477 public void batteryNeedsCpuUpdate() {
2478 updateCpuStatsNow();
2479 }
2480
2481 @Override
2482 public void batteryPowerChanged(boolean onBattery) {
2483 // When plugging in, update the CPU stats first before changing
2484 // the plug state.
2485 updateCpuStatsNow();
2486 synchronized (this) {
2487 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07002488 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002489 }
2490 }
2491 }
2492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 /**
2494 * Initialize the application bind args. These are passed to each
2495 * process when the bindApplication() IPC is sent to the process. They're
2496 * lazily setup to make sure the services are running when they're asked for.
2497 */
2498 private HashMap<String, IBinder> getCommonServicesLocked() {
2499 if (mAppBindArgs == null) {
2500 mAppBindArgs = new HashMap<String, IBinder>();
2501
2502 // Setup the application init args
2503 mAppBindArgs.put("package", ServiceManager.getService("package"));
2504 mAppBindArgs.put("window", ServiceManager.getService("window"));
2505 mAppBindArgs.put(Context.ALARM_SERVICE,
2506 ServiceManager.getService(Context.ALARM_SERVICE));
2507 }
2508 return mAppBindArgs;
2509 }
2510
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002511 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 if (mFocusedActivity != r) {
2513 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002514 if (r != null) {
2515 mWindowManager.setFocusedApp(r.appToken, true);
2516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 }
2518 }
2519
Dianne Hackborn906497c2010-05-10 15:57:38 -07002520 private final void updateLruProcessInternalLocked(ProcessRecord app,
2521 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002523 int lrui = mLruProcesses.indexOf(app);
2524 if (lrui >= 0) mLruProcesses.remove(lrui);
2525
2526 int i = mLruProcesses.size()-1;
2527 int skipTop = 0;
2528
Dianne Hackborn906497c2010-05-10 15:57:38 -07002529 app.lruSeq = mLruSeq;
2530
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002531 // compute the new weight for this process.
2532 if (updateActivityTime) {
2533 app.lastActivityTime = SystemClock.uptimeMillis();
2534 }
2535 if (app.activities.size() > 0) {
2536 // If this process has activities, we more strongly want to keep
2537 // it around.
2538 app.lruWeight = app.lastActivityTime;
2539 } else if (app.pubProviders.size() > 0) {
2540 // If this process contains content providers, we want to keep
2541 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002542 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002543 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002544 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002545 } else {
2546 // If this process doesn't have activities, we less strongly
2547 // want to keep it around, and generally want to avoid getting
2548 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002549 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002550 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002551 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002552 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07002553
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002554 while (i >= 0) {
2555 ProcessRecord p = mLruProcesses.get(i);
2556 // If this app shouldn't be in front of the first N background
2557 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002558 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002559 skipTop--;
2560 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07002561 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002562 mLruProcesses.add(i+1, app);
2563 break;
2564 }
2565 i--;
2566 }
2567 if (i < 0) {
2568 mLruProcesses.add(0, app);
2569 }
2570
Dianne Hackborn906497c2010-05-10 15:57:38 -07002571 // If the app is currently using a content provider or service,
2572 // bump those processes as well.
2573 if (app.connections.size() > 0) {
2574 for (ConnectionRecord cr : app.connections) {
2575 if (cr.binding != null && cr.binding.service != null
2576 && cr.binding.service.app != null
2577 && cr.binding.service.app.lruSeq != mLruSeq) {
2578 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
2579 updateActivityTime, i+1);
2580 }
2581 }
2582 }
2583 if (app.conProviders.size() > 0) {
2584 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07002585 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
2586 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07002587 updateActivityTime, i+1);
2588 }
2589 }
2590 }
2591
Joe Onorato8a9b2202010-02-26 18:56:32 -08002592 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 if (oomAdj) {
2594 updateOomAdjLocked();
2595 }
2596 }
2597
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002598 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07002599 boolean oomAdj, boolean updateActivityTime) {
2600 mLruSeq++;
2601 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
2602 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002603
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002604 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 String processName, int uid) {
2606 if (uid == Process.SYSTEM_UID) {
2607 // The system gets to run in any process. If there are multiple
2608 // processes with the same uid, just pick the first (this
2609 // should never happen).
2610 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
2611 processName);
2612 return procs != null ? procs.valueAt(0) : null;
2613 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002614 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 ProcessRecord proc = mProcessNames.get(processName, uid);
2616 return proc;
2617 }
2618
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002619 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002620 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002621 try {
2622 if (pm.performDexOpt(packageName)) {
2623 mDidDexOpt = true;
2624 }
2625 } catch (RemoteException e) {
2626 }
2627 }
2628
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002629 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 int transit = mWindowManager.getPendingAppTransition();
2631 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
2632 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
2633 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
2634 }
2635
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002636 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002638 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
2639 boolean isolated) {
2640 ProcessRecord app;
2641 if (!isolated) {
2642 app = getProcessRecordLocked(processName, info.uid);
2643 } else {
2644 // If this is an isolated process, it can't re-use an existing process.
2645 app = null;
2646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 // We don't have to do anything more if:
2648 // (1) There is an existing application record; and
2649 // (2) The caller doesn't think it is dead, OR there is no thread
2650 // object attached to it so we know it couldn't have crashed; and
2651 // (3) There is a pid assigned to it, so it is either starting or
2652 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002653 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 + " app=" + app + " knownToBeDead=" + knownToBeDead
2655 + " thread=" + (app != null ? app.thread : null)
2656 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01002657 if (app != null && app.pid > 0) {
2658 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002659 // We already have the app running, or are waiting for it to
2660 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002661 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002662 // If this is a new package in the process, add the package to the list
2663 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002664 return app;
2665 } else {
2666 // An application record is attached to a previous process,
2667 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002668 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002669 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 String hostingNameStr = hostingName != null
2674 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002675
2676 if (!isolated) {
2677 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2678 // If we are in the background, then check to see if this process
2679 // is bad. If so, we will just silently fail.
2680 if (mBadProcesses.get(info.processName, info.uid) != null) {
2681 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2682 + "/" + info.processName);
2683 return null;
2684 }
2685 } else {
2686 // When the user is explicitly starting a process, then clear its
2687 // crash count so that we won't make it bad until they see at
2688 // least one crash dialog again, and make the process good again
2689 // if it had been bad.
2690 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002691 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002692 mProcessCrashTimes.remove(info.processName, info.uid);
2693 if (mBadProcesses.get(info.processName, info.uid) != null) {
2694 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
2695 info.processName);
2696 mBadProcesses.remove(info.processName, info.uid);
2697 if (app != null) {
2698 app.bad = false;
2699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 }
2701 }
2702 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002705 app = newProcessRecordLocked(null, info, processName, isolated);
2706 if (app == null) {
2707 Slog.w(TAG, "Failed making new process record for "
2708 + processName + "/" + info.uid + " isolated=" + isolated);
2709 return null;
2710 }
2711 mProcessNames.put(processName, app.uid, app);
2712 if (isolated) {
2713 mIsolatedProcesses.put(app.uid, app);
2714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 } else {
2716 // If this is a new package in the process, add the package to the list
2717 app.addPackage(info.packageName);
2718 }
2719
2720 // If the system is not ready yet, then hold off on starting this
2721 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002722 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002723 && !isAllowedWhileBooting(info)
2724 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 if (!mProcessesOnHold.contains(app)) {
2726 mProcessesOnHold.add(app);
2727 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002728 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 return app;
2730 }
2731
2732 startProcessLocked(app, hostingType, hostingNameStr);
2733 return (app.pid != 0) ? app : null;
2734 }
2735
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002736 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2737 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2738 }
2739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 private final void startProcessLocked(ProcessRecord app,
2741 String hostingType, String hostingNameStr) {
2742 if (app.pid > 0 && app.pid != MY_PID) {
2743 synchronized (mPidsSelfLocked) {
2744 mPidsSelfLocked.remove(app.pid);
2745 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2746 }
2747 app.pid = 0;
2748 }
2749
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002750 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2751 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 mProcessesOnHold.remove(app);
2753
2754 updateCpuStats();
2755
2756 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2757 mProcDeaths[0] = 0;
2758
2759 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002760 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002763 if (!app.isolated) {
2764 try {
2765 gids = mContext.getPackageManager().getPackageGids(
2766 app.info.packageName);
2767 } catch (PackageManager.NameNotFoundException e) {
2768 Slog.w(TAG, "Unable to retrieve gids", e);
2769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 }
2771 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2772 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2773 && mTopComponent != null
2774 && app.processName.equals(mTopComponent.getPackageName())) {
2775 uid = 0;
2776 }
2777 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2778 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2779 uid = 0;
2780 }
2781 }
2782 int debugFlags = 0;
2783 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2784 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002785 // Also turn on CheckJNI for debuggable apps. It's quite
2786 // awkward to turn on otherwise.
2787 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002789 // Run the app in safe mode if its manifest requests so or the
2790 // system is booted in safe mode.
2791 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2792 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002793 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2796 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2797 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002798 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2799 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 if ("1".equals(SystemProperties.get("debug.assert"))) {
2802 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2803 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002804
2805 // Start the process. It will either succeed and return a result containing
2806 // the PID of the new process, or else throw a RuntimeException.
2807 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002808 app.processName, uid, uid, gids, debugFlags,
2809 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2812 synchronized (bs) {
2813 if (bs.isOnBattery()) {
2814 app.batteryStats.incStartsLocked();
2815 }
2816 }
2817
Jeff Brown3f9dd282011-07-08 20:02:19 -07002818 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 app.processName, hostingType,
2820 hostingNameStr != null ? hostingNameStr : "");
2821
2822 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002823 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 }
2825
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002826 StringBuilder buf = mStringBuilder;
2827 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 buf.append("Start proc ");
2829 buf.append(app.processName);
2830 buf.append(" for ");
2831 buf.append(hostingType);
2832 if (hostingNameStr != null) {
2833 buf.append(" ");
2834 buf.append(hostingNameStr);
2835 }
2836 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002837 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 buf.append(" uid=");
2839 buf.append(uid);
2840 buf.append(" gids={");
2841 if (gids != null) {
2842 for (int gi=0; gi<gids.length; gi++) {
2843 if (gi != 0) buf.append(", ");
2844 buf.append(gids[gi]);
2845
2846 }
2847 }
2848 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002849 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002850 app.pid = startResult.pid;
2851 app.usingWrapper = startResult.usingWrapper;
2852 app.removed = false;
2853 synchronized (mPidsSelfLocked) {
2854 this.mPidsSelfLocked.put(startResult.pid, app);
2855 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2856 msg.obj = app;
2857 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2858 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 }
2860 } catch (RuntimeException e) {
2861 // XXX do better error recovery.
2862 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002863 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 }
2865 }
2866
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002867 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 if (resumed) {
2869 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2870 } else {
2871 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2872 }
2873 }
2874
Amith Yamasani742a6712011-05-04 14:49:28 -07002875 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002876 if (mHeadless) {
2877 // Added because none of the other calls to ensureBootCompleted seem to fire
2878 // when running headless.
2879 ensureBootCompleted();
2880 return false;
2881 }
2882
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002883 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2884 && mTopAction == null) {
2885 // We are running in factory test mode, but unable to find
2886 // the factory test app, so just sit around displaying the
2887 // error message and don't try to start anything.
2888 return false;
2889 }
2890 Intent intent = new Intent(
2891 mTopAction,
2892 mTopData != null ? Uri.parse(mTopData) : null);
2893 intent.setComponent(mTopComponent);
2894 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2895 intent.addCategory(Intent.CATEGORY_HOME);
2896 }
2897 ActivityInfo aInfo =
2898 intent.resolveActivityInfo(mContext.getPackageManager(),
2899 STOCK_PM_FLAGS);
2900 if (aInfo != null) {
2901 intent.setComponent(new ComponentName(
2902 aInfo.applicationInfo.packageName, aInfo.name));
2903 // Don't do this if the home app is currently being
2904 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002905 aInfo = new ActivityInfo(aInfo);
2906 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002907 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2908 aInfo.applicationInfo.uid);
2909 if (app == null || app.instrumentationClass == null) {
2910 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002911 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002912 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002913 }
2914 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002915
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002916 return true;
2917 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002918
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002919 /**
2920 * Starts the "new version setup screen" if appropriate.
2921 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002922 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002923 // Only do this once per boot.
2924 if (mCheckedForSetup) {
2925 return;
2926 }
2927
2928 // We will show this screen if the current one is a different
2929 // version than the last one shown, and we are not running in
2930 // low-level factory test mode.
2931 final ContentResolver resolver = mContext.getContentResolver();
2932 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2933 Settings.Secure.getInt(resolver,
2934 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2935 mCheckedForSetup = true;
2936
2937 // See if we should be showing the platform update setup UI.
2938 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2939 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2940 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2941
2942 // We don't allow third party apps to replace this.
2943 ResolveInfo ri = null;
2944 for (int i=0; ris != null && i<ris.size(); i++) {
2945 if ((ris.get(i).activityInfo.applicationInfo.flags
2946 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2947 ri = ris.get(i);
2948 break;
2949 }
2950 }
2951
2952 if (ri != null) {
2953 String vers = ri.activityInfo.metaData != null
2954 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2955 : null;
2956 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2957 vers = ri.activityInfo.applicationInfo.metaData.getString(
2958 Intent.METADATA_SETUP_VERSION);
2959 }
2960 String lastVers = Settings.Secure.getString(
2961 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2962 if (vers != null && !vers.equals(lastVers)) {
2963 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2964 intent.setComponent(new ComponentName(
2965 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002966 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002967 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002968 }
2969 }
2970 }
2971 }
2972
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002973 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002974 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002975 }
2976
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002977 void enforceNotIsolatedCaller(String caller) {
2978 if (UserId.isIsolated(Binder.getCallingUid())) {
2979 throw new SecurityException("Isolated process not allowed to call " + caller);
2980 }
2981 }
2982
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002983 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002984 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002985 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002986 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2987 }
2988 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002989
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002990 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002991 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2992 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002993 synchronized (this) {
2994 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2995 }
2996 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002997
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002998 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002999 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07003000 synchronized (this) {
3001 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
3002 }
3003 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003004
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07003005 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003006 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3007 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07003008 synchronized (this) {
3009 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003010 }
3011 }
3012
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07003013 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003014 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07003015 synchronized (this) {
3016 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
3017 }
3018 }
3019
3020 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003021 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3022 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07003023 synchronized (this) {
3024 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
3025 }
3026 }
3027
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003028 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003029 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003030
3031 final int identHash = System.identityHashCode(r);
3032 updateUsageStats(r, true);
3033
3034 int i = mWatchers.beginBroadcast();
3035 while (i > 0) {
3036 i--;
3037 IActivityWatcher w = mWatchers.getBroadcastItem(i);
3038 if (w != null) {
3039 try {
3040 w.activityResuming(identHash);
3041 } catch (RemoteException e) {
3042 }
3043 }
3044 }
3045 mWatchers.finishBroadcast();
3046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047
Jeff Sharkeya4620792011-05-20 15:29:23 -07003048 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
3049 int i = mProcessObservers.beginBroadcast();
3050 while (i > 0) {
3051 i--;
3052 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3053 if (observer != null) {
3054 try {
3055 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
3056 } catch (RemoteException e) {
3057 }
3058 }
3059 }
3060 mProcessObservers.finishBroadcast();
3061 }
3062
3063 private void dispatchProcessDied(int pid, int uid) {
3064 int i = mProcessObservers.beginBroadcast();
3065 while (i > 0) {
3066 i--;
3067 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3068 if (observer != null) {
3069 try {
3070 observer.onProcessDied(pid, uid);
3071 } catch (RemoteException e) {
3072 }
3073 }
3074 }
3075 mProcessObservers.finishBroadcast();
3076 }
3077
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003078 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003079 final int N = mPendingActivityLaunches.size();
3080 if (N <= 0) {
3081 return;
3082 }
3083 for (int i=0; i<N; i++) {
3084 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003085 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003086 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
3087 doResume && i == (N-1));
3088 }
3089 mPendingActivityLaunches.clear();
3090 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003091
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003092 public final int startActivity(IApplicationThread caller,
3093 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3094 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003095 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
3096 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003097 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07003098 int userId = 0;
3099 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
3100 // Requesting home, set the identity to the current user
3101 // HACK!
3102 userId = mCurrentUserId;
3103 } else {
3104 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
3105 // the current user's userId
3106 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
3107 userId = 0;
3108 } else {
3109 userId = Binder.getOrigCallingUser();
3110 }
3111 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003112 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -07003113 grantedUriPermissions, grantedMode, resultTo, resultWho, requestCode, onlyIfNeeded,
3114 debug, profileFile, profileFd, autoStopProfiler, null, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003115 }
3116
3117 public final WaitResult startActivityAndWait(IApplicationThread caller,
3118 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3119 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003120 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
3121 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003122 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003123 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07003124 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003125 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003126 grantedUriPermissions, grantedMode, resultTo, resultWho,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003127 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
Amith Yamasani742a6712011-05-04 14:49:28 -07003128 res, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003129 return res;
3130 }
3131
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003132 public final int startActivityWithConfig(IApplicationThread caller,
3133 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3134 int grantedMode, IBinder resultTo,
3135 String resultWho, int requestCode, boolean onlyIfNeeded,
3136 boolean debug, Configuration config) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003137 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07003138 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003139 grantedUriPermissions, grantedMode, resultTo, resultWho,
Amith Yamasani742a6712011-05-04 14:49:28 -07003140 requestCode, onlyIfNeeded,
3141 debug, null, null, false, null, config, Binder.getOrigCallingUser());
3142 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003143 }
3144
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003145 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003146 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003147 IBinder resultTo, String resultWho, int requestCode,
3148 int flagsMask, int flagsValues) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003149 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003150 // Refuse possible leaked file descriptors
3151 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
3152 throw new IllegalArgumentException("File descriptors passed in Intent");
3153 }
3154
3155 IIntentSender sender = intent.getTarget();
3156 if (!(sender instanceof PendingIntentRecord)) {
3157 throw new IllegalArgumentException("Bad PendingIntent object");
3158 }
3159
3160 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003161
3162 synchronized (this) {
3163 // If this is coming from the currently resumed activity, it is
3164 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003165 if (mMainStack.mResumedActivity != null
3166 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003167 Binder.getCallingUid()) {
3168 mAppSwitchesAllowedTime = 0;
3169 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003170 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003171 int ret = pir.sendInner(0, fillInIntent, resolvedType, null,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003172 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
Amith Yamasani742a6712011-05-04 14:49:28 -07003173 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003174 }
3175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 public boolean startNextMatchingActivity(IBinder callingActivity,
3177 Intent intent) {
3178 // Refuse possible leaked file descriptors
3179 if (intent != null && intent.hasFileDescriptors() == true) {
3180 throw new IllegalArgumentException("File descriptors passed in Intent");
3181 }
3182
3183 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003184 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
3185 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 return false;
3187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 if (r.app == null || r.app.thread == null) {
3189 // The caller is not running... d'oh!
3190 return false;
3191 }
3192 intent = new Intent(intent);
3193 // The caller is not allowed to change the data.
3194 intent.setDataAndType(r.intent.getData(), r.intent.getType());
3195 // And we are resetting to find the next component...
3196 intent.setComponent(null);
3197
3198 ActivityInfo aInfo = null;
3199 try {
3200 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003201 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07003203 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204
3205 // Look for the original activity in the list...
3206 final int N = resolves != null ? resolves.size() : 0;
3207 for (int i=0; i<N; i++) {
3208 ResolveInfo rInfo = resolves.get(i);
3209 if (rInfo.activityInfo.packageName.equals(r.packageName)
3210 && rInfo.activityInfo.name.equals(r.info.name)) {
3211 // We found the current one... the next matching is
3212 // after it.
3213 i++;
3214 if (i<N) {
3215 aInfo = resolves.get(i).activityInfo;
3216 }
3217 break;
3218 }
3219 }
3220 } catch (RemoteException e) {
3221 }
3222
3223 if (aInfo == null) {
3224 // Nobody who is next!
3225 return false;
3226 }
3227
3228 intent.setComponent(new ComponentName(
3229 aInfo.applicationInfo.packageName, aInfo.name));
3230 intent.setFlags(intent.getFlags()&~(
3231 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
3232 Intent.FLAG_ACTIVITY_CLEAR_TOP|
3233 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
3234 Intent.FLAG_ACTIVITY_NEW_TASK));
3235
3236 // Okay now we need to start the new activity, replacing the
3237 // currently running activity. This is a little tricky because
3238 // we want to start the new one as if the current one is finished,
3239 // but not finish the current one first so that there is no flicker.
3240 // And thus...
3241 final boolean wasFinishing = r.finishing;
3242 r.finishing = true;
3243
3244 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003245 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 final String resultWho = r.resultWho;
3247 final int requestCode = r.requestCode;
3248 r.resultTo = null;
3249 if (resultTo != null) {
3250 resultTo.removeResultsLocked(r, resultWho, requestCode);
3251 }
3252
3253 final long origId = Binder.clearCallingIdentity();
3254 // XXX we are not dealing with propagating grantedUriPermissions...
3255 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003256 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackbornbe707852011-11-11 14:32:10 -08003257 r.resolvedType, null, 0, aInfo,
3258 resultTo != null ? resultTo.appToken : null, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003259 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 Binder.restoreCallingIdentity(origId);
3261
3262 r.finishing = wasFinishing;
3263 if (res != START_SUCCESS) {
3264 return false;
3265 }
3266 return true;
3267 }
3268 }
3269
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003270 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 Intent intent, String resolvedType, IBinder resultTo,
3272 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003273
3274 // This is so super not safe, that only the system (or okay root)
3275 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07003276 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003277 final int callingUid = Binder.getCallingUid();
3278 if (callingUid != 0 && callingUid != Process.myUid()) {
3279 throw new SecurityException(
3280 "startActivityInPackage only available to the system");
3281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282
Amith Yamasani742a6712011-05-04 14:49:28 -07003283 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003284 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false,
Amith Yamasani742a6712011-05-04 14:49:28 -07003285 null, null, false, null, null, userId);
3286 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003287 }
3288
3289 public final int startActivities(IApplicationThread caller,
3290 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003291 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07003292 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
3293 Binder.getOrigCallingUser());
3294 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003295 }
3296
3297 public final int startActivitiesInPackage(int uid,
3298 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
3299
3300 // This is so super not safe, that only the system (or okay root)
3301 // can do it.
3302 final int callingUid = Binder.getCallingUid();
3303 if (callingUid != 0 && callingUid != Process.myUid()) {
3304 throw new SecurityException(
3305 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003307 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
3308 UserId.getUserId(uid));
3309 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 }
3311
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003312 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08003314 // Quick case: check if the top-most recent task is the same.
3315 if (N > 0 && mRecentTasks.get(0) == task) {
3316 return;
3317 }
3318 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 for (int i=0; i<N; i++) {
3320 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07003321 if (task.userId == tr.userId
3322 && ((task.affinity != null && task.affinity.equals(tr.affinity))
3323 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 mRecentTasks.remove(i);
3325 i--;
3326 N--;
3327 if (task.intent == null) {
3328 // If the new recent task we are adding is not fully
3329 // specified, then replace it with the existing recent task.
3330 task = tr;
3331 }
3332 }
3333 }
3334 if (N >= MAX_RECENT_TASKS) {
3335 mRecentTasks.remove(N-1);
3336 }
3337 mRecentTasks.add(0, task);
3338 }
3339
3340 public void setRequestedOrientation(IBinder token,
3341 int requestedOrientation) {
3342 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003343 ActivityRecord r = mMainStack.isInStackLocked(token);
3344 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 return;
3346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08003348 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07003350 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08003351 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 if (config != null) {
3353 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08003354 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003355 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 }
3357 }
3358 Binder.restoreCallingIdentity(origId);
3359 }
3360 }
3361
3362 public int getRequestedOrientation(IBinder token) {
3363 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003364 ActivityRecord r = mMainStack.isInStackLocked(token);
3365 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3367 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003368 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 }
3370 }
3371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 /**
3373 * This is the internal entry point for handling Activity.finish().
3374 *
3375 * @param token The Binder token referencing the Activity we want to finish.
3376 * @param resultCode Result code, if any, from this Activity.
3377 * @param resultData Result data (Intent), if any, from this Activity.
3378 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11003379 * @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 -08003380 */
3381 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
3382 // Refuse possible leaked file descriptors
3383 if (resultData != null && resultData.hasFileDescriptors() == true) {
3384 throw new IllegalArgumentException("File descriptors passed in Intent");
3385 }
3386
3387 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003388 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003390 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 if (next != null) {
3392 // ask watcher if this is allowed
3393 boolean resumeOK = true;
3394 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003395 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003397 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 }
3399
3400 if (!resumeOK) {
3401 return false;
3402 }
3403 }
3404 }
3405 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003406 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 resultData, "app-request");
3408 Binder.restoreCallingIdentity(origId);
3409 return res;
3410 }
3411 }
3412
Dianne Hackborn860755f2010-06-03 18:47:52 -07003413 public final void finishHeavyWeightApp() {
3414 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3415 != PackageManager.PERMISSION_GRANTED) {
3416 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
3417 + Binder.getCallingPid()
3418 + ", uid=" + Binder.getCallingUid()
3419 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3420 Slog.w(TAG, msg);
3421 throw new SecurityException(msg);
3422 }
3423
3424 synchronized(this) {
3425 if (mHeavyWeightProcess == null) {
3426 return;
3427 }
3428
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003429 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07003430 mHeavyWeightProcess.activities);
3431 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003432 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003433 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003434 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003435 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003436 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07003437 null, "finish-heavy");
3438 }
3439 }
3440 }
3441
3442 mHeavyWeightProcess = null;
3443 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3444 }
3445 }
3446
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003447 public void crashApplication(int uid, int initialPid, String packageName,
3448 String message) {
3449 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3450 != PackageManager.PERMISSION_GRANTED) {
3451 String msg = "Permission Denial: crashApplication() from pid="
3452 + Binder.getCallingPid()
3453 + ", uid=" + Binder.getCallingUid()
3454 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3455 Slog.w(TAG, msg);
3456 throw new SecurityException(msg);
3457 }
3458
3459 synchronized(this) {
3460 ProcessRecord proc = null;
3461
3462 // Figure out which process to kill. We don't trust that initialPid
3463 // still has any relation to current pids, so must scan through the
3464 // list.
3465 synchronized (mPidsSelfLocked) {
3466 for (int i=0; i<mPidsSelfLocked.size(); i++) {
3467 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003468 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003469 continue;
3470 }
3471 if (p.pid == initialPid) {
3472 proc = p;
3473 break;
3474 }
3475 for (String str : p.pkgList) {
3476 if (str.equals(packageName)) {
3477 proc = p;
3478 }
3479 }
3480 }
3481 }
3482
3483 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07003484 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003485 + " initialPid=" + initialPid
3486 + " packageName=" + packageName);
3487 return;
3488 }
3489
3490 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07003491 if (proc.pid == Process.myPid()) {
3492 Log.w(TAG, "crashApplication: trying to crash self!");
3493 return;
3494 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003495 long ident = Binder.clearCallingIdentity();
3496 try {
3497 proc.thread.scheduleCrash(message);
3498 } catch (RemoteException e) {
3499 }
3500 Binder.restoreCallingIdentity(ident);
3501 }
3502 }
3503 }
3504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 public final void finishSubActivity(IBinder token, String resultWho,
3506 int requestCode) {
3507 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003508 ActivityRecord self = mMainStack.isInStackLocked(token);
3509 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 return;
3511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512
3513 final long origId = Binder.clearCallingIdentity();
3514
3515 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003516 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3517 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 if (r.resultTo == self && r.requestCode == requestCode) {
3519 if ((r.resultWho == null && resultWho == null) ||
3520 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003521 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003522 Activity.RESULT_CANCELED, null, "request-sub");
3523 }
3524 }
3525 }
3526
3527 Binder.restoreCallingIdentity(origId);
3528 }
3529 }
3530
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003531 public boolean willActivityBeVisible(IBinder token) {
3532 synchronized(this) {
3533 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003534 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3535 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003536 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003537 return true;
3538 }
3539 if (r.fullscreen && !r.finishing) {
3540 return false;
3541 }
3542 }
3543 return true;
3544 }
3545 }
3546
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003547 public void overridePendingTransition(IBinder token, String packageName,
3548 int enterAnim, int exitAnim) {
3549 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003550 ActivityRecord self = mMainStack.isInStackLocked(token);
3551 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003552 return;
3553 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003554
3555 final long origId = Binder.clearCallingIdentity();
3556
3557 if (self.state == ActivityState.RESUMED
3558 || self.state == ActivityState.PAUSING) {
3559 mWindowManager.overridePendingAppTransition(packageName,
3560 enterAnim, exitAnim);
3561 }
3562
3563 Binder.restoreCallingIdentity(origId);
3564 }
3565 }
3566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 * Main function for removing an existing process from the activity manager
3569 * as a result of that process going away. Clears out all connections
3570 * to the process.
3571 */
3572 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003573 boolean restarting, boolean allowRestart) {
3574 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003575 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003576 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 }
3578
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003579 if (mProfileProc == app) {
3580 clearProfilerLocked();
3581 }
3582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583 // Just in case...
Dianne Hackborncbb722e2012-02-07 18:33:49 -08003584 mMainStack.appDiedLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585
3586 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003587 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588
3589 boolean atTop = true;
3590 boolean hasVisibleActivities = false;
3591
3592 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003593 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003594 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 TAG, "Removing app " + app + " from history with " + i + " entries");
3596 while (i > 0) {
3597 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003598 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003599 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3601 if (r.app == app) {
3602 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003603 if (ActivityStack.DEBUG_ADD_REMOVE) {
3604 RuntimeException here = new RuntimeException("here");
3605 here.fillInStackTrace();
3606 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
3607 + ": haveState=" + r.haveState
3608 + " stateNotNeeded=" + r.stateNotNeeded
3609 + " finishing=" + r.finishing
3610 + " state=" + r.state, here);
3611 }
3612 if (!r.finishing) {
3613 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08003614 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3615 System.identityHashCode(r),
3616 r.task.taskId, r.shortComponentName,
3617 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003618 }
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003619 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003620 mMainStack.mHistory.remove(i);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003621 r.takeFromHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08003622 mWindowManager.removeAppToken(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003624 mMainStack.validateAppTokensLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003626 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627
3628 } else {
3629 // We have the current state for this activity, so
3630 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003631 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 TAG, "Keeping entry, setting app to null");
3633 if (r.visible) {
3634 hasVisibleActivities = true;
3635 }
3636 r.app = null;
3637 r.nowVisible = false;
3638 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003639 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
3640 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 r.icicle = null;
3642 }
3643 }
3644
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003645 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003646 }
3647 atTop = false;
3648 }
3649
3650 app.activities.clear();
3651
3652 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003653 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 + " running instrumentation " + app.instrumentationClass);
3655 Bundle info = new Bundle();
3656 info.putString("shortMsg", "Process crashed.");
3657 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3658 }
3659
3660 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003661 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 // If there was nothing to resume, and we are not already
3663 // restarting this process, but there is a visible activity that
3664 // is hosted by the process... then make sure all visible
3665 // activities are running, taking care of restarting this
3666 // process.
3667 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003668 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 }
3670 }
3671 }
3672 }
3673
3674 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3675 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003677 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3678 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3680 return i;
3681 }
3682 }
3683 return -1;
3684 }
3685
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003686 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 IApplicationThread thread) {
3688 if (thread == null) {
3689 return null;
3690 }
3691
3692 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003693 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 }
3695
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003696 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 IApplicationThread thread) {
3698
3699 mProcDeaths[0]++;
3700
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003701 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3702 synchronized (stats) {
3703 stats.noteProcessDiedLocked(app.info.uid, pid);
3704 }
3705
Magnus Edlund7bb25812010-02-24 15:45:06 +01003706 // Clean up already done if the process has been re-started.
3707 if (app.pid == pid && app.thread != null &&
3708 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003709 if (!app.killedBackground) {
3710 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3711 + ") has died.");
3712 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08003713 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003714 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 TAG, "Dying app: " + app + ", pid: " + pid
3716 + ", thread: " + thread.asBinder());
3717 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003718 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719
3720 if (doLowMem) {
3721 // If there are no longer any background processes running,
3722 // and the app that died was not running instrumentation,
3723 // then tell everyone we are now low on memory.
3724 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003725 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3726 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003727 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 haveBg = true;
3729 break;
3730 }
3731 }
3732
3733 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003734 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003735 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003736 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3737 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003738 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003739 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3740 // The low memory report is overriding any current
3741 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003742 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003743 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003744 rec.lastRequestedGc = 0;
3745 } else {
3746 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003748 rec.reportLowMemory = true;
3749 rec.lastLowMemory = now;
3750 mProcessesToGc.remove(rec);
3751 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 }
3753 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003754 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003755 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 }
3757 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003758 } else if (app.pid != pid) {
3759 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003760 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003761 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003762 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003763 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003764 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 + thread.asBinder());
3766 }
3767 }
3768
Dan Egnor42471dd2010-01-07 17:25:22 -08003769 /**
3770 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003771 * @param clearTraces causes the dump file to be erased prior to the new
3772 * traces being written, if true; when false, the new traces will be
3773 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003774 * @param firstPids of dalvik VM processes to dump stack traces for first
3775 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08003776 * @return file containing stack traces, or null if no dump file is configured
3777 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003778 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
3779 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003780 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3781 if (tracesPath == null || tracesPath.length() == 0) {
3782 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003784
3785 File tracesFile = new File(tracesPath);
3786 try {
3787 File tracesDir = tracesFile.getParentFile();
3788 if (!tracesDir.exists()) tracesFile.mkdirs();
3789 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3790
Christopher Tate6ee412d2010-05-28 12:01:56 -07003791 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003792 tracesFile.createNewFile();
3793 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3794 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003795 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003796 return null;
3797 }
3798
3799 // Use a FileObserver to detect when traces finish writing.
3800 // The order of traces is considered important to maintain for legibility.
3801 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3802 public synchronized void onEvent(int event, String path) { notify(); }
3803 };
3804
3805 try {
3806 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003807
3808 // First collect all of the stacks of the most important pids.
3809 try {
3810 int num = firstPids.size();
3811 for (int i = 0; i < num; i++) {
3812 synchronized (observer) {
3813 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3814 observer.wait(200); // Wait for write-close, give up after 200msec
3815 }
3816 }
3817 } catch (InterruptedException e) {
3818 Log.wtf(TAG, e);
3819 }
3820
3821 // Next measure CPU usage.
3822 if (processStats != null) {
3823 processStats.init();
3824 System.gc();
3825 processStats.update();
3826 try {
3827 synchronized (processStats) {
3828 processStats.wait(500); // measure over 1/2 second.
3829 }
3830 } catch (InterruptedException e) {
3831 }
3832 processStats.update();
3833
3834 // We'll take the stack crawls of just the top apps using CPU.
3835 final int N = processStats.countWorkingStats();
3836 int numProcs = 0;
3837 for (int i=0; i<N && numProcs<5; i++) {
3838 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3839 if (lastPids.indexOfKey(stats.pid) >= 0) {
3840 numProcs++;
3841 try {
3842 synchronized (observer) {
3843 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3844 observer.wait(200); // Wait for write-close, give up after 200msec
3845 }
3846 } catch (InterruptedException e) {
3847 Log.wtf(TAG, e);
3848 }
3849
3850 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003851 }
3852 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003853
3854 return tracesFile;
3855
Dan Egnor42471dd2010-01-07 17:25:22 -08003856 } finally {
3857 observer.stopWatching();
3858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 }
3860
Jeff Brown4d94a762010-09-23 11:33:28 -07003861 private final class AppNotResponding implements Runnable {
3862 private final ProcessRecord mApp;
3863 private final String mAnnotation;
3864
3865 public AppNotResponding(ProcessRecord app, String annotation) {
3866 mApp = app;
3867 mAnnotation = annotation;
3868 }
3869
3870 @Override
3871 public void run() {
3872 appNotResponding(mApp, null, null, mAnnotation);
3873 }
3874 }
3875
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003876 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3877 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003878 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3879 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3880
Dianne Hackborn287952c2010-09-22 22:34:31 -07003881 if (mController != null) {
3882 try {
3883 // 0 == continue, -1 = kill process immediately
3884 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3885 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3886 } catch (RemoteException e) {
3887 mController = null;
3888 }
3889 }
3890
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003891 long anrTime = SystemClock.uptimeMillis();
3892 if (MONITOR_CPU_USAGE) {
3893 updateCpuStatsNow();
3894 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003895
3896 synchronized (this) {
3897 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3898 if (mShuttingDown) {
3899 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3900 return;
3901 } else if (app.notResponding) {
3902 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3903 return;
3904 } else if (app.crashing) {
3905 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3906 return;
3907 }
3908
3909 // In case we come through here for the same app before completing
3910 // this one, mark as anring now so we will bail out.
3911 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003912
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003913 // Log the ANR to the event log.
3914 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3915 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003916
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003917 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003918 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003919
3920 int parentPid = app.pid;
3921 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003922 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003923
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003924 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003925
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003926 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3927 ProcessRecord r = mLruProcesses.get(i);
3928 if (r != null && r.thread != null) {
3929 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003930 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3931 if (r.persistent) {
3932 firstPids.add(pid);
3933 } else {
3934 lastPids.put(pid, Boolean.TRUE);
3935 }
3936 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 }
3939 }
3940
Dan Egnor42471dd2010-01-07 17:25:22 -08003941 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003942 StringBuilder info = mStringBuilder;
3943 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003944 info.append("ANR in ").append(app.processName);
3945 if (activity != null && activity.shortComponentName != null) {
3946 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003947 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003948 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003950 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003952 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003953 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955
Dianne Hackborn287952c2010-09-22 22:34:31 -07003956 final ProcessStats processStats = new ProcessStats(true);
3957
3958 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3959
Dan Egnor42471dd2010-01-07 17:25:22 -08003960 String cpuInfo = null;
3961 if (MONITOR_CPU_USAGE) {
3962 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003963 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003964 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003965 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003966 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003967 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 }
3969
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003970 info.append(processStats.printCurrentState(anrTime));
3971
Joe Onorato8a9b2202010-02-26 18:56:32 -08003972 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003973 if (tracesFile == null) {
3974 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3975 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3976 }
3977
Jeff Sharkeya353d262011-10-28 11:12:06 -07003978 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3979 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003980
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003981 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003983 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3984 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003986 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3987 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 }
3989 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003990 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 }
3992 }
3993
Dan Egnor42471dd2010-01-07 17:25:22 -08003994 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3995 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3996 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003997
3998 synchronized (this) {
3999 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004000 Slog.w(TAG, "Killing " + app + ": background ANR");
4001 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
4002 app.processName, app.setAdj, "background ANR");
4003 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07004004 return;
4005 }
4006
4007 // Set the app's notResponding state, and look up the errorReportReceiver
4008 makeAppNotRespondingLocked(app,
4009 activity != null ? activity.shortComponentName : null,
4010 annotation != null ? "ANR " + annotation : "ANR",
4011 info.toString());
4012
4013 // Bring up the infamous App Not Responding dialog
4014 Message msg = Message.obtain();
4015 HashMap map = new HashMap();
4016 msg.what = SHOW_NOT_RESPONDING_MSG;
4017 msg.obj = map;
4018 map.put("app", app);
4019 if (activity != null) {
4020 map.put("activity", activity);
4021 }
4022
4023 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08004024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 }
4026
Dianne Hackborn0dad3642010-09-09 21:25:35 -07004027 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
4028 if (!mLaunchWarningShown) {
4029 mLaunchWarningShown = true;
4030 mHandler.post(new Runnable() {
4031 @Override
4032 public void run() {
4033 synchronized (ActivityManagerService.this) {
4034 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
4035 d.show();
4036 mHandler.postDelayed(new Runnable() {
4037 @Override
4038 public void run() {
4039 synchronized (ActivityManagerService.this) {
4040 d.dismiss();
4041 mLaunchWarningShown = false;
4042 }
4043 }
4044 }, 4000);
4045 }
4046 }
4047 });
4048 }
4049 }
4050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07004052 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004053 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 int uid = Binder.getCallingUid();
4055 int pid = Binder.getCallingPid();
4056 long callingId = Binder.clearCallingIdentity();
4057 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004058 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 int pkgUid = -1;
4060 synchronized(this) {
4061 try {
4062 pkgUid = pm.getPackageUid(packageName);
4063 } catch (RemoteException e) {
4064 }
4065 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004066 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 return false;
4068 }
4069 if (uid == pkgUid || checkComponentPermission(
4070 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004071 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08004073 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 } else {
4075 throw new SecurityException(pid+" does not have permission:"+
4076 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
4077 "for process:"+packageName);
4078 }
4079 }
4080
4081 try {
4082 //clear application user data
4083 pm.clearApplicationUserData(packageName, observer);
4084 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
4085 Uri.fromParts("package", packageName, null));
4086 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004087 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07004088 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 } catch (RemoteException e) {
4090 }
4091 } finally {
4092 Binder.restoreCallingIdentity(callingId);
4093 }
4094 return true;
4095 }
4096
Dianne Hackborn03abb812010-01-04 18:43:19 -08004097 public void killBackgroundProcesses(final String packageName) {
4098 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4099 != PackageManager.PERMISSION_GRANTED &&
4100 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
4101 != PackageManager.PERMISSION_GRANTED) {
4102 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 + Binder.getCallingPid()
4104 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08004105 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004106 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 throw new SecurityException(msg);
4108 }
4109
4110 long callingId = Binder.clearCallingIdentity();
4111 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004112 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 int pkgUid = -1;
4114 synchronized(this) {
4115 try {
4116 pkgUid = pm.getPackageUid(packageName);
4117 } catch (RemoteException e) {
4118 }
4119 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004120 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 return;
4122 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004123 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004124 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
4125 }
4126 } finally {
4127 Binder.restoreCallingIdentity(callingId);
4128 }
4129 }
4130
4131 public void killAllBackgroundProcesses() {
4132 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4133 != PackageManager.PERMISSION_GRANTED) {
4134 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
4135 + Binder.getCallingPid()
4136 + ", uid=" + Binder.getCallingUid()
4137 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4138 Slog.w(TAG, msg);
4139 throw new SecurityException(msg);
4140 }
4141
4142 long callingId = Binder.clearCallingIdentity();
4143 try {
4144 synchronized(this) {
4145 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
4146 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
4147 final int NA = apps.size();
4148 for (int ia=0; ia<NA; ia++) {
4149 ProcessRecord app = apps.valueAt(ia);
4150 if (app.persistent) {
4151 // we don't kill persistent processes
4152 continue;
4153 }
4154 if (app.removed) {
4155 procs.add(app);
4156 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
4157 app.removed = true;
4158 procs.add(app);
4159 }
4160 }
4161 }
4162
4163 int N = procs.size();
4164 for (int i=0; i<N; i++) {
4165 removeProcessLocked(procs.get(i), false, true, "kill all background");
4166 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004167 }
4168 } finally {
4169 Binder.restoreCallingIdentity(callingId);
4170 }
4171 }
4172
4173 public void forceStopPackage(final String packageName) {
4174 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4175 != PackageManager.PERMISSION_GRANTED) {
4176 String msg = "Permission Denial: forceStopPackage() from pid="
4177 + Binder.getCallingPid()
4178 + ", uid=" + Binder.getCallingUid()
4179 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004180 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004181 throw new SecurityException(msg);
4182 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004183 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08004184 long callingId = Binder.clearCallingIdentity();
4185 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004186 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08004187 int pkgUid = -1;
4188 synchronized(this) {
4189 try {
4190 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004191 // Convert the uid to the one for the calling user
4192 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004193 } catch (RemoteException e) {
4194 }
4195 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004196 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004197 return;
4198 }
4199 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08004200 try {
4201 pm.setPackageStoppedState(packageName, true);
4202 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08004203 } catch (IllegalArgumentException e) {
4204 Slog.w(TAG, "Failed trying to unstop package "
4205 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08004206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 }
4208 } finally {
4209 Binder.restoreCallingIdentity(callingId);
4210 }
4211 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004212
4213 /*
4214 * The pkg name and uid have to be specified.
4215 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
4216 */
4217 public void killApplicationWithUid(String pkg, int uid) {
4218 if (pkg == null) {
4219 return;
4220 }
4221 // Make sure the uid is valid.
4222 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004223 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004224 return;
4225 }
4226 int callerUid = Binder.getCallingUid();
4227 // Only the system server can kill an application
4228 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07004229 // Post an aysnc message to kill the application
4230 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
4231 msg.arg1 = uid;
4232 msg.arg2 = 0;
4233 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07004234 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004235 } else {
4236 throw new SecurityException(callerUid + " cannot kill pkg: " +
4237 pkg);
4238 }
4239 }
4240
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004241 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004242 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004243 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004244 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004245 if (reason != null) {
4246 intent.putExtra("reason", reason);
4247 }
4248
4249 final int uid = Binder.getCallingUid();
4250 final long origId = Binder.clearCallingIdentity();
4251 synchronized (this) {
4252 int i = mWatchers.beginBroadcast();
4253 while (i > 0) {
4254 i--;
4255 IActivityWatcher w = mWatchers.getBroadcastItem(i);
4256 if (w != null) {
4257 try {
4258 w.closingSystemDialogs(reason);
4259 } catch (RemoteException e) {
4260 }
4261 }
4262 }
4263 mWatchers.finishBroadcast();
4264
Dianne Hackbornffa42482009-09-23 22:20:11 -07004265 mWindowManager.closeSystemDialogs(reason);
4266
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004267 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
4268 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07004269 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004270 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07004271 Activity.RESULT_CANCELED, null, "close-sys");
4272 }
4273 }
4274
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004275 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07004276 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004277 }
4278 Binder.restoreCallingIdentity(origId);
4279 }
4280
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004281 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004282 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004283 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004284 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
4285 for (int i=pids.length-1; i>=0; i--) {
4286 infos[i] = new Debug.MemoryInfo();
4287 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004288 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004289 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004290 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07004291
Dianne Hackbornb437e092011-08-05 17:50:29 -07004292 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004293 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07004294 long[] pss = new long[pids.length];
4295 for (int i=pids.length-1; i>=0; i--) {
4296 pss[i] = Debug.getPss(pids[i]);
4297 }
4298 return pss;
4299 }
4300
Christopher Tate5e1ab332009-09-01 20:32:49 -07004301 public void killApplicationProcess(String processName, int uid) {
4302 if (processName == null) {
4303 return;
4304 }
4305
4306 int callerUid = Binder.getCallingUid();
4307 // Only the system server can kill an application
4308 if (callerUid == Process.SYSTEM_UID) {
4309 synchronized (this) {
4310 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07004311 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07004312 try {
4313 app.thread.scheduleSuicide();
4314 } catch (RemoteException e) {
4315 // If the other end already died, then our work here is done.
4316 }
4317 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004318 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07004319 + processName + " / " + uid);
4320 }
4321 }
4322 } else {
4323 throw new SecurityException(callerUid + " cannot kill app process: " +
4324 processName);
4325 }
4326 }
4327
Dianne Hackborn03abb812010-01-04 18:43:19 -08004328 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004329 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
4331 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004332 if (!mProcessesReady) {
4333 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 intent.putExtra(Intent.EXTRA_UID, uid);
4336 broadcastIntentLocked(null, null, intent,
4337 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07004338 false, false,
4339 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340 }
4341
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004342 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07004343 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004344 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08004345 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004346
Dianne Hackborn03abb812010-01-04 18:43:19 -08004347 // Remove all processes this package may have touched: all with the
4348 // same UID (except for the system or root user), and all whose name
4349 // matches the package name.
4350 final String procNamePrefix = packageName + ":";
4351 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
4352 final int NA = apps.size();
4353 for (int ia=0; ia<NA; ia++) {
4354 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07004355 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07004356 // we don't kill persistent processes
4357 continue;
4358 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004359 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004360 if (doit) {
4361 procs.add(app);
4362 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004363 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
4364 || app.processName.equals(packageName)
4365 || app.processName.startsWith(procNamePrefix)) {
4366 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004367 if (!doit) {
4368 return true;
4369 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004370 app.removed = true;
4371 procs.add(app);
4372 }
4373 }
4374 }
4375 }
4376
4377 int N = procs.size();
4378 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004379 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004380 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004381 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08004382 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004383
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004384 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07004385 boolean callerWillRestart, boolean purgeCache, boolean doit,
4386 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004387 int i;
4388 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 if (uid < 0) {
4391 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004392 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 } catch (RemoteException e) {
4394 }
4395 }
4396
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004397 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004398 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004399
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004400 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
4401 while (badApps.hasNext()) {
4402 SparseArray<Long> ba = badApps.next();
4403 if (ba.get(uid) != null) {
4404 badApps.remove();
4405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004406 }
4407 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004408
4409 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004410 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004412 TaskRecord lastTask = null;
4413 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004414 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004415 final boolean samePackage = r.packageName.equals(name);
4416 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07004417 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004418 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07004419 if (r.finishing) {
4420 // If this activity is just finishing, then it is not
4421 // interesting as far as something to stop.
4422 continue;
4423 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004424 return true;
4425 }
4426 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004427 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004428 if (samePackage) {
4429 if (r.app != null) {
4430 r.app.removed = true;
4431 }
4432 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004433 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004434 lastTask = r.task;
4435 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
4436 null, "force-stop")) {
4437 i--;
4438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004439 }
4440 }
4441
4442 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07004443 int userId = UserId.getUserId(uid);
4444 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07004445 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07004446 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004447 if (!doit) {
4448 return true;
4449 }
4450 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004451 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 if (service.app != null) {
4453 service.app.removed = true;
4454 }
4455 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004456 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004457 services.add(service);
4458 }
4459 }
4460
4461 N = services.size();
4462 for (i=0; i<N; i++) {
4463 bringDownServiceLocked(services.get(i), true);
4464 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004465
4466 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
4467 for (ContentProviderRecord provider : mProvidersByClass.values()) {
4468 if (provider.info.packageName.equals(name)
4469 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
4470 if (!doit) {
4471 return true;
4472 }
4473 didSomething = true;
4474 providers.add(provider);
4475 }
4476 }
4477
4478 N = providers.size();
4479 for (i=0; i<N; i++) {
4480 removeDyingProviderLocked(null, providers.get(i));
4481 }
4482
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004483 if (doit) {
4484 if (purgeCache) {
4485 AttributeCache ac = AttributeCache.instance();
4486 if (ac != null) {
4487 ac.removePackage(name);
4488 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004489 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004490 if (mBooted) {
4491 mMainStack.resumeTopActivityLocked(null);
4492 mMainStack.scheduleIdleLocked();
4493 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004494 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004495
4496 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 }
4498
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004499 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004500 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004502 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004503 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004504 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 + "/" + uid + ")");
4506
4507 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004508 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004509 if (mHeavyWeightProcess == app) {
4510 mHeavyWeightProcess = null;
4511 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
4512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 boolean needRestart = false;
4514 if (app.pid > 0 && app.pid != MY_PID) {
4515 int pid = app.pid;
4516 synchronized (mPidsSelfLocked) {
4517 mPidsSelfLocked.remove(pid);
4518 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4519 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004520 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004521 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004522 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004523 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004524
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004525 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004527 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004528 } else {
4529 needRestart = true;
4530 }
4531 }
4532 } else {
4533 mRemovedProcesses.add(app);
4534 }
4535
4536 return needRestart;
4537 }
4538
4539 private final void processStartTimedOutLocked(ProcessRecord app) {
4540 final int pid = app.pid;
4541 boolean gone = false;
4542 synchronized (mPidsSelfLocked) {
4543 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4544 if (knownApp != null && knownApp.thread == null) {
4545 mPidsSelfLocked.remove(pid);
4546 gone = true;
4547 }
4548 }
4549
4550 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004551 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004552 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004553 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004554 mProcessNames.remove(app.processName, app.uid);
4555 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004556 if (mHeavyWeightProcess == app) {
4557 mHeavyWeightProcess = null;
4558 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
4559 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004560 // Take care of any launching providers waiting for this process.
4561 checkAppInLaunchingProvidersLocked(app, true);
4562 // Take care of any services that are waiting for the process.
4563 for (int i=0; i<mPendingServices.size(); i++) {
4564 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004565 if ((app.uid == sr.appInfo.uid
4566 && app.processName.equals(sr.processName))
4567 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004568 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004569 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004570 mPendingServices.remove(i);
4571 i--;
4572 bringDownServiceLocked(sr, true);
4573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004574 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004575 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
4576 app.processName, app.setAdj, "start timeout");
4577 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004578 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004579 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004580 try {
4581 IBackupManager bm = IBackupManager.Stub.asInterface(
4582 ServiceManager.getService(Context.BACKUP_SERVICE));
4583 bm.agentDisconnected(app.info.packageName);
4584 } catch (RemoteException e) {
4585 // Can't happen; the backup manager is local
4586 }
4587 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004588 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004589 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004590 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004593 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 }
4595 }
4596
4597 private final boolean attachApplicationLocked(IApplicationThread thread,
4598 int pid) {
4599
4600 // Find the application record that is being attached... either via
4601 // the pid if we are running in multiple processes, or just pull the
4602 // next app record if we are emulating process with anonymous threads.
4603 ProcessRecord app;
4604 if (pid != MY_PID && pid >= 0) {
4605 synchronized (mPidsSelfLocked) {
4606 app = mPidsSelfLocked.get(pid);
4607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 } else {
4609 app = null;
4610 }
4611
4612 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004613 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004615 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004617 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004618 } else {
4619 try {
4620 thread.scheduleExit();
4621 } catch (Exception e) {
4622 // Ignore exceptions.
4623 }
4624 }
4625 return false;
4626 }
4627
4628 // If this application record is still attached to a previous
4629 // process, clean it up now.
4630 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004631 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 }
4633
4634 // Tell the process all about itself.
4635
Joe Onorato8a9b2202010-02-26 18:56:32 -08004636 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 TAG, "Binding process pid " + pid + " to record " + app);
4638
4639 String processName = app.processName;
4640 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004641 AppDeathRecipient adr = new AppDeathRecipient(
4642 app, pid, thread);
4643 thread.asBinder().linkToDeath(adr, 0);
4644 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004645 } catch (RemoteException e) {
4646 app.resetPackageList();
4647 startProcessLocked(app, "link fail", processName);
4648 return false;
4649 }
4650
Doug Zongker2bec3d42009-12-04 12:52:44 -08004651 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004652
4653 app.thread = thread;
4654 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004655 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4656 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 app.forcingToForeground = null;
4658 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004659 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004660 app.debugging = false;
4661
4662 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4663
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004664 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004665 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004666
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004667 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004668 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004669 }
4670
Joe Onorato8a9b2202010-02-26 18:56:32 -08004671 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004672 TAG, "New app record " + app
4673 + " thread=" + thread.asBinder() + " pid=" + pid);
4674 try {
4675 int testMode = IApplicationThread.DEBUG_OFF;
4676 if (mDebugApp != null && mDebugApp.equals(processName)) {
4677 testMode = mWaitForDebugger
4678 ? IApplicationThread.DEBUG_WAIT
4679 : IApplicationThread.DEBUG_ON;
4680 app.debugging = true;
4681 if (mDebugTransient) {
4682 mDebugApp = mOrigDebugApp;
4683 mWaitForDebugger = mOrigWaitForDebugger;
4684 }
4685 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004686 String profileFile = app.instrumentationProfileFile;
4687 ParcelFileDescriptor profileFd = null;
4688 boolean profileAutoStop = false;
4689 if (mProfileApp != null && mProfileApp.equals(processName)) {
4690 mProfileProc = app;
4691 profileFile = mProfileFile;
4692 profileFd = mProfileFd;
4693 profileAutoStop = mAutoStopProfiler;
4694 }
4695
Christopher Tate181fafa2009-05-14 11:12:14 -07004696 // If the app is being launched for restore or full backup, set it up specially
4697 boolean isRestrictedBackupMode = false;
4698 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4699 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004700 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004701 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4702 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004703
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004704 ensurePackageDexOpt(app.instrumentationInfo != null
4705 ? app.instrumentationInfo.packageName
4706 : app.info.packageName);
4707 if (app.instrumentationClass != null) {
4708 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004709 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004710 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004711 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004712 ApplicationInfo appInfo = app.instrumentationInfo != null
4713 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004714 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004715 if (profileFd != null) {
4716 profileFd = profileFd.dup();
4717 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004718 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004719 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004720 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn5d927c22011-09-02 12:22:18 -07004721 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004722 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004723 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004724 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004725 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004726 } catch (Exception e) {
4727 // todo: Yikes! What should we do? For now we will try to
4728 // start another process, but that could easily get us in
4729 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004730 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004731
4732 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004733 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004734 startProcessLocked(app, "bind fail", processName);
4735 return false;
4736 }
4737
4738 // Remove this record from the list of starting applications.
4739 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004740 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4741 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 mProcessesOnHold.remove(app);
4743
4744 boolean badApp = false;
4745 boolean didSomething = false;
4746
4747 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004748 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004749 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004750 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004751 && processName.equals(hr.processName)) {
4752 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004753 if (mHeadless) {
4754 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4755 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004756 didSomething = true;
4757 }
4758 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004759 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 + hr.intent.getComponent().flattenToShortString(), e);
4761 badApp = true;
4762 }
4763 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004764 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004765 }
4766 }
4767
4768 // Find any services that should be running in this process...
4769 if (!badApp && mPendingServices.size() > 0) {
4770 ServiceRecord sr = null;
4771 try {
4772 for (int i=0; i<mPendingServices.size(); i++) {
4773 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004774 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4775 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 continue;
4777 }
4778
4779 mPendingServices.remove(i);
4780 i--;
4781 realStartServiceLocked(sr, app);
4782 didSomething = true;
4783 }
4784 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004785 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004786 + sr.shortName, e);
4787 badApp = true;
4788 }
4789 }
4790
Christopher Tatef46723b2012-01-26 14:19:24 -08004791 // Check if a next-broadcast receiver is in this process...
4792 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004793 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004794 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004795 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004796 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004797 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004798 }
4799 }
4800
Christopher Tate181fafa2009-05-14 11:12:14 -07004801 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004802 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004803 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004804 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004805 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004806 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4807 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4808 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004809 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004810 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004811 e.printStackTrace();
4812 }
4813 }
4814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004815 if (badApp) {
4816 // todo: Also need to kill application to deal with all
4817 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004818 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004819 return false;
4820 }
4821
4822 if (!didSomething) {
4823 updateOomAdjLocked();
4824 }
4825
4826 return true;
4827 }
4828
4829 public final void attachApplication(IApplicationThread thread) {
4830 synchronized (this) {
4831 int callingPid = Binder.getCallingPid();
4832 final long origId = Binder.clearCallingIdentity();
4833 attachApplicationLocked(thread, callingPid);
4834 Binder.restoreCallingIdentity(origId);
4835 }
4836 }
4837
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004838 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004840 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4841 if (stopProfiling) {
4842 synchronized (this) {
4843 if (mProfileProc == r.app) {
4844 if (mProfileFd != null) {
4845 try {
4846 mProfileFd.close();
4847 } catch (IOException e) {
4848 }
4849 clearProfilerLocked();
4850 }
4851 }
4852 }
4853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004854 Binder.restoreCallingIdentity(origId);
4855 }
4856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004857 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004858 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004859 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004860 mWindowManager.enableScreenAfterBoot();
4861 }
4862
Dianne Hackborn661cd522011-08-22 00:26:20 -07004863 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004864 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004865 mWindowManager.showBootMessage(msg, always);
4866 }
4867
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004868 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004869 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004870 synchronized (this) {
4871 mMainStack.dismissKeyguardOnNextActivityLocked();
4872 }
4873 }
4874
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004875 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004876 IntentFilter pkgFilter = new IntentFilter();
4877 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4878 pkgFilter.addDataScheme("package");
4879 mContext.registerReceiver(new BroadcastReceiver() {
4880 @Override
4881 public void onReceive(Context context, Intent intent) {
4882 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4883 if (pkgs != null) {
4884 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004885 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004886 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004887 setResultCode(Activity.RESULT_OK);
4888 return;
4889 }
4890 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004891 }
4892 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004893 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004894 }, pkgFilter);
4895
4896 synchronized (this) {
4897 // Ensure that any processes we had put on hold are now started
4898 // up.
4899 final int NP = mProcessesOnHold.size();
4900 if (NP > 0) {
4901 ArrayList<ProcessRecord> procs =
4902 new ArrayList<ProcessRecord>(mProcessesOnHold);
4903 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004904 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4905 + procs.get(ip));
4906 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004907 }
4908 }
4909
4910 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004911 // Start looking for apps that are abusing wake locks.
4912 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004913 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004914 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004915 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004916 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004917 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004918 broadcastIntentLocked(null, null,
4919 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4920 null, null, 0, null, null,
4921 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004922 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004923 }
4924 }
4925 }
4926
4927 final void ensureBootCompleted() {
4928 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004929 boolean enableScreen;
4930 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004931 booting = mBooting;
4932 mBooting = false;
Mike Lockwooda8f767a2011-08-31 14:32:37 -04004933 enableScreen = !mBooted && !mHeadless;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004934 mBooted = true;
4935 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004936
4937 if (booting) {
4938 finishBooting();
4939 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004940
4941 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004942 enableScreenAfterBoot();
4943 }
4944 }
4945
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004946 public final void activityPaused(IBinder token) {
4947 final long origId = Binder.clearCallingIdentity();
4948 mMainStack.activityPaused(token, false);
4949 Binder.restoreCallingIdentity(origId);
4950 }
4951
4952 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4953 CharSequence description) {
4954 if (localLOGV) Slog.v(
4955 TAG, "Activity stopped: token=" + token);
4956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 // Refuse possible leaked file descriptors
4958 if (icicle != null && icicle.hasFileDescriptors()) {
4959 throw new IllegalArgumentException("File descriptors passed in Bundle");
4960 }
4961
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004962 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963
4964 final long origId = Binder.clearCallingIdentity();
4965
4966 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004967 r = mMainStack.isInStackLocked(token);
4968 if (r != null) {
4969 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004970 }
4971 }
4972
4973 if (r != null) {
4974 sendPendingThumbnail(r, null, null, null, false);
4975 }
4976
4977 trimApplications();
4978
4979 Binder.restoreCallingIdentity(origId);
4980 }
4981
4982 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004983 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004984 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004985 }
4986
4987 public String getCallingPackage(IBinder token) {
4988 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004989 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004990 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004991 }
4992 }
4993
4994 public ComponentName getCallingActivity(IBinder token) {
4995 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004996 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004997 return r != null ? r.intent.getComponent() : null;
4998 }
4999 }
5000
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005001 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005002 ActivityRecord r = mMainStack.isInStackLocked(token);
5003 if (r == null) {
5004 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005005 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005006 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005007 }
5008
5009 public ComponentName getActivityClassForToken(IBinder token) {
5010 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005011 ActivityRecord r = mMainStack.isInStackLocked(token);
5012 if (r == null) {
5013 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005014 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005015 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 }
5017 }
5018
5019 public String getPackageForToken(IBinder token) {
5020 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005021 ActivityRecord r = mMainStack.isInStackLocked(token);
5022 if (r == null) {
5023 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005024 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005025 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005026 }
5027 }
5028
5029 public IIntentSender getIntentSender(int type,
5030 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005031 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005032 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005033 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005034 if (intents != null) {
5035 if (intents.length < 1) {
5036 throw new IllegalArgumentException("Intents array length must be >= 1");
5037 }
5038 for (int i=0; i<intents.length; i++) {
5039 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07005040 if (intent != null) {
5041 if (intent.hasFileDescriptors()) {
5042 throw new IllegalArgumentException("File descriptors passed in Intent");
5043 }
5044 if (type == INTENT_SENDER_BROADCAST &&
5045 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
5046 throw new IllegalArgumentException(
5047 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
5048 }
5049 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005050 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005051 }
5052 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005053 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005054 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005055 }
5056 }
5057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005058 synchronized(this) {
5059 int callingUid = Binder.getCallingUid();
5060 try {
Jeff Brown10e89712011-07-08 18:52:57 -07005061 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005062 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005063 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07005064 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 String msg = "Permission Denial: getIntentSender() from pid="
5066 + Binder.getCallingPid()
5067 + ", uid=" + Binder.getCallingUid()
5068 + ", (need uid=" + uid + ")"
5069 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005070 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005071 throw new SecurityException(msg);
5072 }
5073 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005074
Amith Yamasani742a6712011-05-04 14:49:28 -07005075 if (DEBUG_MU)
5076 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
5077 + Binder.getOrigCallingUid());
5078 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005079 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07005080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005081 } catch (RemoteException e) {
5082 throw new SecurityException(e);
5083 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005084 }
5085 }
5086
5087 IIntentSender getIntentSenderLocked(int type,
5088 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005089 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005090 if (DEBUG_MU)
5091 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005092 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07005093 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005094 activity = mMainStack.isInStackLocked(token);
5095 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005096 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005098 if (activity.finishing) {
5099 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005100 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005101 }
5102
5103 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
5104 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
5105 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
5106 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
5107 |PendingIntent.FLAG_UPDATE_CURRENT);
5108
5109 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
5110 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005111 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07005112 WeakReference<PendingIntentRecord> ref;
5113 ref = mIntentSenderRecords.get(key);
5114 PendingIntentRecord rec = ref != null ? ref.get() : null;
5115 if (rec != null) {
5116 if (!cancelCurrent) {
5117 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005118 if (rec.key.requestIntent != null) {
5119 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
5120 }
5121 if (intents != null) {
5122 intents[intents.length-1] = rec.key.requestIntent;
5123 rec.key.allIntents = intents;
5124 rec.key.allResolvedTypes = resolvedTypes;
5125 } else {
5126 rec.key.allIntents = null;
5127 rec.key.allResolvedTypes = null;
5128 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 return rec;
5131 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005132 rec.canceled = true;
5133 mIntentSenderRecords.remove(key);
5134 }
5135 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 return rec;
5137 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005138 rec = new PendingIntentRecord(this, key, callingUid);
5139 mIntentSenderRecords.put(key, rec.ref);
5140 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
5141 if (activity.pendingResults == null) {
5142 activity.pendingResults
5143 = new HashSet<WeakReference<PendingIntentRecord>>();
5144 }
5145 activity.pendingResults.add(rec.ref);
5146 }
5147 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 }
5149
5150 public void cancelIntentSender(IIntentSender sender) {
5151 if (!(sender instanceof PendingIntentRecord)) {
5152 return;
5153 }
5154 synchronized(this) {
5155 PendingIntentRecord rec = (PendingIntentRecord)sender;
5156 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005157 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005158 .getPackageUid(rec.key.packageName);
5159 if (uid != Binder.getCallingUid()) {
5160 String msg = "Permission Denial: cancelIntentSender() from pid="
5161 + Binder.getCallingPid()
5162 + ", uid=" + Binder.getCallingUid()
5163 + " is not allowed to cancel packges "
5164 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005165 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005166 throw new SecurityException(msg);
5167 }
5168 } catch (RemoteException e) {
5169 throw new SecurityException(e);
5170 }
5171 cancelIntentSenderLocked(rec, true);
5172 }
5173 }
5174
5175 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
5176 rec.canceled = true;
5177 mIntentSenderRecords.remove(rec.key);
5178 if (cleanActivity && rec.key.activity != null) {
5179 rec.key.activity.pendingResults.remove(rec.ref);
5180 }
5181 }
5182
5183 public String getPackageForIntentSender(IIntentSender pendingResult) {
5184 if (!(pendingResult instanceof PendingIntentRecord)) {
5185 return null;
5186 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07005187 try {
5188 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5189 return res.key.packageName;
5190 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191 }
5192 return null;
5193 }
5194
Dianne Hackborn6c418d52011-06-29 14:05:33 -07005195 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
5196 if (!(pendingResult instanceof PendingIntentRecord)) {
5197 return false;
5198 }
5199 try {
5200 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5201 if (res.key.allIntents == null) {
5202 return false;
5203 }
5204 for (int i=0; i<res.key.allIntents.length; i++) {
5205 Intent intent = res.key.allIntents[i];
5206 if (intent.getPackage() != null && intent.getComponent() != null) {
5207 return false;
5208 }
5209 }
5210 return true;
5211 } catch (ClassCastException e) {
5212 }
5213 return false;
5214 }
5215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005216 public void setProcessLimit(int max) {
5217 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5218 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005219 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005220 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005221 mProcessLimitOverride = max;
5222 }
5223 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 }
5225
5226 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005227 synchronized (this) {
5228 return mProcessLimitOverride;
5229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230 }
5231
5232 void foregroundTokenDied(ForegroundToken token) {
5233 synchronized (ActivityManagerService.this) {
5234 synchronized (mPidsSelfLocked) {
5235 ForegroundToken cur
5236 = mForegroundProcesses.get(token.pid);
5237 if (cur != token) {
5238 return;
5239 }
5240 mForegroundProcesses.remove(token.pid);
5241 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
5242 if (pr == null) {
5243 return;
5244 }
5245 pr.forcingToForeground = null;
5246 pr.foregroundServices = false;
5247 }
5248 updateOomAdjLocked();
5249 }
5250 }
5251
5252 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
5253 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5254 "setProcessForeground()");
5255 synchronized(this) {
5256 boolean changed = false;
5257
5258 synchronized (mPidsSelfLocked) {
5259 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005260 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005261 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005262 return;
5263 }
5264 ForegroundToken oldToken = mForegroundProcesses.get(pid);
5265 if (oldToken != null) {
5266 oldToken.token.unlinkToDeath(oldToken, 0);
5267 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005268 if (pr != null) {
5269 pr.forcingToForeground = null;
5270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005271 changed = true;
5272 }
5273 if (isForeground && token != null) {
5274 ForegroundToken newToken = new ForegroundToken() {
5275 public void binderDied() {
5276 foregroundTokenDied(this);
5277 }
5278 };
5279 newToken.pid = pid;
5280 newToken.token = token;
5281 try {
5282 token.linkToDeath(newToken, 0);
5283 mForegroundProcesses.put(pid, newToken);
5284 pr.forcingToForeground = token;
5285 changed = true;
5286 } catch (RemoteException e) {
5287 // If the process died while doing this, we will later
5288 // do the cleanup with the process death link.
5289 }
5290 }
5291 }
5292
5293 if (changed) {
5294 updateOomAdjLocked();
5295 }
5296 }
5297 }
5298
5299 // =========================================================
5300 // PERMISSIONS
5301 // =========================================================
5302
5303 static class PermissionController extends IPermissionController.Stub {
5304 ActivityManagerService mActivityManagerService;
5305 PermissionController(ActivityManagerService activityManagerService) {
5306 mActivityManagerService = activityManagerService;
5307 }
5308
5309 public boolean checkPermission(String permission, int pid, int uid) {
5310 return mActivityManagerService.checkPermission(permission, pid,
5311 uid) == PackageManager.PERMISSION_GRANTED;
5312 }
5313 }
5314
5315 /**
5316 * This can be called with or without the global lock held.
5317 */
5318 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005319 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320 // We might be performing an operation on behalf of an indirect binder
5321 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
5322 // client identity accordingly before proceeding.
5323 Identity tlsIdentity = sCallerIdentity.get();
5324 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005325 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005326 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
5327 uid = tlsIdentity.uid;
5328 pid = tlsIdentity.pid;
5329 }
5330
5331 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005332 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005333 return PackageManager.PERMISSION_GRANTED;
5334 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005335 // Isolated processes don't get any permissions.
5336 if (UserId.isIsolated(uid)) {
5337 return PackageManager.PERMISSION_DENIED;
5338 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005339 // If there is a uid that owns whatever is being accessed, it has
5340 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07005341 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005342 return PackageManager.PERMISSION_GRANTED;
5343 }
5344 // If the target is not exported, then nobody else can get to it.
5345 if (!exported) {
5346 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005347 return PackageManager.PERMISSION_DENIED;
5348 }
5349 if (permission == null) {
5350 return PackageManager.PERMISSION_GRANTED;
5351 }
5352 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005353 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354 .checkUidPermission(permission, uid);
5355 } catch (RemoteException e) {
5356 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08005357 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005358 }
5359 return PackageManager.PERMISSION_DENIED;
5360 }
5361
5362 /**
5363 * As the only public entry point for permissions checking, this method
5364 * can enforce the semantic that requesting a check on a null global
5365 * permission is automatically denied. (Internally a null permission
5366 * string is used when calling {@link #checkComponentPermission} in cases
5367 * when only uid-based security is needed.)
5368 *
5369 * This can be called with or without the global lock held.
5370 */
5371 public int checkPermission(String permission, int pid, int uid) {
5372 if (permission == null) {
5373 return PackageManager.PERMISSION_DENIED;
5374 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005375 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005376 }
5377
5378 /**
5379 * Binder IPC calls go through the public entry point.
5380 * This can be called with or without the global lock held.
5381 */
5382 int checkCallingPermission(String permission) {
5383 return checkPermission(permission,
5384 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07005385 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 }
5387
5388 /**
5389 * This can be called with or without the global lock held.
5390 */
5391 void enforceCallingPermission(String permission, String func) {
5392 if (checkCallingPermission(permission)
5393 == PackageManager.PERMISSION_GRANTED) {
5394 return;
5395 }
5396
5397 String msg = "Permission Denial: " + func + " from pid="
5398 + Binder.getCallingPid()
5399 + ", uid=" + Binder.getCallingUid()
5400 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005401 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005402 throw new SecurityException(msg);
5403 }
5404
5405 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07005406 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
5407 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
5408 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
5409 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5410 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005411 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005412 // Is the component private from the target uid?
5413 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
5414
5415 // Acceptable if the there is no read permission needed from the
5416 // target or the target is holding the read permission.
5417 if (!readPerm) {
5418 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07005420 == PackageManager.PERMISSION_GRANTED)) {
5421 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005422 }
5423 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005424
5425 // Acceptable if the there is no write permission needed from the
5426 // target or the target is holding the read permission.
5427 if (!writePerm) {
5428 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07005430 == PackageManager.PERMISSION_GRANTED)) {
5431 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 }
5433 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005434
5435 // Acceptable if there is a path permission matching the URI that
5436 // the target holds the permission on.
5437 PathPermission[] pps = pi.pathPermissions;
5438 if (pps != null && (!readPerm || !writePerm)) {
5439 final String path = uri.getPath();
5440 int i = pps.length;
5441 while (i > 0 && (!readPerm || !writePerm)) {
5442 i--;
5443 PathPermission pp = pps[i];
5444 if (!readPerm) {
5445 final String pprperm = pp.getReadPermission();
5446 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5447 + pprperm + " for " + pp.getPath()
5448 + ": match=" + pp.match(path)
5449 + " check=" + pm.checkUidPermission(pprperm, uid));
5450 if (pprperm != null && pp.match(path) &&
5451 (pm.checkUidPermission(pprperm, uid)
5452 == PackageManager.PERMISSION_GRANTED)) {
5453 readPerm = true;
5454 }
5455 }
5456 if (!writePerm) {
5457 final String ppwperm = pp.getWritePermission();
5458 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5459 + ppwperm + " for " + pp.getPath()
5460 + ": match=" + pp.match(path)
5461 + " check=" + pm.checkUidPermission(ppwperm, uid));
5462 if (ppwperm != null && pp.match(path) &&
5463 (pm.checkUidPermission(ppwperm, uid)
5464 == PackageManager.PERMISSION_GRANTED)) {
5465 writePerm = true;
5466 }
5467 }
5468 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 } catch (RemoteException e) {
5471 return false;
5472 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005473
5474 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 }
5476
5477 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5478 int modeFlags) {
5479 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005480 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005481 return true;
5482 }
5483 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5484 if (perms == null) return false;
5485 UriPermission perm = perms.get(uri);
5486 if (perm == null) return false;
5487 return (modeFlags&perm.modeFlags) == modeFlags;
5488 }
5489
5490 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005491 enforceNotIsolatedCaller("checkUriPermission");
5492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 // Another redirected-binder-call permissions check as in
5494 // {@link checkComponentPermission}.
5495 Identity tlsIdentity = sCallerIdentity.get();
5496 if (tlsIdentity != null) {
5497 uid = tlsIdentity.uid;
5498 pid = tlsIdentity.pid;
5499 }
5500
Amith Yamasani742a6712011-05-04 14:49:28 -07005501 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005502 // Our own process gets to do everything.
5503 if (pid == MY_PID) {
5504 return PackageManager.PERMISSION_GRANTED;
5505 }
5506 synchronized(this) {
5507 return checkUriPermissionLocked(uri, uid, modeFlags)
5508 ? PackageManager.PERMISSION_GRANTED
5509 : PackageManager.PERMISSION_DENIED;
5510 }
5511 }
5512
Dianne Hackborn39792d22010-08-19 18:01:52 -07005513 /**
5514 * Check if the targetPkg can be granted permission to access uri by
5515 * the callingUid using the given modeFlags. Throws a security exception
5516 * if callingUid is not allowed to do this. Returns the uid of the target
5517 * if the URI permission grant should be performed; returns -1 if it is not
5518 * needed (for example targetPkg already has permission to access the URI).
5519 */
5520 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
5521 Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5523 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5524 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005525 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 }
5527
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005528 if (targetPkg != null) {
5529 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5530 "Checking grant " + targetPkg + " permission to " + uri);
5531 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005532
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005533 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534
5535 // If this is not a content: uri, we can't do anything with it.
5536 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005537 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005538 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005539 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 }
5541
5542 String name = uri.getAuthority();
5543 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005544 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
5545 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 if (cpr != null) {
5547 pi = cpr.info;
5548 } else {
5549 try {
5550 pi = pm.resolveContentProvider(name,
5551 PackageManager.GET_URI_PERMISSION_PATTERNS);
5552 } catch (RemoteException ex) {
5553 }
5554 }
5555 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005556 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005557 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 }
5559
5560 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005561 if (targetPkg != null) {
5562 try {
5563 targetUid = pm.getPackageUid(targetPkg);
5564 if (targetUid < 0) {
5565 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5566 "Can't grant URI permission no uid for: " + targetPkg);
5567 return -1;
5568 }
5569 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005570 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005572 } else {
5573 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 }
5575
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005576 if (targetUid >= 0) {
5577 // First... does the target actually need this permission?
5578 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5579 // No need to grant the target this permission.
5580 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5581 "Target " + targetPkg + " already has full permission to " + uri);
5582 return -1;
5583 }
5584 } else {
5585 // First... there is no target package, so can anyone access it?
5586 boolean allowed = pi.exported;
5587 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5588 if (pi.readPermission != null) {
5589 allowed = false;
5590 }
5591 }
5592 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5593 if (pi.writePermission != null) {
5594 allowed = false;
5595 }
5596 }
5597 if (allowed) {
5598 return -1;
5599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005600 }
5601
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005602 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 if (!pi.grantUriPermissions) {
5604 throw new SecurityException("Provider " + pi.packageName
5605 + "/" + pi.name
5606 + " does not allow granting of Uri permissions (uri "
5607 + uri + ")");
5608 }
5609 if (pi.uriPermissionPatterns != null) {
5610 final int N = pi.uriPermissionPatterns.length;
5611 boolean allowed = false;
5612 for (int i=0; i<N; i++) {
5613 if (pi.uriPermissionPatterns[i] != null
5614 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5615 allowed = true;
5616 break;
5617 }
5618 }
5619 if (!allowed) {
5620 throw new SecurityException("Provider " + pi.packageName
5621 + "/" + pi.name
5622 + " does not allow granting of permission to path of Uri "
5623 + uri);
5624 }
5625 }
5626
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005627 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005628 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005629 if (callingUid != Process.myUid()) {
5630 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5631 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5632 throw new SecurityException("Uid " + callingUid
5633 + " does not have permission to uri " + uri);
5634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 }
5636 }
5637
Dianne Hackborn39792d22010-08-19 18:01:52 -07005638 return targetUid;
5639 }
5640
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005641 public int checkGrantUriPermission(int callingUid, String targetPkg,
5642 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005643 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005644 synchronized(this) {
5645 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
5646 }
5647 }
5648
Dianne Hackborn39792d22010-08-19 18:01:52 -07005649 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5650 Uri uri, int modeFlags, UriPermissionOwner owner) {
5651 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5652 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5653 if (modeFlags == 0) {
5654 return;
5655 }
5656
5657 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 // to the uri, and the target doesn't. Let's now give this to
5659 // the target.
5660
Joe Onorato8a9b2202010-02-26 18:56:32 -08005661 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005662 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664 HashMap<Uri, UriPermission> targetUris
5665 = mGrantedUriPermissions.get(targetUid);
5666 if (targetUris == null) {
5667 targetUris = new HashMap<Uri, UriPermission>();
5668 mGrantedUriPermissions.put(targetUid, targetUris);
5669 }
5670
5671 UriPermission perm = targetUris.get(uri);
5672 if (perm == null) {
5673 perm = new UriPermission(targetUid, uri);
5674 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005678 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005679 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005680 } else {
5681 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5682 perm.readOwners.add(owner);
5683 owner.addReadPermission(perm);
5684 }
5685 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5686 perm.writeOwners.add(owner);
5687 owner.addWritePermission(perm);
5688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689 }
5690 }
5691
Dianne Hackborn39792d22010-08-19 18:01:52 -07005692 void grantUriPermissionLocked(int callingUid,
5693 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005694 if (targetPkg == null) {
5695 throw new NullPointerException("targetPkg");
5696 }
5697
Dianne Hackborn39792d22010-08-19 18:01:52 -07005698 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
5699 if (targetUid < 0) {
5700 return;
5701 }
5702
5703 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5704 }
5705
5706 /**
5707 * Like checkGrantUriPermissionLocked, but takes an Intent.
5708 */
5709 int checkGrantUriPermissionFromIntentLocked(int callingUid,
5710 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005711 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005712 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005713 + " from " + intent + "; flags=0x"
5714 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5715
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005716 if (targetPkg == null) {
5717 throw new NullPointerException("targetPkg");
5718 }
5719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005721 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 }
5723 Uri data = intent.getData();
5724 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005725 return -1;
5726 }
5727 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5728 intent.getFlags());
5729 }
5730
5731 /**
5732 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5733 */
5734 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
5735 String targetPkg, Intent intent, UriPermissionOwner owner) {
5736 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
5737 intent.getFlags(), owner);
5738 }
5739
5740 void grantUriPermissionFromIntentLocked(int callingUid,
5741 String targetPkg, Intent intent, UriPermissionOwner owner) {
5742 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
5743 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 return;
5745 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005746
5747 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 }
5749
5750 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5751 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005752 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005753 synchronized(this) {
5754 final ProcessRecord r = getRecordForAppLocked(caller);
5755 if (r == null) {
5756 throw new SecurityException("Unable to find app for caller "
5757 + caller
5758 + " when granting permission to uri " + uri);
5759 }
5760 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005761 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 }
5763 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005764 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 }
5766
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005767 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 null);
5769 }
5770 }
5771
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005772 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5774 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5775 HashMap<Uri, UriPermission> perms
5776 = mGrantedUriPermissions.get(perm.uid);
5777 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005778 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005779 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 perms.remove(perm.uri);
5781 if (perms.size() == 0) {
5782 mGrantedUriPermissions.remove(perm.uid);
5783 }
5784 }
5785 }
5786 }
5787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5789 int modeFlags) {
5790 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5791 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5792 if (modeFlags == 0) {
5793 return;
5794 }
5795
Joe Onorato8a9b2202010-02-26 18:56:32 -08005796 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005797 "Revoking all granted permissions to " + uri);
5798
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005799 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800
5801 final String authority = uri.getAuthority();
5802 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005803 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
5804 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005805 if (cpr != null) {
5806 pi = cpr.info;
5807 } else {
5808 try {
5809 pi = pm.resolveContentProvider(authority,
5810 PackageManager.GET_URI_PERMISSION_PATTERNS);
5811 } catch (RemoteException ex) {
5812 }
5813 }
5814 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005815 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 return;
5817 }
5818
5819 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005820 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 // Right now, if you are not the original owner of the permission,
5822 // you are not allowed to revoke it.
5823 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5824 throw new SecurityException("Uid " + callingUid
5825 + " does not have permission to uri " + uri);
5826 //}
5827 }
5828
5829 // Go through all of the permissions and remove any that match.
5830 final List<String> SEGMENTS = uri.getPathSegments();
5831 if (SEGMENTS != null) {
5832 final int NS = SEGMENTS.size();
5833 int N = mGrantedUriPermissions.size();
5834 for (int i=0; i<N; i++) {
5835 HashMap<Uri, UriPermission> perms
5836 = mGrantedUriPermissions.valueAt(i);
5837 Iterator<UriPermission> it = perms.values().iterator();
5838 toploop:
5839 while (it.hasNext()) {
5840 UriPermission perm = it.next();
5841 Uri targetUri = perm.uri;
5842 if (!authority.equals(targetUri.getAuthority())) {
5843 continue;
5844 }
5845 List<String> targetSegments = targetUri.getPathSegments();
5846 if (targetSegments == null) {
5847 continue;
5848 }
5849 if (targetSegments.size() < NS) {
5850 continue;
5851 }
5852 for (int j=0; j<NS; j++) {
5853 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5854 continue toploop;
5855 }
5856 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005857 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005858 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005859 perm.clearModes(modeFlags);
5860 if (perm.modeFlags == 0) {
5861 it.remove();
5862 }
5863 }
5864 if (perms.size() == 0) {
5865 mGrantedUriPermissions.remove(
5866 mGrantedUriPermissions.keyAt(i));
5867 N--;
5868 i--;
5869 }
5870 }
5871 }
5872 }
5873
5874 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5875 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005876 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 synchronized(this) {
5878 final ProcessRecord r = getRecordForAppLocked(caller);
5879 if (r == null) {
5880 throw new SecurityException("Unable to find app for caller "
5881 + caller
5882 + " when revoking permission to uri " + uri);
5883 }
5884 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005885 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005886 return;
5887 }
5888
5889 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5890 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5891 if (modeFlags == 0) {
5892 return;
5893 }
5894
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005895 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005896
5897 final String authority = uri.getAuthority();
5898 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005899 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 if (cpr != null) {
5901 pi = cpr.info;
5902 } else {
5903 try {
5904 pi = pm.resolveContentProvider(authority,
5905 PackageManager.GET_URI_PERMISSION_PATTERNS);
5906 } catch (RemoteException ex) {
5907 }
5908 }
5909 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005910 Slog.w(TAG, "No content provider found for permission revoke: "
5911 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 return;
5913 }
5914
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005915 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005916 }
5917 }
5918
Dianne Hackborn7e269642010-08-25 19:50:20 -07005919 @Override
5920 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005921 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005922 synchronized(this) {
5923 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5924 return owner.getExternalTokenLocked();
5925 }
5926 }
5927
5928 @Override
5929 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5930 Uri uri, int modeFlags) {
5931 synchronized(this) {
5932 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5933 if (owner == null) {
5934 throw new IllegalArgumentException("Unknown owner: " + token);
5935 }
5936 if (fromUid != Binder.getCallingUid()) {
5937 if (Binder.getCallingUid() != Process.myUid()) {
5938 // Only system code can grant URI permissions on behalf
5939 // of other users.
5940 throw new SecurityException("nice try");
5941 }
5942 }
5943 if (targetPkg == null) {
5944 throw new IllegalArgumentException("null target");
5945 }
5946 if (uri == null) {
5947 throw new IllegalArgumentException("null uri");
5948 }
5949
5950 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5951 }
5952 }
5953
5954 @Override
5955 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5956 synchronized(this) {
5957 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5958 if (owner == null) {
5959 throw new IllegalArgumentException("Unknown owner: " + token);
5960 }
5961
5962 if (uri == null) {
5963 owner.removeUriPermissionsLocked(mode);
5964 } else {
5965 owner.removeUriPermissionLocked(uri, mode);
5966 }
5967 }
5968 }
5969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5971 synchronized (this) {
5972 ProcessRecord app =
5973 who != null ? getRecordForAppLocked(who) : null;
5974 if (app == null) return;
5975
5976 Message msg = Message.obtain();
5977 msg.what = WAIT_FOR_DEBUGGER_MSG;
5978 msg.obj = app;
5979 msg.arg1 = waiting ? 1 : 0;
5980 mHandler.sendMessage(msg);
5981 }
5982 }
5983
5984 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005985 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5986 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005988 outInfo.threshold = homeAppMem;
5989 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5990 outInfo.hiddenAppThreshold = hiddenAppMem;
5991 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005992 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005993 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5994 ProcessList.VISIBLE_APP_ADJ);
5995 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5996 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 }
5998
5999 // =========================================================
6000 // TASK MANAGEMENT
6001 // =========================================================
6002
6003 public List getTasks(int maxNum, int flags,
6004 IThumbnailReceiver receiver) {
6005 ArrayList list = new ArrayList();
6006
6007 PendingThumbnailsRecord pending = null;
6008 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006009 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010
6011 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006012 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
6014 + ", receiver=" + receiver);
6015
6016 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
6017 != PackageManager.PERMISSION_GRANTED) {
6018 if (receiver != null) {
6019 // If the caller wants to wait for pending thumbnails,
6020 // it ain't gonna get them.
6021 try {
6022 receiver.finished();
6023 } catch (RemoteException ex) {
6024 }
6025 }
6026 String msg = "Permission Denial: getTasks() from pid="
6027 + Binder.getCallingPid()
6028 + ", uid=" + Binder.getCallingUid()
6029 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006030 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 throw new SecurityException(msg);
6032 }
6033
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006034 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006035 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006036 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006037 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 TaskRecord curTask = null;
6039 int numActivities = 0;
6040 int numRunning = 0;
6041 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006042 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006044 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045
6046 // Initialize state for next task if needed.
6047 if (top == null ||
6048 (top.state == ActivityState.INITIALIZING
6049 && top.task == r.task)) {
6050 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 curTask = r.task;
6052 numActivities = numRunning = 0;
6053 }
6054
6055 // Add 'r' into the current task.
6056 numActivities++;
6057 if (r.app != null && r.app.thread != null) {
6058 numRunning++;
6059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060
Joe Onorato8a9b2202010-02-26 18:56:32 -08006061 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006062 TAG, r.intent.getComponent().flattenToShortString()
6063 + ": task=" + r.task);
6064
6065 // If the next one is a different task, generate a new
6066 // TaskInfo entry for what we have.
6067 if (next == null || next.task != curTask) {
6068 ActivityManager.RunningTaskInfo ci
6069 = new ActivityManager.RunningTaskInfo();
6070 ci.id = curTask.taskId;
6071 ci.baseActivity = r.intent.getComponent();
6072 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006073 if (top.thumbHolder != null) {
6074 ci.description = top.thumbHolder.lastDescription;
6075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 ci.numActivities = numActivities;
6077 ci.numRunning = numRunning;
6078 //System.out.println(
6079 // "#" + maxNum + ": " + " descr=" + ci.description);
6080 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006081 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 TAG, "State=" + top.state + "Idle=" + top.idle
6083 + " app=" + top.app
6084 + " thr=" + (top.app != null ? top.app.thread : null));
6085 if (top.state == ActivityState.RESUMED
6086 || top.state == ActivityState.PAUSING) {
6087 if (top.idle && top.app != null
6088 && top.app.thread != null) {
6089 topRecord = top;
6090 topThumbnail = top.app.thread;
6091 } else {
6092 top.thumbnailNeeded = true;
6093 }
6094 }
6095 if (pending == null) {
6096 pending = new PendingThumbnailsRecord(receiver);
6097 }
6098 pending.pendingRecords.add(top);
6099 }
6100 list.add(ci);
6101 maxNum--;
6102 top = null;
6103 }
6104 }
6105
6106 if (pending != null) {
6107 mPendingThumbnails.add(pending);
6108 }
6109 }
6110
Joe Onorato8a9b2202010-02-26 18:56:32 -08006111 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006112
6113 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006114 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08006116 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006118 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006119 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 }
6121 }
6122
6123 if (pending == null && receiver != null) {
6124 // In this case all thumbnails were available and the client
6125 // is being asked to be told when the remaining ones come in...
6126 // which is unusually, since the top-most currently running
6127 // activity should never have a canned thumbnail! Oh well.
6128 try {
6129 receiver.finished();
6130 } catch (RemoteException ex) {
6131 }
6132 }
6133
6134 return list;
6135 }
6136
6137 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
6138 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006139 final int callingUid = Binder.getCallingUid();
6140 // If it's the system uid asking, then use the current user id.
6141 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
6142 // require the entire list.
6143 final int callingUserId = callingUid == Process.SYSTEM_UID
6144 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 synchronized (this) {
6146 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
6147 "getRecentTasks()");
6148
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006149 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07006150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 final int N = mRecentTasks.size();
6152 ArrayList<ActivityManager.RecentTaskInfo> res
6153 = new ArrayList<ActivityManager.RecentTaskInfo>(
6154 maxNum < N ? maxNum : N);
6155 for (int i=0; i<N && maxNum > 0; i++) {
6156 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07006157 // Only add calling user's recent tasks
6158 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07006159 // Return the entry if desired by the caller. We always return
6160 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07006161 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07006162 // not supplied RECENT_WITH_EXCLUDED and there is some reason
6163 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07006164
Dianne Hackborn905577f2011-09-07 18:31:28 -07006165 if (i == 0
6166 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 || (tr.intent == null)
6168 || ((tr.intent.getFlags()
6169 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
6170 ActivityManager.RecentTaskInfo rti
6171 = new ActivityManager.RecentTaskInfo();
6172 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08006173 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006174 rti.baseIntent = new Intent(
6175 tr.intent != null ? tr.intent : tr.affinityIntent);
6176 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08006177 rti.description = tr.lastDescription;
6178
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07006179 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
6180 // Check whether this activity is currently available.
6181 try {
6182 if (rti.origActivity != null) {
6183 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
6184 continue;
6185 }
6186 } else if (rti.baseIntent != null) {
6187 if (pm.queryIntentActivities(rti.baseIntent,
6188 null, 0) == null) {
6189 continue;
6190 }
6191 }
6192 } catch (RemoteException e) {
6193 // Will never happen.
6194 }
6195 }
6196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 res.add(rti);
6198 maxNum--;
6199 }
6200 }
6201 return res;
6202 }
6203 }
6204
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006205 private TaskRecord taskForIdLocked(int id) {
6206 final int N = mRecentTasks.size();
6207 for (int i=0; i<N; i++) {
6208 TaskRecord tr = mRecentTasks.get(i);
6209 if (tr.taskId == id) {
6210 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08006211 }
6212 }
6213 return null;
6214 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006215
6216 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
6217 synchronized (this) {
6218 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
6219 "getTaskThumbnails()");
6220 TaskRecord tr = taskForIdLocked(id);
6221 if (tr != null) {
6222 return mMainStack.getTaskThumbnailsLocked(tr);
6223 }
6224 }
6225 return null;
6226 }
6227
6228 public boolean removeSubTask(int taskId, int subTaskIndex) {
6229 synchronized (this) {
6230 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
6231 "removeSubTask()");
6232 long ident = Binder.clearCallingIdentity();
6233 try {
6234 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
6235 } finally {
6236 Binder.restoreCallingIdentity(ident);
6237 }
6238 }
6239 }
6240
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006241 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006242 TaskRecord tr = root.task;
6243 Intent baseIntent = new Intent(
6244 tr.intent != null ? tr.intent : tr.affinityIntent);
6245 ComponentName component = baseIntent.getComponent();
6246 if (component == null) {
6247 Slog.w(TAG, "Now component for base intent of task: " + tr);
6248 return;
6249 }
6250
6251 // Find any running services associated with this app.
6252 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07006253 for (ServiceRecord sr : mServiceMap.getAllServices(root.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006254 if (sr.packageName.equals(component.getPackageName())) {
6255 services.add(sr);
6256 }
6257 }
6258
6259 // Take care of any running services associated with the app.
6260 for (int i=0; i<services.size(); i++) {
6261 ServiceRecord sr = services.get(i);
6262 if (sr.startRequested) {
6263 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006264 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006265 stopServiceLocked(sr);
6266 } else {
6267 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
6268 sr.makeNextStartId(), baseIntent, -1));
6269 if (sr.app != null && sr.app.thread != null) {
6270 sendServiceArgsLocked(sr, false);
6271 }
6272 }
6273 }
6274 }
6275
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006276 if (killProcesses) {
6277 // Find any running processes associated with this app.
6278 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
6279 SparseArray<ProcessRecord> appProcs
6280 = mProcessNames.getMap().get(component.getPackageName());
6281 if (appProcs != null) {
6282 for (int i=0; i<appProcs.size(); i++) {
6283 procs.add(appProcs.valueAt(i));
6284 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006285 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006286
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006287 // Kill the running processes.
6288 for (int i=0; i<procs.size(); i++) {
6289 ProcessRecord pr = procs.get(i);
6290 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
6291 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
6292 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
6293 pr.processName, pr.setAdj, "remove task");
6294 Process.killProcessQuiet(pr.pid);
6295 } else {
6296 pr.waitingToKill = "remove task";
6297 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006298 }
6299 }
6300 }
6301
6302 public boolean removeTask(int taskId, int flags) {
6303 synchronized (this) {
6304 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
6305 "removeTask()");
6306 long ident = Binder.clearCallingIdentity();
6307 try {
6308 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
6309 if (r != null) {
6310 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006311 cleanUpRemovedTaskLocked(r,
6312 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006313 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07006314 } else {
6315 TaskRecord tr = null;
6316 int i=0;
6317 while (i < mRecentTasks.size()) {
6318 TaskRecord t = mRecentTasks.get(i);
6319 if (t.taskId == taskId) {
6320 tr = t;
6321 break;
6322 }
6323 i++;
6324 }
6325 if (tr != null) {
6326 if (tr.numActivities <= 0) {
6327 // Caller is just removing a recent task that is
6328 // not actively running. That is easy!
6329 mRecentTasks.remove(i);
6330 } else {
6331 Slog.w(TAG, "removeTask: task " + taskId
6332 + " does not have activities to remove, "
6333 + " but numActivities=" + tr.numActivities
6334 + ": " + tr);
6335 }
6336 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006337 }
6338 } finally {
6339 Binder.restoreCallingIdentity(ident);
6340 }
6341 }
6342 return false;
6343 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08006344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
6346 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006347 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 TaskRecord jt = startTask;
6349
6350 // First look backwards
6351 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006352 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 if (r.task != jt) {
6354 jt = r.task;
6355 if (affinity.equals(jt.affinity)) {
6356 return j;
6357 }
6358 }
6359 }
6360
6361 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006362 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 jt = startTask;
6364 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006365 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 if (r.task != jt) {
6367 if (affinity.equals(jt.affinity)) {
6368 return j;
6369 }
6370 jt = r.task;
6371 }
6372 }
6373
6374 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006375 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 return N-1;
6377 }
6378
6379 return -1;
6380 }
6381
6382 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006383 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006385 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6387 "moveTaskToFront()");
6388
6389 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006390 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6391 Binder.getCallingUid(), "Task to front")) {
6392 return;
6393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 final long origId = Binder.clearCallingIdentity();
6395 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006396 TaskRecord tr = taskForIdLocked(task);
6397 if (tr != null) {
6398 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6399 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006401 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6402 // Caller wants the home activity moved with it. To accomplish this,
6403 // we'll just move the home task to the top first.
6404 mMainStack.moveHomeToFrontLocked();
6405 }
6406 mMainStack.moveTaskToFrontLocked(tr, null);
6407 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006409 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6410 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006412 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6413 mMainStack.mUserLeaving = true;
6414 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006415 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6416 // Caller wants the home activity moved with it. To accomplish this,
6417 // we'll just move the home task to the top first.
6418 mMainStack.moveHomeToFrontLocked();
6419 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006420 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 return;
6422 }
6423 }
6424 } finally {
6425 Binder.restoreCallingIdentity(origId);
6426 }
6427 }
6428 }
6429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 public void moveTaskToBack(int task) {
6431 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6432 "moveTaskToBack()");
6433
6434 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006435 if (mMainStack.mResumedActivity != null
6436 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006437 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6438 Binder.getCallingUid(), "Task to back")) {
6439 return;
6440 }
6441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006443 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 Binder.restoreCallingIdentity(origId);
6445 }
6446 }
6447
6448 /**
6449 * Moves an activity, and all of the other activities within the same task, to the bottom
6450 * of the history stack. The activity's order within the task is unchanged.
6451 *
6452 * @param token A reference to the activity we wish to move
6453 * @param nonRoot If false then this only works if the activity is the root
6454 * of a task; if true it will work for any activity in a task.
6455 * @return Returns true if the move completed, false if not.
6456 */
6457 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006458 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 synchronized(this) {
6460 final long origId = Binder.clearCallingIdentity();
6461 int taskId = getTaskForActivityLocked(token, !nonRoot);
6462 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006463 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 }
6465 Binder.restoreCallingIdentity(origId);
6466 }
6467 return false;
6468 }
6469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 public void moveTaskBackwards(int task) {
6471 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6472 "moveTaskBackwards()");
6473
6474 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006475 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6476 Binder.getCallingUid(), "Task backwards")) {
6477 return;
6478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 final long origId = Binder.clearCallingIdentity();
6480 moveTaskBackwardsLocked(task);
6481 Binder.restoreCallingIdentity(origId);
6482 }
6483 }
6484
6485 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006486 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 }
6488
6489 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6490 synchronized(this) {
6491 return getTaskForActivityLocked(token, onlyRoot);
6492 }
6493 }
6494
6495 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006496 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 TaskRecord lastTask = null;
6498 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006499 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006500 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 if (!onlyRoot || lastTask != r.task) {
6502 return r.task.taskId;
6503 }
6504 return -1;
6505 }
6506 lastTask = r.task;
6507 }
6508
6509 return -1;
6510 }
6511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 public void finishOtherInstances(IBinder token, ComponentName className) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006513 enforceNotIsolatedCaller("finishOtherInstances");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006514 synchronized(this) {
6515 final long origId = Binder.clearCallingIdentity();
6516
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006517 int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 TaskRecord lastTask = null;
6519 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006520 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 if (r.realActivity.equals(className)
Dianne Hackbornbe707852011-11-11 14:32:10 -08006522 && r.appToken != token && lastTask != r.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006523 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 null, "others")) {
6525 i--;
6526 N--;
6527 }
6528 }
6529 lastTask = r.task;
6530 }
6531
6532 Binder.restoreCallingIdentity(origId);
6533 }
6534 }
6535
6536 // =========================================================
6537 // THUMBNAILS
6538 // =========================================================
6539
6540 public void reportThumbnail(IBinder token,
6541 Bitmap thumbnail, CharSequence description) {
6542 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6543 final long origId = Binder.clearCallingIdentity();
6544 sendPendingThumbnail(null, token, thumbnail, description, true);
6545 Binder.restoreCallingIdentity(origId);
6546 }
6547
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006548 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 Bitmap thumbnail, CharSequence description, boolean always) {
6550 TaskRecord task = null;
6551 ArrayList receivers = null;
6552
6553 //System.out.println("Send pending thumbnail: " + r);
6554
6555 synchronized(this) {
6556 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006557 r = mMainStack.isInStackLocked(token);
6558 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559 return;
6560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006561 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006562 if (thumbnail == null && r.thumbHolder != null) {
6563 thumbnail = r.thumbHolder.lastThumbnail;
6564 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006565 }
6566 if (thumbnail == null && !always) {
6567 // If there is no thumbnail, and this entry is not actually
6568 // going away, then abort for now and pick up the next
6569 // thumbnail we get.
6570 return;
6571 }
6572 task = r.task;
6573
6574 int N = mPendingThumbnails.size();
6575 int i=0;
6576 while (i<N) {
6577 PendingThumbnailsRecord pr =
6578 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6579 //System.out.println("Looking in " + pr.pendingRecords);
6580 if (pr.pendingRecords.remove(r)) {
6581 if (receivers == null) {
6582 receivers = new ArrayList();
6583 }
6584 receivers.add(pr);
6585 if (pr.pendingRecords.size() == 0) {
6586 pr.finished = true;
6587 mPendingThumbnails.remove(i);
6588 N--;
6589 continue;
6590 }
6591 }
6592 i++;
6593 }
6594 }
6595
6596 if (receivers != null) {
6597 final int N = receivers.size();
6598 for (int i=0; i<N; i++) {
6599 try {
6600 PendingThumbnailsRecord pr =
6601 (PendingThumbnailsRecord)receivers.get(i);
6602 pr.receiver.newThumbnail(
6603 task != null ? task.taskId : -1, thumbnail, description);
6604 if (pr.finished) {
6605 pr.receiver.finished();
6606 }
6607 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006608 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 }
6610 }
6611 }
6612 }
6613
6614 // =========================================================
6615 // CONTENT PROVIDERS
6616 // =========================================================
6617
Jeff Brown10e89712011-07-08 18:52:57 -07006618 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6619 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006621 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006622 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006623 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 } catch (RemoteException ex) {
6625 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006626 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006627 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6628 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 if (providers != null) {
6630 final int N = providers.size();
6631 for (int i=0; i<N; i++) {
6632 ProviderInfo cpi =
6633 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07006634
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006635 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006636 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 if (cpr == null) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006638 cpr = new ContentProviderRecord(cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07006639 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006641 if (DEBUG_MU)
6642 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006643 app.pubProviders.put(cpi.name, cpr);
6644 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006645 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 }
6647 }
6648 return providers;
6649 }
6650
6651 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006652 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006654 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006656 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006657 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 return null;
6659 }
6660 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006661 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 == PackageManager.PERMISSION_GRANTED) {
6663 return null;
6664 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006665
6666 PathPermission[] pps = cpi.pathPermissions;
6667 if (pps != null) {
6668 int i = pps.length;
6669 while (i > 0) {
6670 i--;
6671 PathPermission pp = pps[i];
6672 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006673 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006674 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006675 return null;
6676 }
6677 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006678 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006679 == PackageManager.PERMISSION_GRANTED) {
6680 return null;
6681 }
6682 }
6683 }
6684
Dianne Hackbornb424b632010-08-18 15:59:05 -07006685 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6686 if (perms != null) {
6687 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6688 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6689 return null;
6690 }
6691 }
6692 }
6693
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006694 String msg;
6695 if (!cpi.exported) {
6696 msg = "Permission Denial: opening provider " + cpi.name
6697 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6698 + ", uid=" + callingUid + ") that is not exported from uid "
6699 + cpi.applicationInfo.uid;
6700 } else {
6701 msg = "Permission Denial: opening provider " + cpi.name
6702 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6703 + ", uid=" + callingUid + ") requires "
6704 + cpi.readPermission + " or " + cpi.writePermission;
6705 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006706 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 return msg;
6708 }
6709
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006710 boolean incProviderCount(ProcessRecord r, ContentProviderRecord cpr) {
6711 if (r != null) {
6712 Integer cnt = r.conProviders.get(cpr);
6713 if (DEBUG_PROVIDER) Slog.v(TAG,
6714 "Adding provider requested by "
6715 + r.processName + " from process "
6716 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6717 + " cnt=" + (cnt == null ? 1 : cnt));
6718 if (cnt == null) {
6719 cpr.clients.add(r);
6720 r.conProviders.put(cpr, new Integer(1));
6721 return true;
6722 } else {
6723 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6724 }
6725 } else {
6726 cpr.externals++;
6727 }
6728 return false;
6729 }
6730
6731 boolean decProviderCount(ProcessRecord r, ContentProviderRecord cpr) {
6732 if (r != null) {
6733 Integer cnt = r.conProviders.get(cpr);
6734 if (DEBUG_PROVIDER) Slog.v(TAG,
6735 "Removing provider requested by "
6736 + r.processName + " from process "
6737 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6738 + " cnt=" + cnt);
6739 if (cnt == null || cnt.intValue() <= 1) {
6740 cpr.clients.remove(r);
6741 r.conProviders.remove(cpr);
6742 return true;
6743 } else {
6744 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6745 }
6746 } else {
6747 cpr.externals++;
6748 }
6749 return false;
6750 }
6751
Amith Yamasani742a6712011-05-04 14:49:28 -07006752 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
6753 String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 ContentProviderRecord cpr;
6755 ProviderInfo cpi = null;
6756
6757 synchronized(this) {
6758 ProcessRecord r = null;
6759 if (caller != null) {
6760 r = getRecordForAppLocked(caller);
6761 if (r == null) {
6762 throw new SecurityException(
6763 "Unable to find app for caller " + caller
6764 + " (pid=" + Binder.getCallingPid()
6765 + ") when getting content provider " + name);
6766 }
6767 }
6768
6769 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006770 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006771 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006772 boolean providerRunning = cpr != null;
6773 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006775 String msg;
6776 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6777 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778 }
6779
6780 if (r != null && cpr.canRunHere(r)) {
6781 // This provider has been published or is in the process
6782 // of being published... but it is also allowed to run
6783 // in the caller's process, so don't make a connection
6784 // and just let the caller instantiate its own instance.
6785 if (cpr.provider != null) {
6786 // don't give caller the provider object, it needs
6787 // to make its own.
6788 cpr = new ContentProviderRecord(cpr);
6789 }
6790 return cpr;
6791 }
6792
6793 final long origId = Binder.clearCallingIdentity();
6794
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006795 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 // return it right away.
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006797 final boolean countChanged = incProviderCount(r, cpr);
6798 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006799 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006800 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006801 // make sure to count it as being accessed and thus
6802 // back up on the LRU list. This is good because
6803 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006804 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006805 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006806 }
6807
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006808 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006809 if (false) {
6810 if (cpr.name.flattenToShortString().equals(
6811 "com.android.providers.calendar/.CalendarProvider2")) {
6812 Slog.v(TAG, "****************** KILLING "
6813 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006814 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006815 }
6816 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006817 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006818 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6819 // NOTE: there is still a race here where a signal could be
6820 // pending on the process even though we managed to update its
6821 // adj level. Not sure what to do about this, but at least
6822 // the race is now smaller.
6823 if (!success) {
6824 // Uh oh... it looks like the provider's process
6825 // has been killed on us. We need to wait for a new
6826 // process to be started, and make sure its death
6827 // doesn't kill our process.
6828 Slog.i(TAG,
6829 "Existing provider " + cpr.name.flattenToShortString()
6830 + " is crashing; detaching " + r);
6831 boolean lastRef = decProviderCount(r, cpr);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006832 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006833 if (!lastRef) {
6834 // This wasn't the last ref our process had on
6835 // the provider... we have now been killed, bail.
6836 return null;
6837 }
6838 providerRunning = false;
6839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 }
6841
6842 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006845 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006846 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006847 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006848 resolveContentProvider(name,
6849 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006850 } catch (RemoteException ex) {
6851 }
6852 if (cpi == null) {
6853 return null;
6854 }
6855
Amith Yamasani742a6712011-05-04 14:49:28 -07006856 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
6857 Binder.getOrigCallingUser());
6858
Dianne Hackbornb424b632010-08-18 15:59:05 -07006859 String msg;
6860 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6861 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 }
6863
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006864 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006865 && !cpi.processName.equals("system")) {
6866 // If this content provider does not run in the system
6867 // process, and the system is not yet ready to run other
6868 // processes, then fail fast instead of hanging.
6869 throw new IllegalArgumentException(
6870 "Attempt to launch content provider before system ready");
6871 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006872
6873 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006874 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006875 final boolean firstClass = cpr == null;
6876 if (firstClass) {
6877 try {
6878 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006879 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006880 getApplicationInfo(
6881 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006882 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006883 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006884 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006885 + cpi.name);
6886 return null;
6887 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006888 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006889 cpr = new ContentProviderRecord(cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006890 } catch (RemoteException ex) {
6891 // pm is in same process, this will never happen.
6892 }
6893 }
6894
6895 if (r != null && cpr.canRunHere(r)) {
6896 // If this is a multiprocess provider, then just return its
6897 // info and allow the caller to instantiate it. Only do
6898 // this if the provider is the same user as the caller's
6899 // process, or can run as root (so can be in any process).
6900 return cpr;
6901 }
6902
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006903 if (DEBUG_PROVIDER) {
6904 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006905 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006906 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006907 }
6908
6909 // This is single process, and our app is now connecting to it.
6910 // See if we are already in the process of launching this
6911 // provider.
6912 final int N = mLaunchingProviders.size();
6913 int i;
6914 for (i=0; i<N; i++) {
6915 if (mLaunchingProviders.get(i) == cpr) {
6916 break;
6917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918 }
6919
6920 // If the provider is not already being launched, then get it
6921 // started.
6922 if (i >= N) {
6923 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006924
6925 try {
6926 // Content provider is now in use, its package can't be stopped.
6927 try {
6928 AppGlobals.getPackageManager().setPackageStoppedState(
6929 cpr.appInfo.packageName, false);
6930 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006931 } catch (IllegalArgumentException e) {
6932 Slog.w(TAG, "Failed trying to unstop package "
6933 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006934 }
6935
6936 ProcessRecord proc = startProcessLocked(cpi.processName,
6937 cpr.appInfo, false, 0, "content provider",
6938 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006939 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006940 if (proc == null) {
6941 Slog.w(TAG, "Unable to launch app "
6942 + cpi.applicationInfo.packageName + "/"
6943 + cpi.applicationInfo.uid + " for provider "
6944 + name + ": process is bad");
6945 return null;
6946 }
6947 cpr.launchingApp = proc;
6948 mLaunchingProviders.add(cpr);
6949 } finally {
6950 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006952 }
6953
6954 // Make sure the provider is published (the same provider class
6955 // may be published under multiple names).
6956 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006957 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006959 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006960 incProviderCount(r, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006961 }
6962 }
6963
6964 // Wait for the provider to be published...
6965 synchronized (cpr) {
6966 while (cpr.provider == null) {
6967 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006968 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 + cpi.applicationInfo.packageName + "/"
6970 + cpi.applicationInfo.uid + " for provider "
6971 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006972 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973 cpi.applicationInfo.packageName,
6974 cpi.applicationInfo.uid, name);
6975 return null;
6976 }
6977 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006978 if (DEBUG_MU) {
6979 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6980 + cpr.launchingApp);
6981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006982 cpr.wait();
6983 } catch (InterruptedException ex) {
6984 }
6985 }
6986 }
6987 return cpr;
6988 }
6989
6990 public final ContentProviderHolder getContentProvider(
6991 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006992 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006993 if (caller == null) {
6994 String msg = "null IApplicationThread when getting content provider "
6995 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006996 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006997 throw new SecurityException(msg);
6998 }
6999
Amith Yamasani742a6712011-05-04 14:49:28 -07007000 ContentProviderHolder contentProvider = getContentProviderImpl(caller, name);
7001 return contentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007002 }
7003
7004 private ContentProviderHolder getContentProviderExternal(String name) {
7005 return getContentProviderImpl(null, name);
7006 }
7007
7008 /**
7009 * Drop a content provider from a ProcessRecord's bookkeeping
7010 * @param cpr
7011 */
7012 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007013 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07007015 int userId = UserId.getUserId(Binder.getCallingUid());
7016 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007018 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08007019 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007020 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 return;
7022 }
7023 final ProcessRecord r = getRecordForAppLocked(caller);
7024 if (r == null) {
7025 throw new SecurityException(
7026 "Unable to find app for caller " + caller +
7027 " when removing content provider " + name);
7028 }
7029 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07007030 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07007031 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
7032 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
7033 + r.info.processName + " from process "
7034 + localCpr.appInfo.processName);
7035 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007036 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08007037 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007038 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007039 return;
7040 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07007041 if (decProviderCount(r, localCpr)) {
7042 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07007043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007045 }
7046 }
7047
7048 private void removeContentProviderExternal(String name) {
7049 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07007050 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
7051 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007052 if(cpr == null) {
7053 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08007054 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 return;
7056 }
7057
7058 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07007059 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07007060 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
7061 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007062 localCpr.externals--;
7063 if (localCpr.externals < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007064 Slog.e(TAG, "Externals < 0 for content provider " + localCpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007065 }
7066 updateOomAdjLocked();
7067 }
7068 }
7069
7070 public final void publishContentProviders(IApplicationThread caller,
7071 List<ContentProviderHolder> providers) {
7072 if (providers == null) {
7073 return;
7074 }
7075
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007076 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007077 synchronized(this) {
7078 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07007079 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007080 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 if (r == null) {
7082 throw new SecurityException(
7083 "Unable to find app for caller " + caller
7084 + " (pid=" + Binder.getCallingPid()
7085 + ") when publishing content providers");
7086 }
7087
7088 final long origId = Binder.clearCallingIdentity();
7089
7090 final int N = providers.size();
7091 for (int i=0; i<N; i++) {
7092 ContentProviderHolder src = providers.get(i);
7093 if (src == null || src.info == null || src.provider == null) {
7094 continue;
7095 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07007096 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07007097 if (DEBUG_MU)
7098 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007099 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07007100 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07007101 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007102 String names[] = dst.info.authority.split(";");
7103 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07007104 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007105 }
7106
7107 int NL = mLaunchingProviders.size();
7108 int j;
7109 for (j=0; j<NL; j++) {
7110 if (mLaunchingProviders.get(j) == dst) {
7111 mLaunchingProviders.remove(j);
7112 j--;
7113 NL--;
7114 }
7115 }
7116 synchronized (dst) {
7117 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07007118 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 dst.notifyAll();
7120 }
7121 updateOomAdjLocked(r);
7122 }
7123 }
7124
7125 Binder.restoreCallingIdentity(origId);
7126 }
7127 }
7128
7129 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07007130 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06007131 synchronized (mSelf) {
7132 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
7133 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08007134 if (providers != null) {
7135 for (int i=providers.size()-1; i>=0; i--) {
7136 ProviderInfo pi = (ProviderInfo)providers.get(i);
7137 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7138 Slog.w(TAG, "Not installing system proc provider " + pi.name
7139 + ": not system .apk");
7140 providers.remove(i);
7141 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08007142 }
7143 }
7144 }
Josh Bartel2ecce342010-02-25 10:55:48 -06007145 if (providers != null) {
7146 mSystemThread.installSystemProviders(providers);
7147 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007148
7149 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01007150
7151 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007152 }
7153
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007154 /**
7155 * Allows app to retrieve the MIME type of a URI without having permission
7156 * to access its content provider.
7157 *
7158 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
7159 *
7160 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
7161 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
7162 */
7163 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007164 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007165 final String name = uri.getAuthority();
7166 final long ident = Binder.clearCallingIdentity();
7167 ContentProviderHolder holder = null;
7168
7169 try {
7170 holder = getContentProviderExternal(name);
7171 if (holder != null) {
7172 return holder.provider.getType(uri);
7173 }
7174 } catch (RemoteException e) {
7175 Log.w(TAG, "Content provider dead retrieving " + uri, e);
7176 return null;
7177 } finally {
7178 if (holder != null) {
7179 removeContentProviderExternal(name);
7180 }
7181 Binder.restoreCallingIdentity(ident);
7182 }
7183
7184 return null;
7185 }
7186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 // =========================================================
7188 // GLOBAL MANAGEMENT
7189 // =========================================================
7190
7191 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007192 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007193 String proc = customProcess != null ? customProcess : info.processName;
7194 BatteryStatsImpl.Uid.Proc ps = null;
7195 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007196 int uid = info.uid;
7197 if (isolated) {
7198 int userId = UserId.getUserId(uid);
7199 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
7200 uid = 0;
7201 while (true) {
7202 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
7203 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
7204 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
7205 }
7206 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
7207 mNextIsolatedProcessUid++;
7208 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
7209 // No process for this uid, use it.
7210 break;
7211 }
7212 stepsLeft--;
7213 if (stepsLeft <= 0) {
7214 return null;
7215 }
7216 }
7217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007218 synchronized (stats) {
7219 ps = stats.getProcessStatsLocked(info.uid, proc);
7220 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007221 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007222 }
7223
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007224 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
7225 ProcessRecord app;
7226 if (!isolated) {
7227 app = getProcessRecordLocked(info.processName, info.uid);
7228 } else {
7229 app = null;
7230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007231
7232 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007233 app = newProcessRecordLocked(null, info, null, isolated);
7234 mProcessNames.put(info.processName, app.uid, app);
7235 if (isolated) {
7236 mIsolatedProcesses.put(app.uid, app);
7237 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007238 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007239 }
7240
Dianne Hackborne7f97212011-02-24 14:40:20 -08007241 // This package really, really can not be stopped.
7242 try {
7243 AppGlobals.getPackageManager().setPackageStoppedState(
7244 info.packageName, false);
7245 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007246 } catch (IllegalArgumentException e) {
7247 Slog.w(TAG, "Failed trying to unstop package "
7248 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007249 }
7250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007251 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7252 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7253 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007254 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 }
7256 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7257 mPersistentStartingProcesses.add(app);
7258 startProcessLocked(app, "added application", app.processName);
7259 }
7260
7261 return app;
7262 }
7263
7264 public void unhandledBack() {
7265 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7266 "unhandledBack()");
7267
7268 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007269 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007270 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007271 TAG, "Performing unhandledBack(): stack size = " + count);
7272 if (count > 1) {
7273 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007274 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007275 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
7276 Binder.restoreCallingIdentity(origId);
7277 }
7278 }
7279 }
7280
7281 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007282 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007283 String name = uri.getAuthority();
7284 ContentProviderHolder cph = getContentProviderExternal(name);
7285 ParcelFileDescriptor pfd = null;
7286 if (cph != null) {
7287 // We record the binder invoker's uid in thread-local storage before
7288 // going to the content provider to open the file. Later, in the code
7289 // that handles all permissions checks, we look for this uid and use
7290 // that rather than the Activity Manager's own uid. The effect is that
7291 // we do the check against the caller's permissions even though it looks
7292 // to the content provider like the Activity Manager itself is making
7293 // the request.
7294 sCallerIdentity.set(new Identity(
7295 Binder.getCallingPid(), Binder.getCallingUid()));
7296 try {
7297 pfd = cph.provider.openFile(uri, "r");
7298 } catch (FileNotFoundException e) {
7299 // do nothing; pfd will be returned null
7300 } finally {
7301 // Ensure that whatever happens, we clean up the identity state
7302 sCallerIdentity.remove();
7303 }
7304
7305 // We've got the fd now, so we're done with the provider.
7306 removeContentProviderExternal(name);
7307 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007308 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 }
7310 return pfd;
7311 }
7312
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007313 // Actually is sleeping or shutting down or whatever else in the future
7314 // is an inactive state.
7315 public boolean isSleeping() {
7316 return mSleeping || mShuttingDown;
7317 }
7318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007319 public void goingToSleep() {
7320 synchronized(this) {
7321 mSleeping = true;
7322 mWindowManager.setEventDispatching(false);
7323
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007324 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007325
7326 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07007327 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007328 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7329 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07007330 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007331 }
7332 }
7333
Dianne Hackborn55280a92009-05-07 15:53:46 -07007334 public boolean shutdown(int timeout) {
7335 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7336 != PackageManager.PERMISSION_GRANTED) {
7337 throw new SecurityException("Requires permission "
7338 + android.Manifest.permission.SHUTDOWN);
7339 }
7340
7341 boolean timedout = false;
7342
7343 synchronized(this) {
7344 mShuttingDown = true;
7345 mWindowManager.setEventDispatching(false);
7346
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007347 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007348 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007349 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007350 while (mMainStack.mResumedActivity != null
Dianne Hackborncbb722e2012-02-07 18:33:49 -08007351 || mMainStack.mPausingActivities.size() > 0) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007352 long delay = endTime - System.currentTimeMillis();
7353 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007354 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007355 timedout = true;
7356 break;
7357 }
7358 try {
7359 this.wait();
7360 } catch (InterruptedException e) {
7361 }
7362 }
7363 }
7364 }
7365
7366 mUsageStatsService.shutdown();
7367 mBatteryStatsService.shutdown();
7368
7369 return timedout;
7370 }
7371
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007372 public final void activitySlept(IBinder token) {
7373 if (localLOGV) Slog.v(
7374 TAG, "Activity slept: token=" + token);
7375
7376 ActivityRecord r = null;
7377
7378 final long origId = Binder.clearCallingIdentity();
7379
7380 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007381 r = mMainStack.isInStackLocked(token);
7382 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007383 mMainStack.activitySleptLocked(r);
7384 }
7385 }
7386
7387 Binder.restoreCallingIdentity(origId);
7388 }
7389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007390 public void wakingUp() {
7391 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 mWindowManager.setEventDispatching(true);
7393 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007394 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007395 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 }
7397 }
7398
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007399 public void stopAppSwitches() {
7400 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7401 != PackageManager.PERMISSION_GRANTED) {
7402 throw new SecurityException("Requires permission "
7403 + android.Manifest.permission.STOP_APP_SWITCHES);
7404 }
7405
7406 synchronized(this) {
7407 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7408 + APP_SWITCH_DELAY_TIME;
7409 mDidAppSwitch = false;
7410 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7411 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7412 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7413 }
7414 }
7415
7416 public void resumeAppSwitches() {
7417 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7418 != PackageManager.PERMISSION_GRANTED) {
7419 throw new SecurityException("Requires permission "
7420 + android.Manifest.permission.STOP_APP_SWITCHES);
7421 }
7422
7423 synchronized(this) {
7424 // Note that we don't execute any pending app switches... we will
7425 // let those wait until either the timeout, or the next start
7426 // activity request.
7427 mAppSwitchesAllowedTime = 0;
7428 }
7429 }
7430
7431 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7432 String name) {
7433 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7434 return true;
7435 }
7436
7437 final int perm = checkComponentPermission(
7438 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007439 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007440 if (perm == PackageManager.PERMISSION_GRANTED) {
7441 return true;
7442 }
7443
Joe Onorato8a9b2202010-02-26 18:56:32 -08007444 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007445 return false;
7446 }
7447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007448 public void setDebugApp(String packageName, boolean waitForDebugger,
7449 boolean persistent) {
7450 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7451 "setDebugApp()");
7452
7453 // Note that this is not really thread safe if there are multiple
7454 // callers into it at the same time, but that's not a situation we
7455 // care about.
7456 if (persistent) {
7457 final ContentResolver resolver = mContext.getContentResolver();
7458 Settings.System.putString(
7459 resolver, Settings.System.DEBUG_APP,
7460 packageName);
7461 Settings.System.putInt(
7462 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7463 waitForDebugger ? 1 : 0);
7464 }
7465
7466 synchronized (this) {
7467 if (!persistent) {
7468 mOrigDebugApp = mDebugApp;
7469 mOrigWaitForDebugger = mWaitForDebugger;
7470 }
7471 mDebugApp = packageName;
7472 mWaitForDebugger = waitForDebugger;
7473 mDebugTransient = !persistent;
7474 if (packageName != null) {
7475 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07007476 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007477 Binder.restoreCallingIdentity(origId);
7478 }
7479 }
7480 }
7481
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007482 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7483 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7484 synchronized (this) {
7485 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7486 if (!isDebuggable) {
7487 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7488 throw new SecurityException("Process not debuggable: " + app.packageName);
7489 }
7490 }
7491 mProfileApp = processName;
7492 mProfileFile = profileFile;
7493 if (mProfileFd != null) {
7494 try {
7495 mProfileFd.close();
7496 } catch (IOException e) {
7497 }
7498 mProfileFd = null;
7499 }
7500 mProfileFd = profileFd;
7501 mProfileType = 0;
7502 mAutoStopProfiler = autoStopProfiler;
7503 }
7504 }
7505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 public void setAlwaysFinish(boolean enabled) {
7507 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7508 "setAlwaysFinish()");
7509
7510 Settings.System.putInt(
7511 mContext.getContentResolver(),
7512 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7513
7514 synchronized (this) {
7515 mAlwaysFinishActivities = enabled;
7516 }
7517 }
7518
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007519 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007521 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007522 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007523 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007524 }
7525 }
7526
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007527 public boolean isUserAMonkey() {
7528 // For now the fact that there is a controller implies
7529 // we have a monkey.
7530 synchronized (this) {
7531 return mController != null;
7532 }
7533 }
7534
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007535 public void registerActivityWatcher(IActivityWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007536 enforceNotIsolatedCaller("registerActivityWatcher");
Josh Bartel2ecce342010-02-25 10:55:48 -06007537 synchronized (this) {
7538 mWatchers.register(watcher);
7539 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007540 }
7541
7542 public void unregisterActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06007543 synchronized (this) {
7544 mWatchers.unregister(watcher);
7545 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007546 }
7547
Jeff Sharkeya4620792011-05-20 15:29:23 -07007548 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007549 enforceNotIsolatedCaller("registerProcessObserver");
Jeff Sharkeya4620792011-05-20 15:29:23 -07007550 mProcessObservers.register(observer);
7551 }
7552
7553 public void unregisterProcessObserver(IProcessObserver observer) {
7554 mProcessObservers.unregister(observer);
7555 }
7556
Daniel Sandler69a48172010-06-23 16:29:36 -04007557 public void setImmersive(IBinder token, boolean immersive) {
7558 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007559 ActivityRecord r = mMainStack.isInStackLocked(token);
7560 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007561 throw new IllegalArgumentException();
7562 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007563 r.immersive = immersive;
7564 }
7565 }
7566
7567 public boolean isImmersive(IBinder token) {
7568 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007569 ActivityRecord r = mMainStack.isInStackLocked(token);
7570 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007571 throw new IllegalArgumentException();
7572 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007573 return r.immersive;
7574 }
7575 }
7576
7577 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007578 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007579 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007580 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007581 return (r != null) ? r.immersive : false;
7582 }
7583 }
7584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 public final void enterSafeMode() {
7586 synchronized(this) {
7587 // It only makes sense to do this before the system is ready
7588 // and started launching other packages.
7589 if (!mSystemReady) {
7590 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007591 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 } catch (RemoteException e) {
7593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 }
7595 }
7596 }
7597
Jeff Brownb09abc12011-01-13 21:08:27 -08007598 public final void showSafeModeOverlay() {
7599 View v = LayoutInflater.from(mContext).inflate(
7600 com.android.internal.R.layout.safe_mode, null);
7601 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7602 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7603 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7604 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7605 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7606 lp.format = v.getBackground().getOpacity();
7607 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7608 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7609 ((WindowManager)mContext.getSystemService(
7610 Context.WINDOW_SERVICE)).addView(v, lp);
7611 }
7612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613 public void noteWakeupAlarm(IIntentSender sender) {
7614 if (!(sender instanceof PendingIntentRecord)) {
7615 return;
7616 }
7617 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7618 synchronized (stats) {
7619 if (mBatteryStatsService.isOnBattery()) {
7620 mBatteryStatsService.enforceCallingPermission();
7621 PendingIntentRecord rec = (PendingIntentRecord)sender;
7622 int MY_UID = Binder.getCallingUid();
7623 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7624 BatteryStatsImpl.Uid.Pkg pkg =
7625 stats.getPackageStatsLocked(uid, rec.key.packageName);
7626 pkg.incWakeupsLocked();
7627 }
7628 }
7629 }
7630
Dianne Hackborn64825172011-03-02 21:32:58 -08007631 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007633 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007634 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007635 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 // XXX Note: don't acquire main activity lock here, because the window
7637 // manager calls in with its locks held.
7638
7639 boolean killed = false;
7640 synchronized (mPidsSelfLocked) {
7641 int[] types = new int[pids.length];
7642 int worstType = 0;
7643 for (int i=0; i<pids.length; i++) {
7644 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7645 if (proc != null) {
7646 int type = proc.setAdj;
7647 types[i] = type;
7648 if (type > worstType) {
7649 worstType = type;
7650 }
7651 }
7652 }
7653
Dianne Hackborn64825172011-03-02 21:32:58 -08007654 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007655 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007656 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7657 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007658 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007659 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007660
7661 // If this is not a secure call, don't let it kill processes that
7662 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007663 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7664 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007665 }
7666
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007667 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 for (int i=0; i<pids.length; i++) {
7669 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7670 if (proc == null) {
7671 continue;
7672 }
7673 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007674 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007675 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007676 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7677 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007679 proc.killedBackground = true;
7680 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007681 }
7682 }
7683 }
7684 return killed;
7685 }
7686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 public final void startRunning(String pkg, String cls, String action,
7688 String data) {
7689 synchronized(this) {
7690 if (mStartRunning) {
7691 return;
7692 }
7693 mStartRunning = true;
7694 mTopComponent = pkg != null && cls != null
7695 ? new ComponentName(pkg, cls) : null;
7696 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7697 mTopData = data;
7698 if (!mSystemReady) {
7699 return;
7700 }
7701 }
7702
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007703 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007704 }
7705
7706 private void retrieveSettings() {
7707 final ContentResolver resolver = mContext.getContentResolver();
7708 String debugApp = Settings.System.getString(
7709 resolver, Settings.System.DEBUG_APP);
7710 boolean waitForDebugger = Settings.System.getInt(
7711 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7712 boolean alwaysFinishActivities = Settings.System.getInt(
7713 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7714
7715 Configuration configuration = new Configuration();
7716 Settings.System.getConfiguration(resolver, configuration);
7717
7718 synchronized (this) {
7719 mDebugApp = mOrigDebugApp = debugApp;
7720 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7721 mAlwaysFinishActivities = alwaysFinishActivities;
7722 // This happens before any activities are started, so we can
7723 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007724 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007725 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 }
7727 }
7728
7729 public boolean testIsSystemReady() {
7730 // no need to synchronize(this) just to read & return the value
7731 return mSystemReady;
7732 }
7733
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007734 private static File getCalledPreBootReceiversFile() {
7735 File dataDir = Environment.getDataDirectory();
7736 File systemDir = new File(dataDir, "system");
7737 File fname = new File(systemDir, "called_pre_boots.dat");
7738 return fname;
7739 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007740
7741 static final int LAST_DONE_VERSION = 10000;
7742
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007743 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7744 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7745 File file = getCalledPreBootReceiversFile();
7746 FileInputStream fis = null;
7747 try {
7748 fis = new FileInputStream(file);
7749 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007750 int fvers = dis.readInt();
7751 if (fvers == LAST_DONE_VERSION) {
7752 String vers = dis.readUTF();
7753 String codename = dis.readUTF();
7754 String build = dis.readUTF();
7755 if (android.os.Build.VERSION.RELEASE.equals(vers)
7756 && android.os.Build.VERSION.CODENAME.equals(codename)
7757 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7758 int num = dis.readInt();
7759 while (num > 0) {
7760 num--;
7761 String pkg = dis.readUTF();
7762 String cls = dis.readUTF();
7763 lastDoneReceivers.add(new ComponentName(pkg, cls));
7764 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007765 }
7766 }
7767 } catch (FileNotFoundException e) {
7768 } catch (IOException e) {
7769 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7770 } finally {
7771 if (fis != null) {
7772 try {
7773 fis.close();
7774 } catch (IOException e) {
7775 }
7776 }
7777 }
7778 return lastDoneReceivers;
7779 }
7780
7781 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7782 File file = getCalledPreBootReceiversFile();
7783 FileOutputStream fos = null;
7784 DataOutputStream dos = null;
7785 try {
7786 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7787 fos = new FileOutputStream(file);
7788 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007789 dos.writeInt(LAST_DONE_VERSION);
7790 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007791 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007792 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007793 dos.writeInt(list.size());
7794 for (int i=0; i<list.size(); i++) {
7795 dos.writeUTF(list.get(i).getPackageName());
7796 dos.writeUTF(list.get(i).getClassName());
7797 }
7798 } catch (IOException e) {
7799 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7800 file.delete();
7801 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007802 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007803 if (dos != null) {
7804 try {
7805 dos.close();
7806 } catch (IOException e) {
7807 // TODO Auto-generated catch block
7808 e.printStackTrace();
7809 }
7810 }
7811 }
7812 }
7813
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007814 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 synchronized(this) {
7816 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007817 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 return;
7819 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007820
7821 // Check to see if there are any update receivers to run.
7822 if (!mDidUpdate) {
7823 if (mWaitingUpdate) {
7824 return;
7825 }
7826 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7827 List<ResolveInfo> ris = null;
7828 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007829 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007830 intent, null, 0);
7831 } catch (RemoteException e) {
7832 }
7833 if (ris != null) {
7834 for (int i=ris.size()-1; i>=0; i--) {
7835 if ((ris.get(i).activityInfo.applicationInfo.flags
7836 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7837 ris.remove(i);
7838 }
7839 }
7840 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007841
7842 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7843
7844 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007845 for (int i=0; i<ris.size(); i++) {
7846 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007847 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7848 if (lastDoneReceivers.contains(comp)) {
7849 ris.remove(i);
7850 i--;
7851 }
7852 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007853
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007854 for (int i=0; i<ris.size(); i++) {
7855 ActivityInfo ai = ris.get(i).activityInfo;
7856 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7857 doneReceivers.add(comp);
7858 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007859 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007860 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007861 finisher = new IIntentReceiver.Stub() {
7862 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007863 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007864 boolean sticky) {
7865 // The raw IIntentReceiver interface is called
7866 // with the AM lock held, so redispatch to
7867 // execute our code without the lock.
7868 mHandler.post(new Runnable() {
7869 public void run() {
7870 synchronized (ActivityManagerService.this) {
7871 mDidUpdate = true;
7872 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007873 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007874 showBootMessage(mContext.getText(
7875 R.string.android_upgrading_complete),
7876 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007877 systemReady(goingCallback);
7878 }
7879 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007880 }
7881 };
7882 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007883 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007884 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007885 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007886 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7887 Process.SYSTEM_UID);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007888 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007889 mWaitingUpdate = true;
7890 }
7891 }
7892 }
7893 if (mWaitingUpdate) {
7894 return;
7895 }
7896 mDidUpdate = true;
7897 }
7898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 mSystemReady = true;
7900 if (!mStartRunning) {
7901 return;
7902 }
7903 }
7904
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007905 ArrayList<ProcessRecord> procsToKill = null;
7906 synchronized(mPidsSelfLocked) {
7907 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7908 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7909 if (!isAllowedWhileBooting(proc.info)){
7910 if (procsToKill == null) {
7911 procsToKill = new ArrayList<ProcessRecord>();
7912 }
7913 procsToKill.add(proc);
7914 }
7915 }
7916 }
7917
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007918 synchronized(this) {
7919 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007920 for (int i=procsToKill.size()-1; i>=0; i--) {
7921 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007922 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007923 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007924 }
7925 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007926
7927 // Now that we have cleaned up any update processes, we
7928 // are ready to start launching real processes and know that
7929 // we won't trample on them any more.
7930 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007931 }
7932
Joe Onorato8a9b2202010-02-26 18:56:32 -08007933 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007934 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007935 SystemClock.uptimeMillis());
7936
7937 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007938 // Make sure we have no pre-ready processes sitting around.
7939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007940 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7941 ResolveInfo ri = mContext.getPackageManager()
7942 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007943 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944 CharSequence errorMsg = null;
7945 if (ri != null) {
7946 ActivityInfo ai = ri.activityInfo;
7947 ApplicationInfo app = ai.applicationInfo;
7948 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7949 mTopAction = Intent.ACTION_FACTORY_TEST;
7950 mTopData = null;
7951 mTopComponent = new ComponentName(app.packageName,
7952 ai.name);
7953 } else {
7954 errorMsg = mContext.getResources().getText(
7955 com.android.internal.R.string.factorytest_not_system);
7956 }
7957 } else {
7958 errorMsg = mContext.getResources().getText(
7959 com.android.internal.R.string.factorytest_no_action);
7960 }
7961 if (errorMsg != null) {
7962 mTopAction = null;
7963 mTopData = null;
7964 mTopComponent = null;
7965 Message msg = Message.obtain();
7966 msg.what = SHOW_FACTORY_ERROR_MSG;
7967 msg.getData().putCharSequence("msg", errorMsg);
7968 mHandler.sendMessage(msg);
7969 }
7970 }
7971 }
7972
7973 retrieveSettings();
7974
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007975 if (goingCallback != null) goingCallback.run();
7976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007977 synchronized (this) {
7978 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7979 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007980 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007981 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 if (apps != null) {
7983 int N = apps.size();
7984 int i;
7985 for (i=0; i<N; i++) {
7986 ApplicationInfo info
7987 = (ApplicationInfo)apps.get(i);
7988 if (info != null &&
7989 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007990 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 }
7992 }
7993 }
7994 } catch (RemoteException ex) {
7995 // pm is in same process, this will never happen.
7996 }
7997 }
7998
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007999 // Start up initial activity.
8000 mBooting = true;
8001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008002 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008003 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008004 Message msg = Message.obtain();
8005 msg.what = SHOW_UID_ERROR_MSG;
8006 mHandler.sendMessage(msg);
8007 }
8008 } catch (RemoteException e) {
8009 }
8010
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008011 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 }
8013 }
8014
Dan Egnorb7f03672009-12-09 16:22:32 -08008015 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008016 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008018 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008019 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008020 startAppProblemLocked(app);
8021 app.stopFreezingAllLocked();
8022 return handleAppCrashLocked(app);
8023 }
8024
Dan Egnorb7f03672009-12-09 16:22:32 -08008025 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008026 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008028 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008029 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
8030 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 startAppProblemLocked(app);
8032 app.stopFreezingAllLocked();
8033 }
8034
8035 /**
8036 * Generate a process error record, suitable for attachment to a ProcessRecord.
8037 *
8038 * @param app The ProcessRecord in which the error occurred.
8039 * @param condition Crashing, Application Not Responding, etc. Values are defined in
8040 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08008041 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008042 * @param shortMsg Short message describing the crash.
8043 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08008044 * @param stackTrace Full crash stack trace, may be null.
8045 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008046 * @return Returns a fully-formed AppErrorStateInfo record.
8047 */
8048 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008049 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008050 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08008051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008052 report.condition = condition;
8053 report.processName = app.processName;
8054 report.pid = app.pid;
8055 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08008056 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 report.shortMsg = shortMsg;
8058 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08008059 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060
8061 return report;
8062 }
8063
Dan Egnor42471dd2010-01-07 17:25:22 -08008064 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008065 synchronized (this) {
8066 app.crashing = false;
8067 app.crashingReport = null;
8068 app.notResponding = false;
8069 app.notRespondingReport = null;
8070 if (app.anrDialog == fromDialog) {
8071 app.anrDialog = null;
8072 }
8073 if (app.waitDialog == fromDialog) {
8074 app.waitDialog = null;
8075 }
8076 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008077 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008078 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07008079 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
8080 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008081 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 }
8084 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008085
Dan Egnorb7f03672009-12-09 16:22:32 -08008086 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 long now = SystemClock.uptimeMillis();
8088
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008089 Long crashTime;
8090 if (!app.isolated) {
8091 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
8092 } else {
8093 crashTime = null;
8094 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07008095 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008096 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008097 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008098 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008099 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008100 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008101 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
8102 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008104 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008105 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008106 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008107 }
8108 }
8109 if (!app.persistent) {
8110 // We don't want to start this process again until the user
8111 // explicitly does so... but for persistent process, we really
8112 // need to keep it running. If a persistent process is actually
8113 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008114 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008115 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008116 if (!app.isolated) {
8117 // XXX We don't have a way to mark isolated processes
8118 // as bad, since they don't have a peristent identity.
8119 mBadProcesses.put(app.info.processName, app.uid, now);
8120 mProcessCrashTimes.remove(app.info.processName, app.uid);
8121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008123 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008124 // Don't let services in this process be restarted and potentially
8125 // annoy the user repeatedly. Unless it is persistent, since those
8126 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008127 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008128 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008129 return false;
8130 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008131 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008132 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008133 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008134 if (r.app == app) {
8135 // If the top running activity is from this crashing
8136 // process, then terminate it to avoid getting in a loop.
8137 Slog.w(TAG, " Force finishing activity "
8138 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008139 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008140 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008141 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08008142 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008143 // stopped, to avoid a situation where one will get
8144 // re-start our crashing activity once it gets resumed again.
8145 index--;
8146 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008147 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008148 if (r.state == ActivityState.RESUMED
8149 || r.state == ActivityState.PAUSING
8150 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008151 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008152 Slog.w(TAG, " Force finishing activity "
8153 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008154 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008155 Activity.RESULT_CANCELED, null, "crashed");
8156 }
8157 }
8158 }
8159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 }
8161
8162 // Bump up the crash count of any services currently running in the proc.
8163 if (app.services.size() != 0) {
8164 // Any services running in the application need to be placed
8165 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008166 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008167 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008168 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008169 sr.crashCount++;
8170 }
8171 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008172
8173 // If the crashing process is what we consider to be the "home process" and it has been
8174 // replaced by a third-party app, clear the package preferred activities from packages
8175 // with a home activity running in the process to prevent a repeatedly crashing app
8176 // from blocking the user to manually clear the list.
8177 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8178 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8179 Iterator it = mHomeProcess.activities.iterator();
8180 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008181 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008182 if (r.isHomeActivity) {
8183 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8184 try {
8185 ActivityThread.getPackageManager()
8186 .clearPackagePreferredActivities(r.packageName);
8187 } catch (RemoteException c) {
8188 // pm is in same process, this will never happen.
8189 }
8190 }
8191 }
8192 }
8193
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008194 if (!app.isolated) {
8195 // XXX Can't keep track of crash times for isolated processes,
8196 // because they don't have a perisistent identity.
8197 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8198 }
8199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008200 return true;
8201 }
8202
8203 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008204 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8205 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008206 skipCurrentReceiverLocked(app);
8207 }
8208
8209 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008210 for (BroadcastQueue queue : mBroadcastQueues) {
8211 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008212 }
8213 }
8214
Dan Egnor60d87622009-12-16 16:32:58 -08008215 /**
8216 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8217 * The application process will exit immediately after this call returns.
8218 * @param app object of the crashing app, null for the system server
8219 * @param crashInfo describing the exception
8220 */
8221 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008222 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008223 final String processName = app == null ? "system_server"
8224 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008225
8226 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008227 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008228 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008229 crashInfo.exceptionClassName,
8230 crashInfo.exceptionMessage,
8231 crashInfo.throwFileName,
8232 crashInfo.throwLineNumber);
8233
Jeff Sharkeya353d262011-10-28 11:12:06 -07008234 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008235
8236 crashApplication(r, crashInfo);
8237 }
8238
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008239 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008240 IBinder app,
8241 int violationMask,
8242 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008243 ProcessRecord r = findAppProcess(app, "StrictMode");
8244 if (r == null) {
8245 return;
8246 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008247
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008248 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008249 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008250 boolean logIt = true;
8251 synchronized (mAlreadyLoggedViolatedStacks) {
8252 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8253 logIt = false;
8254 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008255 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008256 // the relative pain numbers, without logging all
8257 // the stack traces repeatedly. We'd want to do
8258 // likewise in the client code, which also does
8259 // dup suppression, before the Binder call.
8260 } else {
8261 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8262 mAlreadyLoggedViolatedStacks.clear();
8263 }
8264 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8265 }
8266 }
8267 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008268 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008269 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008270 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008271
8272 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8273 AppErrorResult result = new AppErrorResult();
8274 synchronized (this) {
8275 final long origId = Binder.clearCallingIdentity();
8276
8277 Message msg = Message.obtain();
8278 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8279 HashMap<String, Object> data = new HashMap<String, Object>();
8280 data.put("result", result);
8281 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008282 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008283 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008284 msg.obj = data;
8285 mHandler.sendMessage(msg);
8286
8287 Binder.restoreCallingIdentity(origId);
8288 }
8289 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008290 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008291 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008292 }
8293
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008294 // Depending on the policy in effect, there could be a bunch of
8295 // these in quick succession so we try to batch these together to
8296 // minimize disk writes, number of dropbox entries, and maximize
8297 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008298 private void logStrictModeViolationToDropBox(
8299 ProcessRecord process,
8300 StrictMode.ViolationInfo info) {
8301 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008302 return;
8303 }
8304 final boolean isSystemApp = process == null ||
8305 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8306 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008307 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008308 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8309 final DropBoxManager dbox = (DropBoxManager)
8310 mContext.getSystemService(Context.DROPBOX_SERVICE);
8311
8312 // Exit early if the dropbox isn't configured to accept this report type.
8313 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8314
8315 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008316 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008317 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8318 synchronized (sb) {
8319 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008320 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008321 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8322 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008323 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8324 if (info.violationNumThisLoop != 0) {
8325 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8326 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008327 if (info.numAnimationsRunning != 0) {
8328 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8329 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008330 if (info.broadcastIntentAction != null) {
8331 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8332 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008333 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008334 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008335 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008336 if (info.numInstances != -1) {
8337 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8338 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008339 if (info.tags != null) {
8340 for (String tag : info.tags) {
8341 sb.append("Span-Tag: ").append(tag).append("\n");
8342 }
8343 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008344 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008345 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8346 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008347 }
8348 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008349
8350 // Only buffer up to ~64k. Various logging bits truncate
8351 // things at 128k.
8352 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008353 }
8354
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008355 // Flush immediately if the buffer's grown too large, or this
8356 // is a non-system app. Non-system apps are isolated with a
8357 // different tag & policy and not batched.
8358 //
8359 // Batching is useful during internal testing with
8360 // StrictMode settings turned up high. Without batching,
8361 // thousands of separate files could be created on boot.
8362 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008363 new Thread("Error dump: " + dropboxTag) {
8364 @Override
8365 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008366 String report;
8367 synchronized (sb) {
8368 report = sb.toString();
8369 sb.delete(0, sb.length());
8370 sb.trimToSize();
8371 }
8372 if (report.length() != 0) {
8373 dbox.addText(dropboxTag, report);
8374 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008375 }
8376 }.start();
8377 return;
8378 }
8379
8380 // System app batching:
8381 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008382 // An existing dropbox-writing thread is outstanding, so
8383 // we don't need to start it up. The existing thread will
8384 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008385 return;
8386 }
8387
8388 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8389 // (After this point, we shouldn't access AMS internal data structures.)
8390 new Thread("Error dump: " + dropboxTag) {
8391 @Override
8392 public void run() {
8393 // 5 second sleep to let stacks arrive and be batched together
8394 try {
8395 Thread.sleep(5000); // 5 seconds
8396 } catch (InterruptedException e) {}
8397
8398 String errorReport;
8399 synchronized (mStrictModeBuffer) {
8400 errorReport = mStrictModeBuffer.toString();
8401 if (errorReport.length() == 0) {
8402 return;
8403 }
8404 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8405 mStrictModeBuffer.trimToSize();
8406 }
8407 dbox.addText(dropboxTag, errorReport);
8408 }
8409 }.start();
8410 }
8411
Dan Egnor60d87622009-12-16 16:32:58 -08008412 /**
8413 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8414 * @param app object of the crashing app, null for the system server
8415 * @param tag reported by the caller
8416 * @param crashInfo describing the context of the error
8417 * @return true if the process should exit immediately (WTF is fatal)
8418 */
8419 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008420 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008421 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008422 final String processName = app == null ? "system_server"
8423 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008424
8425 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008426 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008427 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008428 tag, crashInfo.exceptionMessage);
8429
Jeff Sharkeya353d262011-10-28 11:12:06 -07008430 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008431
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008432 if (r != null && r.pid != Process.myPid() &&
8433 Settings.Secure.getInt(mContext.getContentResolver(),
8434 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008435 crashApplication(r, crashInfo);
8436 return true;
8437 } else {
8438 return false;
8439 }
8440 }
8441
8442 /**
8443 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8444 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8445 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008446 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008447 if (app == null) {
8448 return null;
8449 }
8450
8451 synchronized (this) {
8452 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8453 final int NA = apps.size();
8454 for (int ia=0; ia<NA; ia++) {
8455 ProcessRecord p = apps.valueAt(ia);
8456 if (p.thread != null && p.thread.asBinder() == app) {
8457 return p;
8458 }
8459 }
8460 }
8461
Dianne Hackborncb44d962011-03-10 17:02:27 -08008462 Slog.w(TAG, "Can't find mystery application for " + reason
8463 + " from pid=" + Binder.getCallingPid()
8464 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008465 return null;
8466 }
8467 }
8468
8469 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008470 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8471 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008472 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008473 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8474 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008475 // Watchdog thread ends up invoking this function (with
8476 // a null ProcessRecord) to add the stack file to dropbox.
8477 // Do not acquire a lock on this (am) in such cases, as it
8478 // could cause a potential deadlock, if and when watchdog
8479 // is invoked due to unavailability of lock on am and it
8480 // would prevent watchdog from killing system_server.
8481 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008482 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008483 return;
8484 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008485 // Note: ProcessRecord 'process' is guarded by the service
8486 // instance. (notably process.pkgList, which could otherwise change
8487 // concurrently during execution of this method)
8488 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008489 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008490 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008491 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008492 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8493 for (String pkg : process.pkgList) {
8494 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008495 try {
Dan Egnora455d192010-03-12 08:52:28 -08008496 PackageInfo pi = pm.getPackageInfo(pkg, 0);
8497 if (pi != null) {
8498 sb.append(" v").append(pi.versionCode);
8499 if (pi.versionName != null) {
8500 sb.append(" (").append(pi.versionName).append(")");
8501 }
8502 }
8503 } catch (RemoteException e) {
8504 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008505 }
Dan Egnora455d192010-03-12 08:52:28 -08008506 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008507 }
Dan Egnora455d192010-03-12 08:52:28 -08008508 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008509 }
8510
8511 private static String processClass(ProcessRecord process) {
8512 if (process == null || process.pid == MY_PID) {
8513 return "system_server";
8514 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8515 return "system_app";
8516 } else {
8517 return "data_app";
8518 }
8519 }
8520
8521 /**
8522 * Write a description of an error (crash, WTF, ANR) to the drop box.
8523 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8524 * @param process which caused the error, null means the system server
8525 * @param activity which triggered the error, null if unknown
8526 * @param parent activity related to the error, null if unknown
8527 * @param subject line related to the error, null if absent
8528 * @param report in long form describing the error, null if absent
8529 * @param logFile to include in the report, null if none
8530 * @param crashInfo giving an application stack trace, null if absent
8531 */
8532 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008533 ProcessRecord process, String processName, ActivityRecord activity,
8534 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008535 final String report, final File logFile,
8536 final ApplicationErrorReport.CrashInfo crashInfo) {
8537 // NOTE -- this must never acquire the ActivityManagerService lock,
8538 // otherwise the watchdog may be prevented from resetting the system.
8539
8540 final String dropboxTag = processClass(process) + "_" + eventType;
8541 final DropBoxManager dbox = (DropBoxManager)
8542 mContext.getSystemService(Context.DROPBOX_SERVICE);
8543
8544 // Exit early if the dropbox isn't configured to accept this report type.
8545 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8546
8547 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008548 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008549 if (activity != null) {
8550 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8551 }
8552 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8553 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8554 }
8555 if (parent != null && parent != activity) {
8556 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8557 }
8558 if (subject != null) {
8559 sb.append("Subject: ").append(subject).append("\n");
8560 }
8561 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008562 if (Debug.isDebuggerConnected()) {
8563 sb.append("Debugger: Connected\n");
8564 }
Dan Egnora455d192010-03-12 08:52:28 -08008565 sb.append("\n");
8566
8567 // Do the rest in a worker thread to avoid blocking the caller on I/O
8568 // (After this point, we shouldn't access AMS internal data structures.)
8569 Thread worker = new Thread("Error dump: " + dropboxTag) {
8570 @Override
8571 public void run() {
8572 if (report != null) {
8573 sb.append(report);
8574 }
8575 if (logFile != null) {
8576 try {
8577 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8578 } catch (IOException e) {
8579 Slog.e(TAG, "Error reading " + logFile, e);
8580 }
8581 }
8582 if (crashInfo != null && crashInfo.stackTrace != null) {
8583 sb.append(crashInfo.stackTrace);
8584 }
8585
8586 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8587 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8588 if (lines > 0) {
8589 sb.append("\n");
8590
8591 // Merge several logcat streams, and take the last N lines
8592 InputStreamReader input = null;
8593 try {
8594 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8595 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8596 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8597
8598 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8599 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8600 input = new InputStreamReader(logcat.getInputStream());
8601
8602 int num;
8603 char[] buf = new char[8192];
8604 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8605 } catch (IOException e) {
8606 Slog.e(TAG, "Error running logcat", e);
8607 } finally {
8608 if (input != null) try { input.close(); } catch (IOException e) {}
8609 }
8610 }
8611
8612 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008613 }
Dan Egnora455d192010-03-12 08:52:28 -08008614 };
8615
8616 if (process == null || process.pid == MY_PID) {
8617 worker.run(); // We may be about to die -- need to run this synchronously
8618 } else {
8619 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008620 }
8621 }
8622
8623 /**
8624 * Bring up the "unexpected error" dialog box for a crashing app.
8625 * Deal with edge cases (intercepts from instrumented applications,
8626 * ActivityController, error intent receivers, that sort of thing).
8627 * @param r the application crashing
8628 * @param crashInfo describing the failure
8629 */
8630 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008631 long timeMillis = System.currentTimeMillis();
8632 String shortMsg = crashInfo.exceptionClassName;
8633 String longMsg = crashInfo.exceptionMessage;
8634 String stackTrace = crashInfo.stackTrace;
8635 if (shortMsg != null && longMsg != null) {
8636 longMsg = shortMsg + ": " + longMsg;
8637 } else if (shortMsg != null) {
8638 longMsg = shortMsg;
8639 }
8640
Dan Egnor60d87622009-12-16 16:32:58 -08008641 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008642 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008643 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 try {
8645 String name = r != null ? r.processName : null;
8646 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008647 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008648 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008649 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 + " at watcher's request");
8651 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008652 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008653 }
8654 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008655 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 }
8657 }
8658
8659 final long origId = Binder.clearCallingIdentity();
8660
8661 // If this process is running instrumentation, finish it.
8662 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008663 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008665 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8666 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008667 Bundle info = new Bundle();
8668 info.putString("shortMsg", shortMsg);
8669 info.putString("longMsg", longMsg);
8670 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8671 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008672 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008673 }
8674
Dan Egnor60d87622009-12-16 16:32:58 -08008675 // If we can't identify the process or it's already exceeded its crash quota,
8676 // quit right away without showing a crash dialog.
8677 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008679 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 }
8681
8682 Message msg = Message.obtain();
8683 msg.what = SHOW_ERROR_MSG;
8684 HashMap data = new HashMap();
8685 data.put("result", result);
8686 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008687 msg.obj = data;
8688 mHandler.sendMessage(msg);
8689
8690 Binder.restoreCallingIdentity(origId);
8691 }
8692
8693 int res = result.get();
8694
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008695 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008697 if (r != null && !r.isolated) {
8698 // XXX Can't keep track of crash time for isolated processes,
8699 // since they don't have a persistent identity.
8700 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701 SystemClock.uptimeMillis());
8702 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008703 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008704 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008705 }
8706 }
8707
8708 if (appErrorIntent != null) {
8709 try {
8710 mContext.startActivity(appErrorIntent);
8711 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008712 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008715 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008716
8717 Intent createAppErrorIntentLocked(ProcessRecord r,
8718 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8719 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008720 if (report == null) {
8721 return null;
8722 }
8723 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8724 result.setComponent(r.errorReportReceiver);
8725 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8726 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8727 return result;
8728 }
8729
Dan Egnorb7f03672009-12-09 16:22:32 -08008730 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8731 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008732 if (r.errorReportReceiver == null) {
8733 return null;
8734 }
8735
8736 if (!r.crashing && !r.notResponding) {
8737 return null;
8738 }
8739
Dan Egnorb7f03672009-12-09 16:22:32 -08008740 ApplicationErrorReport report = new ApplicationErrorReport();
8741 report.packageName = r.info.packageName;
8742 report.installerPackageName = r.errorReportReceiver.getPackageName();
8743 report.processName = r.processName;
8744 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008745 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008746
Dan Egnorb7f03672009-12-09 16:22:32 -08008747 if (r.crashing) {
8748 report.type = ApplicationErrorReport.TYPE_CRASH;
8749 report.crashInfo = crashInfo;
8750 } else if (r.notResponding) {
8751 report.type = ApplicationErrorReport.TYPE_ANR;
8752 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008753
Dan Egnorb7f03672009-12-09 16:22:32 -08008754 report.anrInfo.activity = r.notRespondingReport.tag;
8755 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8756 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008757 }
8758
Dan Egnorb7f03672009-12-09 16:22:32 -08008759 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008760 }
8761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008762 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008763 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008764 // assume our apps are happy - lazy create the list
8765 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8766
8767 synchronized (this) {
8768
8769 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008770 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8771 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008772 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8773 // This one's in trouble, so we'll generate a report for it
8774 // crashes are higher priority (in case there's a crash *and* an anr)
8775 ActivityManager.ProcessErrorStateInfo report = null;
8776 if (app.crashing) {
8777 report = app.crashingReport;
8778 } else if (app.notResponding) {
8779 report = app.notRespondingReport;
8780 }
8781
8782 if (report != null) {
8783 if (errList == null) {
8784 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8785 }
8786 errList.add(report);
8787 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008788 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008789 " crashing = " + app.crashing +
8790 " notResponding = " + app.notResponding);
8791 }
8792 }
8793 }
8794 }
8795
8796 return errList;
8797 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008798
8799 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008800 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008801 if (currApp != null) {
8802 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8803 }
8804 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008805 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8806 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008807 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8808 if (currApp != null) {
8809 currApp.lru = 0;
8810 }
8811 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008812 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008813 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8814 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8815 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8816 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8817 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8818 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8819 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8820 } else {
8821 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8822 }
8823 }
8824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008825 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008826 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008827 // Lazy instantiation of list
8828 List<ActivityManager.RunningAppProcessInfo> runList = null;
8829 synchronized (this) {
8830 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008831 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8832 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008833 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8834 // Generate process state info for running application
8835 ActivityManager.RunningAppProcessInfo currApp =
8836 new ActivityManager.RunningAppProcessInfo(app.processName,
8837 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07008838 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07008839 if (mHeavyWeightProcess == app) {
Dianne Hackborn482566e2010-09-03 12:51:28 -07008840 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07008841 }
Dianne Hackborn42499172010-10-15 18:45:07 -07008842 if (app.persistent) {
8843 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 int adj = app.curAdj;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008846 currApp.importance = oomAdjToImportance(adj, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008847 currApp.importanceReasonCode = app.adjTypeCode;
8848 if (app.adjSource instanceof ProcessRecord) {
8849 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008850 currApp.importanceReasonImportance = oomAdjToImportance(
8851 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008852 } else if (app.adjSource instanceof ActivityRecord) {
8853 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008854 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8855 }
8856 if (app.adjTarget instanceof ComponentName) {
8857 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8858 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008859 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008860 // + " lru=" + currApp.lru);
8861 if (runList == null) {
8862 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8863 }
8864 runList.add(currApp);
8865 }
8866 }
8867 }
8868 return runList;
8869 }
8870
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008871 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008872 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008873 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8874 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8875 if (runningApps != null && runningApps.size() > 0) {
8876 Set<String> extList = new HashSet<String>();
8877 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8878 if (app.pkgList != null) {
8879 for (String pkg : app.pkgList) {
8880 extList.add(pkg);
8881 }
8882 }
8883 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008884 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008885 for (String pkg : extList) {
8886 try {
8887 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8888 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8889 retList.add(info);
8890 }
8891 } catch (RemoteException e) {
8892 }
8893 }
8894 }
8895 return retList;
8896 }
8897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008898 @Override
8899 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008900 if (checkCallingPermission(android.Manifest.permission.DUMP)
8901 != PackageManager.PERMISSION_GRANTED) {
8902 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8903 + Binder.getCallingPid()
8904 + ", uid=" + Binder.getCallingUid()
8905 + " without permission "
8906 + android.Manifest.permission.DUMP);
8907 return;
8908 }
8909
8910 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008911 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008912 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008913
8914 int opti = 0;
8915 while (opti < args.length) {
8916 String opt = args[opti];
8917 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8918 break;
8919 }
8920 opti++;
8921 if ("-a".equals(opt)) {
8922 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008923 } else if ("-c".equals(opt)) {
8924 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008925 } else if ("-h".equals(opt)) {
8926 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008927 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008928 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008929 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008930 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8931 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8932 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008933 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008934 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008935 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008936 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008937 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008938 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008939 pw.println(" all: dump all activities");
8940 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008941 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008942 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8943 pw.println(" a partial substring in a component name, a");
8944 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008945 pw.println(" -a: include all available server state.");
8946 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008948 } else {
8949 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008950 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008951 }
8952
8953 // Is the caller requesting to dump a particular piece of data?
8954 if (opti < args.length) {
8955 String cmd = args[opti];
8956 opti++;
8957 if ("activities".equals(cmd) || "a".equals(cmd)) {
8958 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008959 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008961 return;
8962 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008963 String[] newArgs;
8964 String name;
8965 if (opti >= args.length) {
8966 name = null;
8967 newArgs = EMPTY_STRING_ARRAY;
8968 } else {
8969 name = args[opti];
8970 opti++;
8971 newArgs = new String[args.length - opti];
8972 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8973 args.length - opti);
8974 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008975 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008976 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008977 }
8978 return;
8979 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008980 String[] newArgs;
8981 String name;
8982 if (opti >= args.length) {
8983 name = null;
8984 newArgs = EMPTY_STRING_ARRAY;
8985 } else {
8986 name = args[opti];
8987 opti++;
8988 newArgs = new String[args.length - opti];
8989 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8990 args.length - opti);
8991 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008992 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008993 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008994 }
8995 return;
8996 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008997 String[] newArgs;
8998 String name;
8999 if (opti >= args.length) {
9000 name = null;
9001 newArgs = EMPTY_STRING_ARRAY;
9002 } else {
9003 name = args[opti];
9004 opti++;
9005 newArgs = new String[args.length - opti];
9006 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9007 args.length - opti);
9008 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009009 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009010 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009011 }
9012 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009013 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
9014 synchronized (this) {
9015 dumpOomLocked(fd, pw, args, opti, true);
9016 }
9017 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08009018 } else if ("provider".equals(cmd)) {
9019 String[] newArgs;
9020 String name;
9021 if (opti >= args.length) {
9022 name = null;
9023 newArgs = EMPTY_STRING_ARRAY;
9024 } else {
9025 name = args[opti];
9026 opti++;
9027 newArgs = new String[args.length - opti];
9028 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9029 }
9030 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
9031 pw.println("No providers match: " + name);
9032 pw.println("Use -h for help.");
9033 }
9034 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009035 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9036 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009037 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009038 }
9039 return;
9040 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009041 String[] newArgs;
9042 String name;
9043 if (opti >= args.length) {
9044 name = null;
9045 newArgs = EMPTY_STRING_ARRAY;
9046 } else {
9047 name = args[opti];
9048 opti++;
9049 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009050 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9051 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009052 }
9053 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
9054 pw.println("No services match: " + name);
9055 pw.println("Use -h for help.");
9056 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009057 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009058 } else if ("package".equals(cmd)) {
9059 String[] newArgs;
9060 if (opti >= args.length) {
9061 pw.println("package: no package name specified");
9062 pw.println("Use -h for help.");
9063 return;
9064 } else {
9065 dumpPackage = args[opti];
9066 opti++;
9067 newArgs = new String[args.length - opti];
9068 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9069 args.length - opti);
9070 args = newArgs;
9071 opti = 0;
9072 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009073 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9074 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009075 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009076 }
9077 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07009078 } else {
9079 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009080 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
9081 pw.println("Bad activity command, or no activities match: " + cmd);
9082 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009083 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009084 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009085 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009086 }
9087
9088 // No piece of data specified, dump everything.
9089 synchronized (this) {
9090 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009091 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009092 if (needSep) {
9093 pw.println(" ");
9094 }
9095 if (dumpAll) {
9096 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009097 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009098 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009099 if (needSep) {
9100 pw.println(" ");
9101 }
9102 if (dumpAll) {
9103 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009104 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009105 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009106 if (needSep) {
9107 pw.println(" ");
9108 }
9109 if (dumpAll) {
9110 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009111 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009112 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009113 if (needSep) {
9114 pw.println(" ");
9115 }
9116 if (dumpAll) {
9117 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009118 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009119 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009120 if (needSep) {
9121 pw.println(" ");
9122 }
9123 if (dumpAll) {
9124 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009125 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009126 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009127 }
9128 }
9129
9130 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009131 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009132 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9133 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009134 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9135 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009136 pw.println(" ");
9137 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009138 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9139 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009140 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009141 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009142 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009143 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009144 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009145 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009146 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009148 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009149 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009150 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009151 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009152 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9153 pw.println(" ");
9154 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009155 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009156 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009157 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009158 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009159 pw.println(" ");
9160 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009161 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009162 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009164
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009165 pw.println(" ");
Dianne Hackborncbb722e2012-02-07 18:33:49 -08009166 if (mMainStack.mPausingActivities.size() > 0) {
9167 pw.println(" mPausingActivities: " + Arrays.toString(
9168 mMainStack.mPausingActivities.toArray()));
9169 }
9170 if (mMainStack.mInputPausedActivities.size() > 0) {
9171 pw.println(" mInputPausedActivities: " + Arrays.toString(
9172 mMainStack.mInputPausedActivities.toArray()));
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009173 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009174 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009175 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009176 if (dumpAll) {
9177 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9178 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009179 pw.println(" mDismissKeyguardOnNextActivity: "
9180 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009182
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009183 if (mRecentTasks.size() > 0) {
9184 pw.println();
9185 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009186
9187 final int N = mRecentTasks.size();
9188 for (int i=0; i<N; i++) {
9189 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009190 if (dumpPackage != null) {
9191 if (tr.realActivity == null ||
9192 !dumpPackage.equals(tr.realActivity)) {
9193 continue;
9194 }
9195 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009196 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9197 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009198 if (dumpAll) {
9199 mRecentTasks.get(i).dump(pw, " ");
9200 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009201 }
9202 }
9203
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009204 if (dumpAll) {
9205 pw.println(" ");
9206 pw.println(" mCurTask: " + mCurTask);
9207 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009208
9209 return true;
9210 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009211
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009212 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009213 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009214 boolean needSep = false;
9215 int numPers = 0;
9216
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009217 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9218
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009219 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009220 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9221 final int NA = procs.size();
9222 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009223 ProcessRecord r = procs.valueAt(ia);
9224 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9225 continue;
9226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009227 if (!needSep) {
9228 pw.println(" All known processes:");
9229 needSep = true;
9230 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009231 pw.print(r.persistent ? " *PERS*" : " *APP*");
9232 pw.print(" UID "); pw.print(procs.keyAt(ia));
9233 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009234 r.dump(pw, " ");
9235 if (r.persistent) {
9236 numPers++;
9237 }
9238 }
9239 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009240 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009241
9242 if (mIsolatedProcesses.size() > 0) {
9243 if (needSep) pw.println(" ");
9244 needSep = true;
9245 pw.println(" Isolated process list (sorted by uid):");
9246 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9247 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9248 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9249 continue;
9250 }
9251 pw.println(String.format("%sIsolated #%2d: %s",
9252 " ", i, r.toString()));
9253 }
9254 }
9255
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009256 if (mLruProcesses.size() > 0) {
9257 if (needSep) pw.println(" ");
9258 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009259 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009260 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009261 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009262 needSep = true;
9263 }
9264
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009265 if (dumpAll) {
9266 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009267 boolean printed = false;
9268 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9269 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9270 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9271 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009272 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009273 if (!printed) {
9274 if (needSep) pw.println(" ");
9275 needSep = true;
9276 pw.println(" PID mappings:");
9277 printed = true;
9278 }
9279 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9280 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009281 }
9282 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009283 }
9284
9285 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009286 synchronized (mPidsSelfLocked) {
9287 boolean printed = false;
9288 for (int i=0; i<mForegroundProcesses.size(); i++) {
9289 ProcessRecord r = mPidsSelfLocked.get(
9290 mForegroundProcesses.valueAt(i).pid);
9291 if (dumpPackage != null && (r == null
9292 || !dumpPackage.equals(r.info.packageName))) {
9293 continue;
9294 }
9295 if (!printed) {
9296 if (needSep) pw.println(" ");
9297 needSep = true;
9298 pw.println(" Foreground Processes:");
9299 printed = true;
9300 }
9301 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9302 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009304 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009305 }
9306
9307 if (mPersistentStartingProcesses.size() > 0) {
9308 if (needSep) pw.println(" ");
9309 needSep = true;
9310 pw.println(" Persisent processes that are starting:");
9311 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009312 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009314
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009315 if (mRemovedProcesses.size() > 0) {
9316 if (needSep) pw.println(" ");
9317 needSep = true;
9318 pw.println(" Processes that are being removed:");
9319 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009320 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009321 }
9322
9323 if (mProcessesOnHold.size() > 0) {
9324 if (needSep) pw.println(" ");
9325 needSep = true;
9326 pw.println(" Processes that are on old until the system is ready:");
9327 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009328 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009330
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009331 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009332
9333 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009334 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009335 long now = SystemClock.uptimeMillis();
9336 for (Map.Entry<String, SparseArray<Long>> procs
9337 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009338 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009339 SparseArray<Long> uids = procs.getValue();
9340 final int N = uids.size();
9341 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009342 int puid = uids.keyAt(i);
9343 ProcessRecord r = mProcessNames.get(pname, puid);
9344 if (dumpPackage != null && (r == null
9345 || !dumpPackage.equals(r.info.packageName))) {
9346 continue;
9347 }
9348 if (!printed) {
9349 if (needSep) pw.println(" ");
9350 needSep = true;
9351 pw.println(" Time since processes crashed:");
9352 printed = true;
9353 }
9354 pw.print(" Process "); pw.print(pname);
9355 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009356 pw.print(": last crashed ");
9357 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009358 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009359 }
9360 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009362
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009363 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009364 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009365 for (Map.Entry<String, SparseArray<Long>> procs
9366 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009367 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009368 SparseArray<Long> uids = procs.getValue();
9369 final int N = uids.size();
9370 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009371 int puid = uids.keyAt(i);
9372 ProcessRecord r = mProcessNames.get(pname, puid);
9373 if (dumpPackage != null && (r == null
9374 || !dumpPackage.equals(r.info.packageName))) {
9375 continue;
9376 }
9377 if (!printed) {
9378 if (needSep) pw.println(" ");
9379 needSep = true;
9380 pw.println(" Bad processes:");
9381 }
9382 pw.print(" Bad process "); pw.print(pname);
9383 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009384 pw.print(": crashed at time ");
9385 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009386 }
9387 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009389
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009390 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009391 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009392 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009393 if (dumpAll) {
9394 StringBuilder sb = new StringBuilder(128);
9395 sb.append(" mPreviousProcessVisibleTime: ");
9396 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9397 pw.println(sb);
9398 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009399 if (mHeavyWeightProcess != null) {
9400 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9401 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009402 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009403 if (dumpAll) {
9404 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009405 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009406 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009407 for (Map.Entry<String, Integer> entry
9408 : mCompatModePackages.getPackages().entrySet()) {
9409 String pkg = entry.getKey();
9410 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009411 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9412 continue;
9413 }
9414 if (!printed) {
9415 pw.println(" mScreenCompatPackages:");
9416 printed = true;
9417 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009418 pw.print(" "); pw.print(pkg); pw.print(": ");
9419 pw.print(mode); pw.println();
9420 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009421 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009422 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009423 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
9424 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9425 || mOrigWaitForDebugger) {
9426 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9427 + " mDebugTransient=" + mDebugTransient
9428 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9429 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009430 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9431 || mProfileFd != null) {
9432 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9433 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9434 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9435 + mAutoStopProfiler);
9436 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009437 if (mAlwaysFinishActivities || mController != null) {
9438 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9439 + " mController=" + mController);
9440 }
9441 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009442 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009443 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009444 + " mProcessesReady=" + mProcessesReady
9445 + " mSystemReady=" + mSystemReady);
9446 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009447 + " mBooted=" + mBooted
9448 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009449 pw.print(" mLastPowerCheckRealtime=");
9450 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9451 pw.println("");
9452 pw.print(" mLastPowerCheckUptime=");
9453 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9454 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009455 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9456 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009457 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009458 pw.println(" mNumServiceProcs=" + mNumServiceProcs
9459 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009460 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009461
9462 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009463 }
9464
Dianne Hackborn287952c2010-09-22 22:34:31 -07009465 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009466 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009467 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009468 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009469 long now = SystemClock.uptimeMillis();
9470 for (int i=0; i<mProcessesToGc.size(); i++) {
9471 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009472 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9473 continue;
9474 }
9475 if (!printed) {
9476 if (needSep) pw.println(" ");
9477 needSep = true;
9478 pw.println(" Processes that are waiting to GC:");
9479 printed = true;
9480 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009481 pw.print(" Process "); pw.println(proc);
9482 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9483 pw.print(", last gced=");
9484 pw.print(now-proc.lastRequestedGc);
9485 pw.print(" ms ago, last lowMem=");
9486 pw.print(now-proc.lastLowMemory);
9487 pw.println(" ms ago");
9488
9489 }
9490 }
9491 return needSep;
9492 }
9493
9494 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9495 int opti, boolean dumpAll) {
9496 boolean needSep = false;
9497
9498 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009499 if (needSep) pw.println(" ");
9500 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009501 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009502 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009503 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009504 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9505 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9506 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9507 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9508 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009509 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009510 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009511 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009512 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009513 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009514 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009515
9516 if (needSep) pw.println(" ");
9517 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009518 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009519 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009520 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009521 needSep = true;
9522 }
9523
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009524 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009525
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009526 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009527 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009528 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009529 if (mHeavyWeightProcess != null) {
9530 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9531 }
9532
9533 return true;
9534 }
9535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009536 /**
9537 * There are three ways to call this:
9538 * - no service specified: dump all the services
9539 * - a flattened component name that matched an existing service was specified as the
9540 * first arg: dump that one service
9541 * - the first arg isn't the flattened component name of an existing service:
9542 * dump all services whose component contains the first arg as a substring
9543 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009544 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9545 int opti, boolean dumpAll) {
9546 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009547
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009548 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009549 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009550 try {
9551 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9552 for (UserInfo user : users) {
9553 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9554 services.add(r1);
9555 }
9556 }
9557 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009558 }
9559 }
9560 } else {
9561 ComponentName componentName = name != null
9562 ? ComponentName.unflattenFromString(name) : null;
9563 int objectId = 0;
9564 if (componentName == null) {
9565 // Not a '/' separated full component name; maybe an object ID?
9566 try {
9567 objectId = Integer.parseInt(name, 16);
9568 name = null;
9569 componentName = null;
9570 } catch (RuntimeException e) {
9571 }
9572 }
9573
9574 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009575 try {
9576 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9577 for (UserInfo user : users) {
9578 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9579 if (componentName != null) {
9580 if (r1.name.equals(componentName)) {
9581 services.add(r1);
9582 }
9583 } else if (name != null) {
9584 if (r1.name.flattenToString().contains(name)) {
9585 services.add(r1);
9586 }
9587 } else if (System.identityHashCode(r1) == objectId) {
9588 services.add(r1);
9589 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009590 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009591 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009592 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009593 }
9594 }
9595 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009596
9597 if (services.size() <= 0) {
9598 return false;
9599 }
9600
9601 boolean needSep = false;
9602 for (int i=0; i<services.size(); i++) {
9603 if (needSep) {
9604 pw.println();
9605 }
9606 needSep = true;
9607 dumpService("", fd, pw, services.get(i), args, dumpAll);
9608 }
9609 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009610 }
9611
9612 /**
9613 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9614 * there is a thread associated with the service.
9615 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009616 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9617 final ServiceRecord r, String[] args, boolean dumpAll) {
9618 String innerPrefix = prefix + " ";
9619 synchronized (this) {
9620 pw.print(prefix); pw.print("SERVICE ");
9621 pw.print(r.shortName); pw.print(" ");
9622 pw.print(Integer.toHexString(System.identityHashCode(r)));
9623 pw.print(" pid=");
9624 if (r.app != null) pw.println(r.app.pid);
9625 else pw.println("(not running)");
9626 if (dumpAll) {
9627 r.dump(pw, innerPrefix);
9628 }
9629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009630 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009631 pw.print(prefix); pw.println(" Client:");
9632 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009633 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009634 TransferPipe tp = new TransferPipe();
9635 try {
9636 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9637 tp.setBufferPrefix(prefix + " ");
9638 tp.go(fd);
9639 } finally {
9640 tp.kill();
9641 }
9642 } catch (IOException e) {
9643 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009644 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009645 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009646 }
9647 }
9648 }
9649
Marco Nelissen18cb2872011-11-15 11:19:53 -08009650 /**
9651 * There are three ways to call this:
9652 * - no provider specified: dump all the providers
9653 * - a flattened component name that matched an existing provider was specified as the
9654 * first arg: dump that one provider
9655 * - the first arg isn't the flattened component name of an existing provider:
9656 * dump all providers whose component contains the first arg as a substring
9657 */
9658 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9659 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009660 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009661 }
9662
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009663 static class ItemMatcher {
9664 ArrayList<ComponentName> components;
9665 ArrayList<String> strings;
9666 ArrayList<Integer> objects;
9667 boolean all;
9668
9669 ItemMatcher() {
9670 all = true;
9671 }
9672
9673 void build(String name) {
9674 ComponentName componentName = ComponentName.unflattenFromString(name);
9675 if (componentName != null) {
9676 if (components == null) {
9677 components = new ArrayList<ComponentName>();
9678 }
9679 components.add(componentName);
9680 all = false;
9681 } else {
9682 int objectId = 0;
9683 // Not a '/' separated full component name; maybe an object ID?
9684 try {
9685 objectId = Integer.parseInt(name, 16);
9686 if (objects == null) {
9687 objects = new ArrayList<Integer>();
9688 }
9689 objects.add(objectId);
9690 all = false;
9691 } catch (RuntimeException e) {
9692 // Not an integer; just do string match.
9693 if (strings == null) {
9694 strings = new ArrayList<String>();
9695 }
9696 strings.add(name);
9697 all = false;
9698 }
9699 }
9700 }
9701
9702 int build(String[] args, int opti) {
9703 for (; opti<args.length; opti++) {
9704 String name = args[opti];
9705 if ("--".equals(name)) {
9706 return opti+1;
9707 }
9708 build(name);
9709 }
9710 return opti;
9711 }
9712
9713 boolean match(Object object, ComponentName comp) {
9714 if (all) {
9715 return true;
9716 }
9717 if (components != null) {
9718 for (int i=0; i<components.size(); i++) {
9719 if (components.get(i).equals(comp)) {
9720 return true;
9721 }
9722 }
9723 }
9724 if (objects != null) {
9725 for (int i=0; i<objects.size(); i++) {
9726 if (System.identityHashCode(object) == objects.get(i)) {
9727 return true;
9728 }
9729 }
9730 }
9731 if (strings != null) {
9732 String flat = comp.flattenToString();
9733 for (int i=0; i<strings.size(); i++) {
9734 if (flat.contains(strings.get(i))) {
9735 return true;
9736 }
9737 }
9738 }
9739 return false;
9740 }
9741 }
9742
Dianne Hackborn625ac272010-09-17 18:29:22 -07009743 /**
9744 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009745 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009746 * - the cmd arg isn't the flattened component name of an existing activity:
9747 * dump all activity whose component contains the cmd as a substring
9748 * - A hex number of the ActivityRecord object instance.
9749 */
9750 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9751 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009752 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009753
9754 if ("all".equals(name)) {
9755 synchronized (this) {
9756 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009757 activities.add(r1);
9758 }
9759 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009760 } else if ("top".equals(name)) {
9761 synchronized (this) {
9762 final int N = mMainStack.mHistory.size();
9763 if (N > 0) {
9764 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9765 }
9766 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009767 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009768 ItemMatcher matcher = new ItemMatcher();
9769 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009770
9771 synchronized (this) {
9772 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009773 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009774 activities.add(r1);
9775 }
9776 }
9777 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009778 }
9779
9780 if (activities.size() <= 0) {
9781 return false;
9782 }
9783
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009784 String[] newArgs = new String[args.length - opti];
9785 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9786
Dianne Hackborn30d71892010-12-11 10:37:55 -08009787 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009788 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009789 for (int i=activities.size()-1; i>=0; i--) {
9790 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009791 if (needSep) {
9792 pw.println();
9793 }
9794 needSep = true;
9795 synchronized (this) {
9796 if (lastTask != r.task) {
9797 lastTask = r.task;
9798 pw.print("TASK "); pw.print(lastTask.affinity);
9799 pw.print(" id="); pw.println(lastTask.taskId);
9800 if (dumpAll) {
9801 lastTask.dump(pw, " ");
9802 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009803 }
9804 }
9805 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009806 }
9807 return true;
9808 }
9809
9810 /**
9811 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9812 * there is a thread associated with the activity.
9813 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009814 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009815 final ActivityRecord r, String[] args, boolean dumpAll) {
9816 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009817 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009818 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9819 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9820 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009821 if (r.app != null) pw.println(r.app.pid);
9822 else pw.println("(not running)");
9823 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009824 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009825 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009826 }
9827 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009828 // flush anything that is already in the PrintWriter since the thread is going
9829 // to write to the file descriptor directly
9830 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009831 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009832 TransferPipe tp = new TransferPipe();
9833 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009834 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9835 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009836 tp.go(fd);
9837 } finally {
9838 tp.kill();
9839 }
9840 } catch (IOException e) {
9841 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009842 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009843 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009844 }
9845 }
9846 }
9847
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009848 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009849 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009850 boolean needSep = false;
9851
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009852 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009853 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009854 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009855 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009856 Iterator it = mRegisteredReceivers.values().iterator();
9857 while (it.hasNext()) {
9858 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009859 if (dumpPackage != null && (r.app == null ||
9860 !dumpPackage.equals(r.app.info.packageName))) {
9861 continue;
9862 }
9863 if (!printed) {
9864 pw.println(" Registered Receivers:");
9865 needSep = true;
9866 printed = true;
9867 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009868 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009869 r.dump(pw, " ");
9870 }
9871 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009872
9873 if (mReceiverResolver.dump(pw, needSep ?
9874 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9875 " ", dumpPackage, false)) {
9876 needSep = true;
9877 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009878 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009879
9880 for (BroadcastQueue q : mBroadcastQueues) {
9881 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009883
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009884 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009885
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009886 if (mStickyBroadcasts != null && dumpPackage == null) {
9887 if (needSep) {
9888 pw.println();
9889 }
9890 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009891 pw.println(" Sticky broadcasts:");
9892 StringBuilder sb = new StringBuilder(128);
9893 for (Map.Entry<String, ArrayList<Intent>> ent
9894 : mStickyBroadcasts.entrySet()) {
9895 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009896 if (dumpAll) {
9897 pw.println(":");
9898 ArrayList<Intent> intents = ent.getValue();
9899 final int N = intents.size();
9900 for (int i=0; i<N; i++) {
9901 sb.setLength(0);
9902 sb.append(" Intent: ");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009903 intents.get(i).toShortString(sb, false, true, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009904 pw.println(sb.toString());
9905 Bundle bundle = intents.get(i).getExtras();
9906 if (bundle != null) {
9907 pw.print(" ");
9908 pw.println(bundle.toString());
9909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009910 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009911 } else {
9912 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009913 }
9914 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009915 needSep = true;
9916 }
9917
9918 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009919 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009920 for (BroadcastQueue queue : mBroadcastQueues) {
9921 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9922 + queue.mBroadcastsScheduled);
9923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009924 pw.println(" mHandler:");
9925 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009926 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009927 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009928
9929 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009930 }
9931
Marco Nelissen18cb2872011-11-15 11:19:53 -08009932 /**
9933 * Prints a list of ServiceRecords (dumpsys activity services)
9934 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009935 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009936 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009937 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009938
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009939 ItemMatcher matcher = new ItemMatcher();
9940 matcher.build(args, opti);
9941
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009942 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009943 try {
9944 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9945 for (UserInfo user : users) {
9946 if (mServiceMap.getAllServices(user.id).size() > 0) {
9947 boolean printed = false;
9948 long nowReal = SystemClock.elapsedRealtime();
9949 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9950 user.id).iterator();
9951 needSep = false;
9952 while (it.hasNext()) {
9953 ServiceRecord r = it.next();
9954 if (!matcher.match(r, r.name)) {
9955 continue;
9956 }
9957 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9958 continue;
9959 }
9960 if (!printed) {
9961 pw.println(" Active services:");
9962 printed = true;
9963 }
9964 if (needSep) {
9965 pw.println();
9966 }
9967 pw.print(" * ");
9968 pw.println(r);
9969 if (dumpAll) {
9970 r.dump(pw, " ");
9971 needSep = true;
9972 } else {
9973 pw.print(" app=");
9974 pw.println(r.app);
9975 pw.print(" created=");
9976 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9977 pw.print(" started=");
9978 pw.print(r.startRequested);
9979 pw.print(" connections=");
9980 pw.println(r.connections.size());
9981 if (r.connections.size() > 0) {
9982 pw.println(" Connections:");
9983 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9984 for (int i = 0; i < clist.size(); i++) {
9985 ConnectionRecord conn = clist.get(i);
9986 pw.print(" ");
9987 pw.print(conn.binding.intent.intent.getIntent()
9988 .toShortString(false, false, false));
9989 pw.print(" -> ");
9990 ProcessRecord proc = conn.binding.client;
9991 pw.println(proc != null ? proc.toShortString() : "null");
9992 }
9993 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009994 }
9995 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009996 if (dumpClient && r.app != null && r.app.thread != null) {
9997 pw.println(" Client:");
9998 pw.flush();
9999 try {
10000 TransferPipe tp = new TransferPipe();
10001 try {
10002 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
10003 r, args);
10004 tp.setBufferPrefix(" ");
10005 // Short timeout, since blocking here can
10006 // deadlock with the application.
10007 tp.go(fd, 2000);
10008 } finally {
10009 tp.kill();
10010 }
10011 } catch (IOException e) {
10012 pw.println(" Failure while dumping the service: " + e);
10013 } catch (RemoteException e) {
10014 pw.println(" Got a RemoteException while dumping the service");
10015 }
10016 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010017 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010018 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010019 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010021 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010022 } catch (RemoteException re) {
10023
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010025
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010026 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010027 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010028 for (int i=0; i<mPendingServices.size(); i++) {
10029 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010030 if (!matcher.match(r, r.name)) {
10031 continue;
10032 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010033 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
10034 continue;
10035 }
10036 if (!printed) {
10037 if (needSep) pw.println(" ");
10038 needSep = true;
10039 pw.println(" Pending services:");
10040 printed = true;
10041 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010042 pw.print(" * Pending "); pw.println(r);
10043 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010044 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010045 needSep = true;
10046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010047
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010048 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010049 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010050 for (int i=0; i<mRestartingServices.size(); i++) {
10051 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010052 if (!matcher.match(r, r.name)) {
10053 continue;
10054 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010055 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
10056 continue;
10057 }
10058 if (!printed) {
10059 if (needSep) pw.println(" ");
10060 needSep = true;
10061 pw.println(" Restarting services:");
10062 printed = true;
10063 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010064 pw.print(" * Restarting "); pw.println(r);
10065 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010066 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010067 needSep = true;
10068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010069
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010070 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010071 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010072 for (int i=0; i<mStoppingServices.size(); i++) {
10073 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010074 if (!matcher.match(r, r.name)) {
10075 continue;
10076 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010077 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
10078 continue;
10079 }
10080 if (!printed) {
10081 if (needSep) pw.println(" ");
10082 needSep = true;
10083 pw.println(" Stopping services:");
10084 printed = true;
10085 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010086 pw.print(" * Stopping "); pw.println(r);
10087 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010088 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010089 needSep = true;
10090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010091
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010092 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010093 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010094 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010095 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010096 = mServiceConnections.values().iterator();
10097 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010098 ArrayList<ConnectionRecord> r = it.next();
10099 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010100 ConnectionRecord cr = r.get(i);
10101 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
10102 continue;
10103 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010104 if (dumpPackage != null && (cr.binding.client == null
10105 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
10106 continue;
10107 }
10108 if (!printed) {
10109 if (needSep) pw.println(" ");
10110 needSep = true;
10111 pw.println(" Connection bindings to services:");
10112 printed = true;
10113 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010114 pw.print(" * "); pw.println(cr);
10115 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010117 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010118 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010119 }
10120 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010121
10122 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010123 }
10124
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010125 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010126 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010127 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010128
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010129 ItemMatcher matcher = new ItemMatcher();
10130 matcher.build(args, opti);
10131
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010132 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -070010133
10134 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010135
10136 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010137 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010138 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010139 ContentProviderRecord r = mLaunchingProviders.get(i);
10140 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
10141 continue;
10142 }
10143 if (!printed) {
10144 if (needSep) pw.println(" ");
10145 needSep = true;
10146 pw.println(" Launching content providers:");
10147 printed = true;
10148 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010149 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010150 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010151 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010152 }
10153
10154 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010155 if (needSep) pw.println();
10156 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010157 pw.println("Granted Uri Permissions:");
10158 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
10159 int uid = mGrantedUriPermissions.keyAt(i);
10160 HashMap<Uri, UriPermission> perms
10161 = mGrantedUriPermissions.valueAt(i);
10162 pw.print(" * UID "); pw.print(uid);
10163 pw.println(" holds:");
10164 for (UriPermission perm : perms.values()) {
10165 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010166 if (dumpAll) {
10167 perm.dump(pw, " ");
10168 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010169 }
10170 }
10171 needSep = true;
10172 }
10173
10174 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010175 }
10176
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010177 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010178 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010179 boolean needSep = false;
10180
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010181 if (mIntentSenderRecords.size() > 0) {
10182 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010183 Iterator<WeakReference<PendingIntentRecord>> it
10184 = mIntentSenderRecords.values().iterator();
10185 while (it.hasNext()) {
10186 WeakReference<PendingIntentRecord> ref = it.next();
10187 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010188 if (dumpPackage != null && (rec == null
10189 || !dumpPackage.equals(rec.key.packageName))) {
10190 continue;
10191 }
10192 if (!printed) {
10193 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
10194 printed = true;
10195 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010196 needSep = true;
10197 if (rec != null) {
10198 pw.print(" * "); pw.println(rec);
10199 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010200 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010201 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010202 } else {
10203 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010204 }
10205 }
10206 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010207
10208 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010209 }
10210
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010211 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010212 String prefix, String label, boolean complete, boolean brief, boolean client,
10213 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010214 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010215 boolean needNL = false;
10216 final String innerPrefix = prefix + " ";
10217 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010218 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010219 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010220 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
10221 continue;
10222 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -070010223 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010224 if (needNL) {
10225 pw.println(" ");
10226 needNL = false;
10227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010228 if (lastTask != r.task) {
10229 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010230 pw.print(prefix);
10231 pw.print(full ? "* " : " ");
10232 pw.println(lastTask);
10233 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010234 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010235 } else if (complete) {
10236 // Complete + brief == give a summary. Isn't that obvious?!?
10237 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010238 pw.print(prefix); pw.print(" ");
10239 pw.println(lastTask.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010240 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010242 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010243 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
10244 pw.print(" #"); pw.print(i); pw.print(": ");
10245 pw.println(r);
10246 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010247 r.dump(pw, innerPrefix);
10248 } else if (complete) {
10249 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010250 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010251 if (r.app != null) {
10252 pw.print(innerPrefix); pw.println(r.app);
10253 }
10254 }
10255 if (client && r.app != null && r.app.thread != null) {
10256 // flush anything that is already in the PrintWriter since the thread is going
10257 // to write to the file descriptor directly
10258 pw.flush();
10259 try {
10260 TransferPipe tp = new TransferPipe();
10261 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -080010262 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
10263 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010264 // Short timeout, since blocking here can
10265 // deadlock with the application.
10266 tp.go(fd, 2000);
10267 } finally {
10268 tp.kill();
10269 }
10270 } catch (IOException e) {
10271 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
10272 } catch (RemoteException e) {
10273 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
10274 }
10275 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010277 }
10278 }
10279
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010280 private static String buildOomTag(String prefix, String space, int val, int base) {
10281 if (val == base) {
10282 if (space == null) return prefix;
10283 return prefix + " ";
10284 }
10285 return prefix + "+" + Integer.toString(val-base);
10286 }
10287
10288 private static final int dumpProcessList(PrintWriter pw,
10289 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010290 String prefix, String normalLabel, String persistentLabel,
10291 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010292 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010293 final int N = list.size()-1;
10294 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010295 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010296 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10297 continue;
10298 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010299 pw.println(String.format("%s%s #%2d: %s",
10300 prefix, (r.persistent ? persistentLabel : normalLabel),
10301 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010302 if (r.persistent) {
10303 numPers++;
10304 }
10305 }
10306 return numPers;
10307 }
10308
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010309 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010310 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010311 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010312 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010313
Dianne Hackborn905577f2011-09-07 18:31:28 -070010314 ArrayList<Pair<ProcessRecord, Integer>> list
10315 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10316 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010317 ProcessRecord r = origList.get(i);
10318 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10319 continue;
10320 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010321 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10322 }
10323
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010324 if (list.size() <= 0) {
10325 return false;
10326 }
10327
Dianne Hackborn905577f2011-09-07 18:31:28 -070010328 Comparator<Pair<ProcessRecord, Integer>> comparator
10329 = new Comparator<Pair<ProcessRecord, Integer>>() {
10330 @Override
10331 public int compare(Pair<ProcessRecord, Integer> object1,
10332 Pair<ProcessRecord, Integer> object2) {
10333 if (object1.first.setAdj != object2.first.setAdj) {
10334 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10335 }
10336 if (object1.second.intValue() != object2.second.intValue()) {
10337 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10338 }
10339 return 0;
10340 }
10341 };
10342
10343 Collections.sort(list, comparator);
10344
Dianne Hackborn287952c2010-09-22 22:34:31 -070010345 final long curRealtime = SystemClock.elapsedRealtime();
10346 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10347 final long curUptime = SystemClock.uptimeMillis();
10348 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10349
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010350 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010351 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010352 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010353 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010354 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010355 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10356 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010357 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10358 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010359 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10360 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010361 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10362 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010363 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010364 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010365 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10366 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10367 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10368 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10369 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10370 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10371 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10372 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010373 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10374 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010375 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10376 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010377 } else {
10378 oomAdj = Integer.toString(r.setAdj);
10379 }
10380 String schedGroup;
10381 switch (r.setSchedGroup) {
10382 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10383 schedGroup = "B";
10384 break;
10385 case Process.THREAD_GROUP_DEFAULT:
10386 schedGroup = "F";
10387 break;
10388 default:
10389 schedGroup = Integer.toString(r.setSchedGroup);
10390 break;
10391 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010392 String foreground;
10393 if (r.foregroundActivities) {
10394 foreground = "A";
10395 } else if (r.foregroundServices) {
10396 foreground = "S";
10397 } else {
10398 foreground = " ";
10399 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010400 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010401 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010402 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10403 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010404 if (r.adjSource != null || r.adjTarget != null) {
10405 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010406 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010407 if (r.adjTarget instanceof ComponentName) {
10408 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10409 } else if (r.adjTarget != null) {
10410 pw.print(r.adjTarget.toString());
10411 } else {
10412 pw.print("{null}");
10413 }
10414 pw.print("<=");
10415 if (r.adjSource instanceof ProcessRecord) {
10416 pw.print("Proc{");
10417 pw.print(((ProcessRecord)r.adjSource).toShortString());
10418 pw.println("}");
10419 } else if (r.adjSource != null) {
10420 pw.println(r.adjSource.toString());
10421 } else {
10422 pw.println("{null}");
10423 }
10424 }
10425 if (inclDetails) {
10426 pw.print(prefix);
10427 pw.print(" ");
10428 pw.print("oom: max="); pw.print(r.maxAdj);
10429 pw.print(" hidden="); pw.print(r.hiddenAdj);
10430 pw.print(" curRaw="); pw.print(r.curRawAdj);
10431 pw.print(" setRaw="); pw.print(r.setRawAdj);
10432 pw.print(" cur="); pw.print(r.curAdj);
10433 pw.print(" set="); pw.println(r.setAdj);
10434 pw.print(prefix);
10435 pw.print(" ");
10436 pw.print("keeping="); pw.print(r.keeping);
10437 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010438 pw.print(" empty="); pw.print(r.empty);
10439 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010440
10441 if (!r.keeping) {
10442 if (r.lastWakeTime != 0) {
10443 long wtime;
10444 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10445 synchronized (stats) {
10446 wtime = stats.getProcessWakeTime(r.info.uid,
10447 r.pid, curRealtime);
10448 }
10449 long timeUsed = wtime - r.lastWakeTime;
10450 pw.print(prefix);
10451 pw.print(" ");
10452 pw.print("keep awake over ");
10453 TimeUtils.formatDuration(realtimeSince, pw);
10454 pw.print(" used ");
10455 TimeUtils.formatDuration(timeUsed, pw);
10456 pw.print(" (");
10457 pw.print((timeUsed*100)/realtimeSince);
10458 pw.println("%)");
10459 }
10460 if (r.lastCpuTime != 0) {
10461 long timeUsed = r.curCpuTime - r.lastCpuTime;
10462 pw.print(prefix);
10463 pw.print(" ");
10464 pw.print("run cpu over ");
10465 TimeUtils.formatDuration(uptimeSince, pw);
10466 pw.print(" used ");
10467 TimeUtils.formatDuration(timeUsed, pw);
10468 pw.print(" (");
10469 pw.print((timeUsed*100)/uptimeSince);
10470 pw.println("%)");
10471 }
10472 }
10473 }
10474 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010475 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010476 }
10477
Dianne Hackbornb437e092011-08-05 17:50:29 -070010478 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010479 ArrayList<ProcessRecord> procs;
10480 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010481 if (args != null && args.length > start
10482 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010483 procs = new ArrayList<ProcessRecord>();
10484 int pid = -1;
10485 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010486 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010487 } catch (NumberFormatException e) {
10488
10489 }
10490 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10491 ProcessRecord proc = mLruProcesses.get(i);
10492 if (proc.pid == pid) {
10493 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010494 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010495 procs.add(proc);
10496 }
10497 }
10498 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010499 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010500 return null;
10501 }
10502 } else {
10503 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10504 }
10505 }
10506 return procs;
10507 }
10508
10509 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10510 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010511 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010512 if (procs == null) {
10513 return;
10514 }
10515
10516 long uptime = SystemClock.uptimeMillis();
10517 long realtime = SystemClock.elapsedRealtime();
10518 pw.println("Applications Graphics Acceleration Info:");
10519 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10520
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010521 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10522 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010523 if (r.thread != null) {
10524 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10525 pw.flush();
10526 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010527 TransferPipe tp = new TransferPipe();
10528 try {
10529 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10530 tp.go(fd);
10531 } finally {
10532 tp.kill();
10533 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010534 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010535 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010536 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010537 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010538 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010539 pw.flush();
10540 }
10541 }
10542 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010543 }
10544
Jeff Brown6754ba22011-12-14 20:20:01 -080010545 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10546 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10547 if (procs == null) {
10548 return;
10549 }
10550
10551 pw.println("Applications Database Info:");
10552
10553 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10554 ProcessRecord r = procs.get(i);
10555 if (r.thread != null) {
10556 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10557 pw.flush();
10558 try {
10559 TransferPipe tp = new TransferPipe();
10560 try {
10561 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10562 tp.go(fd);
10563 } finally {
10564 tp.kill();
10565 }
10566 } catch (IOException e) {
10567 pw.println("Failure while dumping the app: " + r);
10568 pw.flush();
10569 } catch (RemoteException e) {
10570 pw.println("Got a RemoteException while dumping the app " + r);
10571 pw.flush();
10572 }
10573 }
10574 }
10575 }
10576
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010577 final static class MemItem {
10578 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010579 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010580 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010581 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010582 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010583
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010584 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010585 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010586 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010587 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010588 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010589 }
10590 }
10591
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010592 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010593 boolean sort) {
10594 if (sort) {
10595 Collections.sort(items, new Comparator<MemItem>() {
10596 @Override
10597 public int compare(MemItem lhs, MemItem rhs) {
10598 if (lhs.pss < rhs.pss) {
10599 return 1;
10600 } else if (lhs.pss > rhs.pss) {
10601 return -1;
10602 }
10603 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010604 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010605 });
10606 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010607
10608 for (int i=0; i<items.size(); i++) {
10609 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010610 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010611 if (mi.subitems != null) {
10612 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10613 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010614 }
10615 }
10616
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010617 // These are in KB.
10618 static final long[] DUMP_MEM_BUCKETS = new long[] {
10619 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10620 120*1024, 160*1024, 200*1024,
10621 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10622 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10623 };
10624
Dianne Hackborn672342c2011-11-29 11:29:02 -080010625 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10626 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010627 int start = label.lastIndexOf('.');
10628 if (start >= 0) start++;
10629 else start = 0;
10630 int end = label.length();
10631 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10632 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10633 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10634 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010635 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010636 out.append(label, start, end);
10637 return;
10638 }
10639 }
10640 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010641 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010642 out.append(label, start, end);
10643 }
10644
10645 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10646 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10647 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10648 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10649 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10650 };
10651 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10652 "System", "Persistent", "Foreground",
10653 "Visible", "Perceptible", "Heavy Weight",
10654 "Backup", "A Services", "Home", "Previous",
10655 "B Services", "Background"
10656 };
10657
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010658 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010659 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010660 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010661 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010662 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010663
10664 int opti = 0;
10665 while (opti < args.length) {
10666 String opt = args[opti];
10667 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10668 break;
10669 }
10670 opti++;
10671 if ("-a".equals(opt)) {
10672 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010673 } else if ("--oom".equals(opt)) {
10674 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010675 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010676 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010677 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010678 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010679 pw.println("If [process] is specified it can be the name or ");
10680 pw.println("pid of a specific process to dump.");
10681 return;
10682 } else {
10683 pw.println("Unknown argument: " + opt + "; use -h for help");
10684 }
10685 }
10686
10687 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010688 if (procs == null) {
10689 return;
10690 }
10691
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010692 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010693 long uptime = SystemClock.uptimeMillis();
10694 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010695
10696 if (procs.size() == 1 || isCheckinRequest) {
10697 dumpAll = true;
10698 }
10699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010700 if (isCheckinRequest) {
10701 // short checkin version
10702 pw.println(uptime + "," + realtime);
10703 pw.flush();
10704 } else {
10705 pw.println("Applications Memory Usage (kB):");
10706 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10707 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010708
Dianne Hackbornb437e092011-08-05 17:50:29 -070010709 String[] innerArgs = new String[args.length-opti];
10710 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10711
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010712 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10713 long nativePss=0, dalvikPss=0, otherPss=0;
10714 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10715
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010716 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10717 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10718 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010719
10720 long totalPss = 0;
10721
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010722 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10723 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010724 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010725 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010726 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10727 pw.flush();
10728 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010729 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010730 if (dumpAll) {
10731 try {
10732 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10733 } catch (RemoteException e) {
10734 if (!isCheckinRequest) {
10735 pw.println("Got RemoteException!");
10736 pw.flush();
10737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010738 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010739 } else {
10740 mi = new Debug.MemoryInfo();
10741 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010742 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010743
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010744 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010745 long myTotalPss = mi.getTotalPss();
10746 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010747 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010748 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010749 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010750
10751 nativePss += mi.nativePss;
10752 dalvikPss += mi.dalvikPss;
10753 otherPss += mi.otherPss;
10754 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10755 long mem = mi.getOtherPss(j);
10756 miscPss[j] += mem;
10757 otherPss -= mem;
10758 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010759
10760 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010761 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10762 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010763 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010764 if (oomProcs[oomIndex] == null) {
10765 oomProcs[oomIndex] = new ArrayList<MemItem>();
10766 }
10767 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010768 break;
10769 }
10770 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010772 }
10773 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010774
10775 if (!isCheckinRequest && procs.size() > 1) {
10776 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10777
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010778 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10779 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10780 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010781 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010782 String label = Debug.MemoryInfo.getOtherLabel(j);
10783 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010784 }
10785
Dianne Hackbornb437e092011-08-05 17:50:29 -070010786 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10787 for (int j=0; j<oomPss.length; j++) {
10788 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010789 String label = DUMP_MEM_OOM_LABEL[j];
10790 MemItem item = new MemItem(label, label, oomPss[j],
10791 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010792 item.subitems = oomProcs[j];
10793 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010794 }
10795 }
10796
Dianne Hackborn672342c2011-11-29 11:29:02 -080010797 if (outTag != null || outStack != null) {
10798 if (outTag != null) {
10799 appendMemBucket(outTag, totalPss, "total", false);
10800 }
10801 if (outStack != null) {
10802 appendMemBucket(outStack, totalPss, "total", true);
10803 }
10804 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010805 for (int i=0; i<oomMems.size(); i++) {
10806 MemItem miCat = oomMems.get(i);
10807 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10808 continue;
10809 }
10810 if (miCat.id < ProcessList.SERVICE_ADJ
10811 || miCat.id == ProcessList.HOME_APP_ADJ
10812 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010813 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10814 outTag.append(" / ");
10815 }
10816 if (outStack != null) {
10817 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10818 if (firstLine) {
10819 outStack.append(":");
10820 firstLine = false;
10821 }
10822 outStack.append("\n\t at ");
10823 } else {
10824 outStack.append("$");
10825 }
10826 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010827 for (int j=0; j<miCat.subitems.size(); j++) {
10828 MemItem mi = miCat.subitems.get(j);
10829 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010830 if (outTag != null) {
10831 outTag.append(" ");
10832 }
10833 if (outStack != null) {
10834 outStack.append("$");
10835 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010836 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010837 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10838 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10839 }
10840 if (outStack != null) {
10841 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10842 }
10843 }
10844 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10845 outStack.append("(");
10846 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10847 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10848 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10849 outStack.append(":");
10850 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10851 }
10852 }
10853 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010854 }
10855 }
10856 }
10857 }
10858
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010859 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010860 pw.println();
10861 pw.println("Total PSS by process:");
10862 dumpMemItems(pw, " ", procMems, true);
10863 pw.println();
10864 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010865 pw.println("Total PSS by OOM adjustment:");
10866 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010867 if (!oomOnly) {
10868 PrintWriter out = categoryPw != null ? categoryPw : pw;
10869 out.println();
10870 out.println("Total PSS by category:");
10871 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010872 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010873 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010874 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010876 }
10877
10878 /**
10879 * Searches array of arguments for the specified string
10880 * @param args array of argument strings
10881 * @param value value to search for
10882 * @return true if the value is contained in the array
10883 */
10884 private static boolean scanArgs(String[] args, String value) {
10885 if (args != null) {
10886 for (String arg : args) {
10887 if (value.equals(arg)) {
10888 return true;
10889 }
10890 }
10891 }
10892 return false;
10893 }
10894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010895 private final void killServicesLocked(ProcessRecord app,
10896 boolean allowRestart) {
10897 // Report disconnected services.
10898 if (false) {
10899 // XXX we are letting the client link to the service for
10900 // death notifications.
10901 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010902 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010903 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010904 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010905 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010906 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010907 = r.connections.values().iterator();
10908 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010909 ArrayList<ConnectionRecord> cl = jt.next();
10910 for (int i=0; i<cl.size(); i++) {
10911 ConnectionRecord c = cl.get(i);
10912 if (c.binding.client != app) {
10913 try {
10914 //c.conn.connected(r.className, null);
10915 } catch (Exception e) {
10916 // todo: this should be asynchronous!
10917 Slog.w(TAG, "Exception thrown disconnected servce "
10918 + r.shortName
10919 + " from app " + app.processName, e);
10920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010921 }
10922 }
10923 }
10924 }
10925 }
10926 }
10927 }
10928
10929 // Clean up any connections this application has to other services.
10930 if (app.connections.size() > 0) {
10931 Iterator<ConnectionRecord> it = app.connections.iterator();
10932 while (it.hasNext()) {
10933 ConnectionRecord r = it.next();
10934 removeConnectionLocked(r, app, null);
10935 }
10936 }
10937 app.connections.clear();
10938
10939 if (app.services.size() != 0) {
10940 // Any services running in the application need to be placed
10941 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010942 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010943 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010944 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010945 synchronized (sr.stats.getBatteryStats()) {
10946 sr.stats.stopLaunchedLocked();
10947 }
10948 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010949 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010950 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010951 if (mStoppingServices.remove(sr)) {
10952 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10953 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010954
10955 boolean hasClients = sr.bindings.size() > 0;
10956 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010957 Iterator<IntentBindRecord> bindings
10958 = sr.bindings.values().iterator();
10959 while (bindings.hasNext()) {
10960 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010961 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010962 + ": shouldUnbind=" + b.hasBound);
10963 b.binder = null;
10964 b.requested = b.received = b.hasBound = false;
10965 }
10966 }
10967
Dianne Hackborn070783f2010-12-29 16:46:28 -080010968 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10969 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010970 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010971 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010972 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010973 sr.crashCount, sr.shortName, app.pid);
10974 bringDownServiceLocked(sr, true);
10975 } else if (!allowRestart) {
10976 bringDownServiceLocked(sr, true);
10977 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010978 boolean canceled = scheduleServiceRestartLocked(sr, true);
10979
10980 // Should the service remain running? Note that in the
10981 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010982 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010983 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10984 if (sr.pendingStarts.size() == 0) {
10985 sr.startRequested = false;
10986 if (!hasClients) {
10987 // Whoops, no reason to restart!
10988 bringDownServiceLocked(sr, true);
10989 }
10990 }
10991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010992 }
10993 }
10994
10995 if (!allowRestart) {
10996 app.services.clear();
10997 }
10998 }
10999
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011000 // Make sure we have no more records on the stopping list.
11001 int i = mStoppingServices.size();
11002 while (i > 0) {
11003 i--;
11004 ServiceRecord sr = mStoppingServices.get(i);
11005 if (sr.app == app) {
11006 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011007 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011008 }
11009 }
11010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011011 app.executingServices.clear();
11012 }
11013
11014 private final void removeDyingProviderLocked(ProcessRecord proc,
11015 ContentProviderRecord cpr) {
11016 synchronized (cpr) {
11017 cpr.launchingApp = null;
11018 cpr.notifyAll();
11019 }
11020
Amith Yamasani742a6712011-05-04 14:49:28 -070011021 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011022 String names[] = cpr.info.authority.split(";");
11023 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011024 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011025 }
11026
11027 Iterator<ProcessRecord> cit = cpr.clients.iterator();
11028 while (cit.hasNext()) {
11029 ProcessRecord capp = cit.next();
11030 if (!capp.persistent && capp.thread != null
11031 && capp.pid != 0
11032 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011033 Slog.i(TAG, "Kill " + capp.processName
11034 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070011035 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070011036 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070011037 capp.processName, capp.setAdj, "dying provider "
11038 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011039 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011040 }
11041 }
11042
11043 mLaunchingProviders.remove(cpr);
11044 }
11045
11046 /**
11047 * Main code for cleaning up a process when it has gone away. This is
11048 * called both as a result of the process dying, or directly when stopping
11049 * a process when running in single process mode.
11050 */
11051 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011052 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011053 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011054 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011055 }
11056
Dianne Hackborn36124872009-10-08 16:22:03 -070011057 mProcessesToGc.remove(app);
11058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011059 // Dismiss any open dialogs.
11060 if (app.crashDialog != null) {
11061 app.crashDialog.dismiss();
11062 app.crashDialog = null;
11063 }
11064 if (app.anrDialog != null) {
11065 app.anrDialog.dismiss();
11066 app.anrDialog = null;
11067 }
11068 if (app.waitDialog != null) {
11069 app.waitDialog.dismiss();
11070 app.waitDialog = null;
11071 }
11072
11073 app.crashing = false;
11074 app.notResponding = false;
11075
11076 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070011077 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011078 app.thread = null;
11079 app.forcingToForeground = null;
11080 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070011081 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070011082 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011083 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011084
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011085 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011086
11087 boolean restart = false;
11088
11089 int NL = mLaunchingProviders.size();
11090
11091 // Remove published content providers.
11092 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011093 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011094 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011095 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011096 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070011097 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011098
11099 // See if someone is waiting for this provider... in which
11100 // case we don't remove it, but just let it restart.
11101 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011102 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011103 for (; i<NL; i++) {
11104 if (mLaunchingProviders.get(i) == cpr) {
11105 restart = true;
11106 break;
11107 }
11108 }
11109 } else {
11110 i = NL;
11111 }
11112
11113 if (i >= NL) {
11114 removeDyingProviderLocked(app, cpr);
11115 NL = mLaunchingProviders.size();
11116 }
11117 }
11118 app.pubProviders.clear();
11119 }
11120
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011121 // Take care of any launching providers waiting for this process.
11122 if (checkAppInLaunchingProvidersLocked(app, false)) {
11123 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011124 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011126 // Unregister from connected content providers.
11127 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070011128 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011129 while (it.hasNext()) {
11130 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
11131 cpr.clients.remove(app);
11132 }
11133 app.conProviders.clear();
11134 }
11135
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011136 // At this point there may be remaining entries in mLaunchingProviders
11137 // where we were the only one waiting, so they are no longer of use.
11138 // Look for these and clean up if found.
11139 // XXX Commented out for now. Trying to figure out a way to reproduce
11140 // the actual situation to identify what is actually going on.
11141 if (false) {
11142 for (int i=0; i<NL; i++) {
11143 ContentProviderRecord cpr = (ContentProviderRecord)
11144 mLaunchingProviders.get(i);
11145 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
11146 synchronized (cpr) {
11147 cpr.launchingApp = null;
11148 cpr.notifyAll();
11149 }
11150 }
11151 }
11152 }
11153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011154 skipCurrentReceiverLocked(app);
11155
11156 // Unregister any receivers.
11157 if (app.receivers.size() > 0) {
11158 Iterator<ReceiverList> it = app.receivers.iterator();
11159 while (it.hasNext()) {
11160 removeReceiverLocked(it.next());
11161 }
11162 app.receivers.clear();
11163 }
11164
Christopher Tate181fafa2009-05-14 11:12:14 -070011165 // If the app is undergoing backup, tell the backup manager about it
11166 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011167 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070011168 try {
11169 IBackupManager bm = IBackupManager.Stub.asInterface(
11170 ServiceManager.getService(Context.BACKUP_SERVICE));
11171 bm.agentDisconnected(app.info.packageName);
11172 } catch (RemoteException e) {
11173 // can't happen; backup manager is local
11174 }
11175 }
11176
Jeff Sharkey287bd832011-05-28 19:36:26 -070011177 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070011178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011179 // If the caller is restarting this app, then leave it in its
11180 // current lists and let the caller take care of it.
11181 if (restarting) {
11182 return;
11183 }
11184
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011185 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011186 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011187 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011188 mProcessNames.remove(app.processName, app.uid);
11189 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070011190 if (mHeavyWeightProcess == app) {
11191 mHeavyWeightProcess = null;
11192 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
11193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011194 } else if (!app.removed) {
11195 // This app is persistent, so we need to keep its record around.
11196 // If it is not already on the pending app list, add it there
11197 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011198 if (mPersistentStartingProcesses.indexOf(app) < 0) {
11199 mPersistentStartingProcesses.add(app);
11200 restart = true;
11201 }
11202 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011203 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
11204 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011205 mProcessesOnHold.remove(app);
11206
The Android Open Source Project4df24232009-03-05 14:34:35 -080011207 if (app == mHomeProcess) {
11208 mHomeProcess = null;
11209 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070011210 if (app == mPreviousProcess) {
11211 mPreviousProcess = null;
11212 }
11213
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011214 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011215 // We have components that still need to be running in the
11216 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011217 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011218 startProcessLocked(app, "restart", app.processName);
11219 } else if (app.pid > 0 && app.pid != MY_PID) {
11220 // Goodbye!
11221 synchronized (mPidsSelfLocked) {
11222 mPidsSelfLocked.remove(app.pid);
11223 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
11224 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070011225 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011226 }
11227 }
11228
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011229 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
11230 // Look through the content providers we are waiting to have launched,
11231 // and if any run in this process then either schedule a restart of
11232 // the process or kill the client waiting for it if this process has
11233 // gone bad.
11234 int NL = mLaunchingProviders.size();
11235 boolean restart = false;
11236 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011237 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011238 if (cpr.launchingApp == app) {
11239 if (!alwaysBad && !app.bad) {
11240 restart = true;
11241 } else {
11242 removeDyingProviderLocked(app, cpr);
11243 NL = mLaunchingProviders.size();
11244 }
11245 }
11246 }
11247 return restart;
11248 }
11249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011250 // =========================================================
11251 // SERVICES
11252 // =========================================================
11253
11254 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
11255 ActivityManager.RunningServiceInfo info =
11256 new ActivityManager.RunningServiceInfo();
11257 info.service = r.name;
11258 if (r.app != null) {
11259 info.pid = r.app.pid;
11260 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070011261 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011262 info.process = r.processName;
11263 info.foreground = r.isForeground;
11264 info.activeSince = r.createTime;
11265 info.started = r.startRequested;
11266 info.clientCount = r.connections.size();
11267 info.crashCount = r.crashCount;
11268 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070011269 if (r.isForeground) {
11270 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
11271 }
11272 if (r.startRequested) {
11273 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
11274 }
Dan Egnor42471dd2010-01-07 17:25:22 -080011275 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070011276 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
11277 }
11278 if (r.app != null && r.app.persistent) {
11279 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
11280 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011281
11282 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
11283 for (int i=0; i<connl.size(); i++) {
11284 ConnectionRecord conn = connl.get(i);
11285 if (conn.clientLabel != 0) {
11286 info.clientPackage = conn.binding.client.info.packageName;
11287 info.clientLabel = conn.clientLabel;
11288 return info;
11289 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011290 }
11291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011292 return info;
11293 }
11294
11295 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
11296 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011297 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011298 synchronized (this) {
11299 ArrayList<ActivityManager.RunningServiceInfo> res
11300 = new ArrayList<ActivityManager.RunningServiceInfo>();
11301
Amith Yamasani742a6712011-05-04 14:49:28 -070011302 int userId = UserId.getUserId(Binder.getCallingUid());
11303 if (mServiceMap.getAllServices(userId).size() > 0) {
11304 Iterator<ServiceRecord> it
11305 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011306 while (it.hasNext() && res.size() < maxNum) {
11307 res.add(makeRunningServiceInfoLocked(it.next()));
11308 }
11309 }
11310
11311 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
11312 ServiceRecord r = mRestartingServices.get(i);
11313 ActivityManager.RunningServiceInfo info =
11314 makeRunningServiceInfoLocked(r);
11315 info.restarting = r.nextRestartTime;
11316 res.add(info);
11317 }
11318
11319 return res;
11320 }
11321 }
11322
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011323 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011324 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011325 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011326 int userId = UserId.getUserId(Binder.getCallingUid());
11327 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011328 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011329 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
11330 for (int i=0; i<conn.size(); i++) {
11331 if (conn.get(i).clientIntent != null) {
11332 return conn.get(i).clientIntent;
11333 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011334 }
11335 }
11336 }
11337 }
11338 return null;
11339 }
11340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011341 private final ServiceRecord findServiceLocked(ComponentName name,
11342 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011343 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011344 return r == token ? r : null;
11345 }
11346
11347 private final class ServiceLookupResult {
11348 final ServiceRecord record;
11349 final String permission;
11350
11351 ServiceLookupResult(ServiceRecord _record, String _permission) {
11352 record = _record;
11353 permission = _permission;
11354 }
11355 };
11356
11357 private ServiceLookupResult findServiceLocked(Intent service,
11358 String resolvedType) {
11359 ServiceRecord r = null;
11360 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011361 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 }
11363 if (r == null) {
11364 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070011365 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011366 }
11367
11368 if (r == null) {
11369 try {
11370 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011371 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011372 service, resolvedType, 0);
11373 ServiceInfo sInfo =
11374 rInfo != null ? rInfo.serviceInfo : null;
11375 if (sInfo == null) {
11376 return null;
11377 }
11378
11379 ComponentName name = new ComponentName(
11380 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070011381 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011382 } catch (RemoteException ex) {
11383 // pm is in same process, this will never happen.
11384 }
11385 }
11386 if (r != null) {
11387 int callingPid = Binder.getCallingPid();
11388 int callingUid = Binder.getCallingUid();
11389 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011390 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011391 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011392 if (!r.exported) {
11393 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11394 + " from pid=" + callingPid
11395 + ", uid=" + callingUid
11396 + " that is not exported from uid " + r.appInfo.uid);
11397 return new ServiceLookupResult(null, "not exported from uid "
11398 + r.appInfo.uid);
11399 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011400 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011401 + " from pid=" + callingPid
11402 + ", uid=" + callingUid
11403 + " requires " + r.permission);
11404 return new ServiceLookupResult(null, r.permission);
11405 }
11406 return new ServiceLookupResult(r, null);
11407 }
11408 return null;
11409 }
11410
11411 private class ServiceRestarter implements Runnable {
11412 private ServiceRecord mService;
11413
11414 void setService(ServiceRecord service) {
11415 mService = service;
11416 }
11417
11418 public void run() {
11419 synchronized(ActivityManagerService.this) {
11420 performServiceRestartLocked(mService);
11421 }
11422 }
11423 }
11424
11425 private ServiceLookupResult retrieveServiceLocked(Intent service,
11426 String resolvedType, int callingPid, int callingUid) {
11427 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070011428 if (DEBUG_SERVICE)
11429 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
11430 + " origCallingUid=" + callingUid);
11431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011432 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011433 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011434 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011435 if (r == null) {
11436 Intent.FilterComparison filter = new Intent.FilterComparison(service);
11437 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
11438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011439 if (r == null) {
11440 try {
11441 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011442 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011443 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011444 ServiceInfo sInfo =
11445 rInfo != null ? rInfo.serviceInfo : null;
11446 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011447 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011448 ": not found");
11449 return null;
11450 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011451 if (Binder.getOrigCallingUser() > 0) {
11452 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo,
11453 Binder.getOrigCallingUser());
11454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011455 ComponentName name = new ComponentName(
11456 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070011457 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011458 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011459 Intent.FilterComparison filter = new Intent.FilterComparison(
11460 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011461 ServiceRestarter res = new ServiceRestarter();
11462 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11463 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11464 synchronized (stats) {
11465 ss = stats.getServiceStatsLocked(
11466 sInfo.applicationInfo.uid, sInfo.packageName,
11467 sInfo.name);
11468 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080011469 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011470 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070011471 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
11472 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473
11474 // Make sure this component isn't in the pending list.
11475 int N = mPendingServices.size();
11476 for (int i=0; i<N; i++) {
11477 ServiceRecord pr = mPendingServices.get(i);
11478 if (pr.name.equals(name)) {
11479 mPendingServices.remove(i);
11480 i--;
11481 N--;
11482 }
11483 }
11484 }
11485 } catch (RemoteException ex) {
11486 // pm is in same process, this will never happen.
11487 }
11488 }
11489 if (r != null) {
11490 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011491 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011492 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011493 if (!r.exported) {
11494 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11495 + " from pid=" + callingPid
11496 + ", uid=" + callingUid
11497 + " that is not exported from uid " + r.appInfo.uid);
11498 return new ServiceLookupResult(null, "not exported from uid "
11499 + r.appInfo.uid);
11500 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011501 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011502 + " from pid=" + callingPid
11503 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011504 + " requires " + r.permission);
11505 return new ServiceLookupResult(null, r.permission);
11506 }
11507 return new ServiceLookupResult(r, null);
11508 }
11509 return null;
11510 }
11511
Dianne Hackborn287952c2010-09-22 22:34:31 -070011512 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11513 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11514 + why + " of " + r + " in app " + r.app);
11515 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11516 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011517 long now = SystemClock.uptimeMillis();
11518 if (r.executeNesting == 0 && r.app != null) {
11519 if (r.app.executingServices.size() == 0) {
11520 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11521 msg.obj = r.app;
11522 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11523 }
11524 r.app.executingServices.add(r);
11525 }
11526 r.executeNesting++;
11527 r.executingStart = now;
11528 }
11529
11530 private final void sendServiceArgsLocked(ServiceRecord r,
11531 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011532 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011533 if (N == 0) {
11534 return;
11535 }
11536
Dianne Hackborn39792d22010-08-19 18:01:52 -070011537 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011538 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011539 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011540 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11541 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011542 if (si.intent == null && N > 1) {
11543 // If somehow we got a dummy null intent in the middle,
11544 // then skip it. DO NOT skip a null intent when it is
11545 // the only one in the list -- this is to support the
11546 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011547 continue;
11548 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011549 si.deliveredTime = SystemClock.uptimeMillis();
11550 r.deliveredStarts.add(si);
11551 si.deliveryCount++;
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011552 if (si.targetPermissionUid >= 0 && si.intent != null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011553 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -070011554 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011555 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011556 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011557 if (!oomAdjusted) {
11558 oomAdjusted = true;
11559 updateOomAdjLocked(r.app);
11560 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011561 int flags = 0;
11562 if (si.deliveryCount > 0) {
11563 flags |= Service.START_FLAG_RETRY;
11564 }
11565 if (si.doneExecutingCount > 0) {
11566 flags |= Service.START_FLAG_REDELIVERY;
11567 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011568 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011569 } catch (RemoteException e) {
11570 // Remote process gone... we'll let the normal cleanup take
11571 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011572 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011573 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011574 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011575 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011576 break;
11577 }
11578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011579 }
11580
11581 private final boolean requestServiceBindingLocked(ServiceRecord r,
11582 IntentBindRecord i, boolean rebind) {
11583 if (r.app == null || r.app.thread == null) {
11584 // If service is not currently running, can't yet bind.
11585 return false;
11586 }
11587 if ((!i.requested || rebind) && i.apps.size() > 0) {
11588 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011589 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011590 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11591 if (!rebind) {
11592 i.requested = true;
11593 }
11594 i.hasBound = true;
11595 i.doRebind = false;
11596 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011597 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011598 return false;
11599 }
11600 }
11601 return true;
11602 }
11603
11604 private final void requestServiceBindingsLocked(ServiceRecord r) {
11605 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11606 while (bindings.hasNext()) {
11607 IntentBindRecord i = bindings.next();
11608 if (!requestServiceBindingLocked(r, i, false)) {
11609 break;
11610 }
11611 }
11612 }
11613
11614 private final void realStartServiceLocked(ServiceRecord r,
11615 ProcessRecord app) throws RemoteException {
11616 if (app.thread == null) {
11617 throw new RemoteException();
11618 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011619 if (DEBUG_MU)
11620 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011621 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011622 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011623 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011624
11625 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011626 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011627 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011628
11629 boolean created = false;
11630 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011631 mStringBuilder.setLength(0);
Dianne Hackborn90c52de2011-09-23 12:57:44 -070011632 r.intent.getIntent().toShortString(mStringBuilder, true, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011633 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011634 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011635 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 synchronized (r.stats.getBatteryStats()) {
11637 r.stats.startLaunchedLocked();
11638 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011639 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011640 app.thread.scheduleCreateService(r, r.serviceInfo,
11641 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011642 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011643 created = true;
11644 } finally {
11645 if (!created) {
11646 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011647 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011648 }
11649 }
11650
11651 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011652
11653 // If the service is in the started state, and there are no
11654 // pending arguments, then fake up one so its onStartCommand() will
11655 // be called.
11656 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011657 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
11658 null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011659 }
11660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011661 sendServiceArgsLocked(r, true);
11662 }
11663
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011664 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11665 boolean allowCancel) {
11666 boolean canceled = false;
11667
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011668 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011669 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011670 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011671
Dianne Hackborn070783f2010-12-29 16:46:28 -080011672 if ((r.serviceInfo.applicationInfo.flags
11673 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11674 minDuration /= 4;
11675 }
11676
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011677 // Any delivered but not yet finished starts should be put back
11678 // on the pending list.
11679 final int N = r.deliveredStarts.size();
11680 if (N > 0) {
11681 for (int i=N-1; i>=0; i--) {
11682 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011683 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011684 if (si.intent == null) {
11685 // We'll generate this again if needed.
11686 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11687 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11688 r.pendingStarts.add(0, si);
11689 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11690 dur *= 2;
11691 if (minDuration < dur) minDuration = dur;
11692 if (resetTime < dur) resetTime = dur;
11693 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011694 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011695 + r.name);
11696 canceled = true;
11697 }
11698 }
11699 r.deliveredStarts.clear();
11700 }
11701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011702 r.totalRestartCount++;
11703 if (r.restartDelay == 0) {
11704 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011705 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011706 } else {
11707 // If it has been a "reasonably long time" since the service
11708 // was started, then reset our restart duration back to
11709 // the beginning, so we don't infinitely increase the duration
11710 // on a service that just occasionally gets killed (which is
11711 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011712 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011713 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011714 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011715 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011716 if ((r.serviceInfo.applicationInfo.flags
11717 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11718 // Services in peristent processes will restart much more
11719 // quickly, since they are pretty important. (Think SystemUI).
11720 r.restartDelay += minDuration/2;
11721 } else {
11722 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11723 if (r.restartDelay < minDuration) {
11724 r.restartDelay = minDuration;
11725 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011727 }
11728 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011729
11730 r.nextRestartTime = now + r.restartDelay;
11731
11732 // Make sure that we don't end up restarting a bunch of services
11733 // all at the same time.
11734 boolean repeat;
11735 do {
11736 repeat = false;
11737 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11738 ServiceRecord r2 = mRestartingServices.get(i);
11739 if (r2 != r && r.nextRestartTime
11740 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11741 && r.nextRestartTime
11742 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11743 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11744 r.restartDelay = r.nextRestartTime - now;
11745 repeat = true;
11746 break;
11747 }
11748 }
11749 } while (repeat);
11750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011751 if (!mRestartingServices.contains(r)) {
11752 mRestartingServices.add(r);
11753 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011754
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011755 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011757 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011758 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011759 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011760 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011761 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011762 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011763 r.shortName, r.restartDelay);
11764
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011765 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011766 }
11767
11768 final void performServiceRestartLocked(ServiceRecord r) {
11769 if (!mRestartingServices.contains(r)) {
11770 return;
11771 }
11772 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11773 }
11774
11775 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11776 if (r.restartDelay == 0) {
11777 return false;
11778 }
11779 r.resetRestartCounter();
11780 mRestartingServices.remove(r);
11781 mHandler.removeCallbacks(r.restarter);
11782 return true;
11783 }
11784
11785 private final boolean bringUpServiceLocked(ServiceRecord r,
11786 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011787 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011788 //r.dump(" ");
11789
Dianne Hackborn36124872009-10-08 16:22:03 -070011790 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011791 sendServiceArgsLocked(r, false);
11792 return true;
11793 }
11794
11795 if (!whileRestarting && r.restartDelay > 0) {
11796 // If waiting for a restart, then do nothing.
11797 return true;
11798 }
11799
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011800 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011801
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011802 // We are now bringing the service up, so no longer in the
11803 // restarting state.
11804 mRestartingServices.remove(r);
11805
Dianne Hackborne7f97212011-02-24 14:40:20 -080011806 // Service is now being launched, its package can't be stopped.
11807 try {
11808 AppGlobals.getPackageManager().setPackageStoppedState(
11809 r.packageName, false);
11810 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011811 } catch (IllegalArgumentException e) {
11812 Slog.w(TAG, "Failed trying to unstop package "
11813 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011814 }
11815
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011816 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011817 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011818 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011819
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011820 if (!isolated) {
11821 app = getProcessRecordLocked(appName, r.appInfo.uid);
11822 if (DEBUG_MU)
11823 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11824 if (app != null && app.thread != null) {
11825 try {
11826 app.addPackage(r.appInfo.packageName);
11827 realStartServiceLocked(r, app);
11828 return true;
11829 } catch (RemoteException e) {
11830 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11831 }
11832
11833 // If a dead object exception was thrown -- fall through to
11834 // restart the application.
11835 }
11836 } else {
11837 // If this service runs in an isolated process, then each time
11838 // we call startProcessLocked() we will get a new isolated
11839 // process, starting another process if we are currently waiting
11840 // for a previous process to come up. To deal with this, we store
11841 // in the service any current isolated process it is running in or
11842 // waiting to have come up.
11843 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011844 }
11845
Dianne Hackborn36124872009-10-08 16:22:03 -070011846 // Not running -- get it started, and enqueue this service record
11847 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011848 if (app == null) {
11849 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11850 "service", r.name, false, isolated)) == null) {
11851 Slog.w(TAG, "Unable to launch app "
11852 + r.appInfo.packageName + "/"
11853 + r.appInfo.uid + " for service "
11854 + r.intent.getIntent() + ": process is bad");
11855 bringDownServiceLocked(r, true);
11856 return false;
11857 }
11858 if (isolated) {
11859 r.isolatedProc = app;
11860 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011861 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011863 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011864 mPendingServices.add(r);
11865 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011867 return true;
11868 }
11869
11870 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011871 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011872 //r.dump(" ");
11873
11874 // Does it still need to run?
11875 if (!force && r.startRequested) {
11876 return;
11877 }
11878 if (r.connections.size() > 0) {
11879 if (!force) {
11880 // XXX should probably keep a count of the number of auto-create
11881 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011882 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011883 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011884 ArrayList<ConnectionRecord> cr = it.next();
11885 for (int i=0; i<cr.size(); i++) {
11886 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11887 return;
11888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011889 }
11890 }
11891 }
11892
11893 // Report to all of the connections that the service is no longer
11894 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011895 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011897 ArrayList<ConnectionRecord> c = it.next();
11898 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011899 ConnectionRecord cr = c.get(i);
11900 // There is still a connection to the service that is
11901 // being brought down. Mark it as dead.
11902 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011903 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011904 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011905 } catch (Exception e) {
11906 Slog.w(TAG, "Failure disconnecting service " + r.name +
11907 " to connection " + c.get(i).conn.asBinder() +
11908 " (in " + c.get(i).binding.client.processName + ")", e);
11909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011910 }
11911 }
11912 }
11913
11914 // Tell the service that it has been unbound.
11915 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11916 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11917 while (it.hasNext()) {
11918 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011919 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011920 + ": hasBound=" + ibr.hasBound);
11921 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11922 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011923 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011924 updateOomAdjLocked(r.app);
11925 ibr.hasBound = false;
11926 r.app.thread.scheduleUnbindService(r,
11927 ibr.intent.getIntent());
11928 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011929 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011930 + r.shortName, e);
11931 serviceDoneExecutingLocked(r, true);
11932 }
11933 }
11934 }
11935 }
11936
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011937 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011938 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011939 System.identityHashCode(r), r.shortName,
11940 (r.app != null) ? r.app.pid : -1);
11941
Amith Yamasani742a6712011-05-04 14:49:28 -070011942 mServiceMap.removeServiceByName(r.name, r.userId);
11943 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011944 r.totalRestartCount = 0;
11945 unscheduleServiceRestartLocked(r);
11946
11947 // Also make sure it is not on the pending list.
11948 int N = mPendingServices.size();
11949 for (int i=0; i<N; i++) {
11950 if (mPendingServices.get(i) == r) {
11951 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011952 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011953 i--;
11954 N--;
11955 }
11956 }
11957
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011958 r.cancelNotification();
11959 r.isForeground = false;
11960 r.foregroundId = 0;
11961 r.foregroundNoti = null;
11962
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011963 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011964 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011965 r.pendingStarts.clear();
11966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011967 if (r.app != null) {
11968 synchronized (r.stats.getBatteryStats()) {
11969 r.stats.stopLaunchedLocked();
11970 }
11971 r.app.services.remove(r);
11972 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011973 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011974 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011975 mStoppingServices.add(r);
11976 updateOomAdjLocked(r.app);
11977 r.app.thread.scheduleStopService(r);
11978 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011979 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011980 + r.shortName, e);
11981 serviceDoneExecutingLocked(r, true);
11982 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011983 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011985 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011986 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011987 }
11988 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011989 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011990 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011991 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011992
11993 if (r.bindings.size() > 0) {
11994 r.bindings.clear();
11995 }
11996
11997 if (r.restarter instanceof ServiceRestarter) {
11998 ((ServiceRestarter)r.restarter).setService(null);
11999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012000 }
12001
12002 ComponentName startServiceLocked(IApplicationThread caller,
12003 Intent service, String resolvedType,
12004 int callingPid, int callingUid) {
12005 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012006 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012007 + " type=" + resolvedType + " args=" + service.getExtras());
12008
12009 if (caller != null) {
12010 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12011 if (callerApp == null) {
12012 throw new SecurityException(
12013 "Unable to find app for caller " + caller
12014 + " (pid=" + Binder.getCallingPid()
12015 + ") when starting service " + service);
12016 }
12017 }
12018
12019 ServiceLookupResult res =
12020 retrieveServiceLocked(service, resolvedType,
12021 callingPid, callingUid);
12022 if (res == null) {
12023 return null;
12024 }
12025 if (res.record == null) {
12026 return new ComponentName("!", res.permission != null
12027 ? res.permission : "private to package");
12028 }
12029 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -070012030 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
12031 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012032 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012033 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012034 }
12035 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012036 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012037 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn39792d22010-08-19 18:01:52 -070012038 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012039 r.lastActivity = SystemClock.uptimeMillis();
12040 synchronized (r.stats.getBatteryStats()) {
12041 r.stats.startRunningLocked();
12042 }
12043 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
12044 return new ComponentName("!", "Service process is bad");
12045 }
12046 return r.name;
12047 }
12048 }
12049
12050 public ComponentName startService(IApplicationThread caller, Intent service,
12051 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012052 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012053 // Refuse possible leaked file descriptors
12054 if (service != null && service.hasFileDescriptors() == true) {
12055 throw new IllegalArgumentException("File descriptors passed in Intent");
12056 }
12057
Amith Yamasani742a6712011-05-04 14:49:28 -070012058 if (DEBUG_SERVICE)
12059 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012060 synchronized(this) {
12061 final int callingPid = Binder.getCallingPid();
12062 final int callingUid = Binder.getCallingUid();
12063 final long origId = Binder.clearCallingIdentity();
12064 ComponentName res = startServiceLocked(caller, service,
12065 resolvedType, callingPid, callingUid);
12066 Binder.restoreCallingIdentity(origId);
12067 return res;
12068 }
12069 }
12070
12071 ComponentName startServiceInPackage(int uid,
12072 Intent service, String resolvedType) {
12073 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070012074 if (DEBUG_SERVICE)
12075 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012076 final long origId = Binder.clearCallingIdentity();
12077 ComponentName res = startServiceLocked(null, service,
12078 resolvedType, -1, uid);
12079 Binder.restoreCallingIdentity(origId);
12080 return res;
12081 }
12082 }
12083
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012084 private void stopServiceLocked(ServiceRecord service) {
12085 synchronized (service.stats.getBatteryStats()) {
12086 service.stats.stopRunningLocked();
12087 }
12088 service.startRequested = false;
12089 service.callStart = false;
12090 bringDownServiceLocked(service, false);
12091 }
12092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012093 public int stopService(IApplicationThread caller, Intent service,
12094 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012095 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012096 // Refuse possible leaked file descriptors
12097 if (service != null && service.hasFileDescriptors() == true) {
12098 throw new IllegalArgumentException("File descriptors passed in Intent");
12099 }
12100
12101 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012102 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012103 + " type=" + resolvedType);
12104
12105 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12106 if (caller != null && callerApp == null) {
12107 throw new SecurityException(
12108 "Unable to find app for caller " + caller
12109 + " (pid=" + Binder.getCallingPid()
12110 + ") when stopping service " + service);
12111 }
12112
12113 // If this service is active, make sure it is stopped.
12114 ServiceLookupResult r = findServiceLocked(service, resolvedType);
12115 if (r != null) {
12116 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012117 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012118 try {
12119 stopServiceLocked(r.record);
12120 } finally {
12121 Binder.restoreCallingIdentity(origId);
12122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012123 return 1;
12124 }
12125 return -1;
12126 }
12127 }
12128
12129 return 0;
12130 }
12131
12132 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012133 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012134 // Refuse possible leaked file descriptors
12135 if (service != null && service.hasFileDescriptors() == true) {
12136 throw new IllegalArgumentException("File descriptors passed in Intent");
12137 }
12138
12139 IBinder ret = null;
12140
12141 synchronized(this) {
12142 ServiceLookupResult r = findServiceLocked(service, resolvedType);
12143
12144 if (r != null) {
12145 // r.record is null if findServiceLocked() failed the caller permission check
12146 if (r.record == null) {
12147 throw new SecurityException(
12148 "Permission Denial: Accessing service " + r.record.name
12149 + " from pid=" + Binder.getCallingPid()
12150 + ", uid=" + Binder.getCallingUid()
12151 + " requires " + r.permission);
12152 }
12153 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
12154 if (ib != null) {
12155 ret = ib.binder;
12156 }
12157 }
12158 }
12159
12160 return ret;
12161 }
12162
12163 public boolean stopServiceToken(ComponentName className, IBinder token,
12164 int startId) {
12165 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012166 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012167 + " " + token + " startId=" + startId);
12168 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012169 if (r != null) {
12170 if (startId >= 0) {
12171 // Asked to only stop if done with all work. Note that
12172 // to avoid leaks, we will take this as dropping all
12173 // start items up to and including this one.
12174 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12175 if (si != null) {
12176 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070012177 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
12178 cur.removeUriPermissionsLocked();
12179 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012180 break;
12181 }
12182 }
12183 }
12184
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012185 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012186 return false;
12187 }
12188
12189 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012190 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012191 + " is last, but have " + r.deliveredStarts.size()
12192 + " remaining args");
12193 }
12194 }
12195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012196 synchronized (r.stats.getBatteryStats()) {
12197 r.stats.stopRunningLocked();
12198 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012199 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012200 }
12201 final long origId = Binder.clearCallingIdentity();
12202 bringDownServiceLocked(r, false);
12203 Binder.restoreCallingIdentity(origId);
12204 return true;
12205 }
12206 }
12207 return false;
12208 }
12209
12210 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012211 int id, Notification notification, boolean removeNotification) {
12212 final long origId = Binder.clearCallingIdentity();
12213 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012214 synchronized(this) {
12215 ServiceRecord r = findServiceLocked(className, token);
12216 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012217 if (id != 0) {
12218 if (notification == null) {
12219 throw new IllegalArgumentException("null notification");
12220 }
12221 if (r.foregroundId != id) {
12222 r.cancelNotification();
12223 r.foregroundId = id;
12224 }
12225 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
12226 r.foregroundNoti = notification;
12227 r.isForeground = true;
12228 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012229 if (r.app != null) {
12230 updateServiceForegroundLocked(r.app, true);
12231 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012232 } else {
12233 if (r.isForeground) {
12234 r.isForeground = false;
12235 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070012236 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012237 updateServiceForegroundLocked(r.app, true);
12238 }
12239 }
12240 if (removeNotification) {
12241 r.cancelNotification();
12242 r.foregroundId = 0;
12243 r.foregroundNoti = null;
12244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012245 }
12246 }
12247 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012248 } finally {
12249 Binder.restoreCallingIdentity(origId);
12250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012251 }
12252
12253 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
12254 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070012255 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012256 if (sr.isForeground) {
12257 anyForeground = true;
12258 break;
12259 }
12260 }
12261 if (anyForeground != proc.foregroundServices) {
12262 proc.foregroundServices = anyForeground;
12263 if (oomAdj) {
12264 updateOomAdjLocked();
12265 }
12266 }
12267 }
12268
12269 public int bindService(IApplicationThread caller, IBinder token,
12270 Intent service, String resolvedType,
12271 IServiceConnection connection, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012272 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012273 // Refuse possible leaked file descriptors
12274 if (service != null && service.hasFileDescriptors() == true) {
12275 throw new IllegalArgumentException("File descriptors passed in Intent");
12276 }
12277
12278 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012279 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012280 + " type=" + resolvedType + " conn=" + connection.asBinder()
12281 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070012282 if (DEBUG_MU)
12283 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
12284 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012285 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12286 if (callerApp == null) {
12287 throw new SecurityException(
12288 "Unable to find app for caller " + caller
12289 + " (pid=" + Binder.getCallingPid()
12290 + ") when binding service " + service);
12291 }
12292
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012293 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012294 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012295 activity = mMainStack.isInStackLocked(token);
12296 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012297 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012298 return 0;
12299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012300 }
12301
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012302 int clientLabel = 0;
12303 PendingIntent clientIntent = null;
12304
12305 if (callerApp.info.uid == Process.SYSTEM_UID) {
12306 // Hacky kind of thing -- allow system stuff to tell us
12307 // what they are, so we can report this elsewhere for
12308 // others to know why certain services are running.
12309 try {
12310 clientIntent = (PendingIntent)service.getParcelableExtra(
12311 Intent.EXTRA_CLIENT_INTENT);
12312 } catch (RuntimeException e) {
12313 }
12314 if (clientIntent != null) {
12315 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
12316 if (clientLabel != 0) {
12317 // There are no useful extras in the intent, trash them.
12318 // System code calling with this stuff just needs to know
12319 // this will happen.
12320 service = service.cloneFilter();
12321 }
12322 }
12323 }
12324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012325 ServiceLookupResult res =
12326 retrieveServiceLocked(service, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -070012327 Binder.getCallingPid(), Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012328 if (res == null) {
12329 return 0;
12330 }
12331 if (res.record == null) {
12332 return -1;
12333 }
12334 ServiceRecord s = res.record;
12335
12336 final long origId = Binder.clearCallingIdentity();
12337
12338 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012339 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012340 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012341 }
12342
12343 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
12344 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012345 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012346
12347 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012348 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12349 if (clist == null) {
12350 clist = new ArrayList<ConnectionRecord>();
12351 s.connections.put(binder, clist);
12352 }
12353 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012354 b.connections.add(c);
12355 if (activity != null) {
12356 if (activity.connections == null) {
12357 activity.connections = new HashSet<ConnectionRecord>();
12358 }
12359 activity.connections.add(c);
12360 }
12361 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012362 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12363 b.client.hasAboveClient = true;
12364 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012365 clist = mServiceConnections.get(binder);
12366 if (clist == null) {
12367 clist = new ArrayList<ConnectionRecord>();
12368 mServiceConnections.put(binder, clist);
12369 }
12370 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012371
12372 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
12373 s.lastActivity = SystemClock.uptimeMillis();
12374 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
12375 return 0;
12376 }
12377 }
12378
12379 if (s.app != null) {
12380 // This could have made the service more important.
12381 updateOomAdjLocked(s.app);
12382 }
12383
Joe Onorato8a9b2202010-02-26 18:56:32 -080012384 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012385 + ": received=" + b.intent.received
12386 + " apps=" + b.intent.apps.size()
12387 + " doRebind=" + b.intent.doRebind);
12388
12389 if (s.app != null && b.intent.received) {
12390 // Service is already running, so we can immediately
12391 // publish the connection.
12392 try {
12393 c.conn.connected(s.name, b.intent.binder);
12394 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012395 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012396 + " to connection " + c.conn.asBinder()
12397 + " (in " + c.binding.client.processName + ")", e);
12398 }
12399
12400 // If this is the first app connected back to this binding,
12401 // and the service had previously asked to be told when
12402 // rebound, then do so.
12403 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
12404 requestServiceBindingLocked(s, b.intent, true);
12405 }
12406 } else if (!b.intent.requested) {
12407 requestServiceBindingLocked(s, b.intent, false);
12408 }
12409
12410 Binder.restoreCallingIdentity(origId);
12411 }
12412
12413 return 1;
12414 }
12415
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012416 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012417 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012418 IBinder binder = c.conn.asBinder();
12419 AppBindRecord b = c.binding;
12420 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012421 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12422 if (clist != null) {
12423 clist.remove(c);
12424 if (clist.size() == 0) {
12425 s.connections.remove(binder);
12426 }
12427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012428 b.connections.remove(c);
12429 if (c.activity != null && c.activity != skipAct) {
12430 if (c.activity.connections != null) {
12431 c.activity.connections.remove(c);
12432 }
12433 }
12434 if (b.client != skipApp) {
12435 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012436 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12437 b.client.updateHasAboveClientLocked();
12438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012440 clist = mServiceConnections.get(binder);
12441 if (clist != null) {
12442 clist.remove(c);
12443 if (clist.size() == 0) {
12444 mServiceConnections.remove(binder);
12445 }
12446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012447
12448 if (b.connections.size() == 0) {
12449 b.intent.apps.remove(b.client);
12450 }
12451
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012452 if (!c.serviceDead) {
12453 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
12454 + ": shouldUnbind=" + b.intent.hasBound);
12455 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
12456 && b.intent.hasBound) {
12457 try {
12458 bumpServiceExecutingLocked(s, "unbind");
12459 updateOomAdjLocked(s.app);
12460 b.intent.hasBound = false;
12461 // Assume the client doesn't want to know about a rebind;
12462 // we will deal with that later if it asks for one.
12463 b.intent.doRebind = false;
12464 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
12465 } catch (Exception e) {
12466 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
12467 serviceDoneExecutingLocked(s, true);
12468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012469 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012470
12471 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
12472 bringDownServiceLocked(s, false);
12473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012474 }
12475 }
12476
12477 public boolean unbindService(IServiceConnection connection) {
12478 synchronized (this) {
12479 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012480 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012481 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
12482 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012483 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012484 + connection.asBinder());
12485 return false;
12486 }
12487
12488 final long origId = Binder.clearCallingIdentity();
12489
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012490 while (clist.size() > 0) {
12491 ConnectionRecord r = clist.get(0);
12492 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012493
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012494 if (r.binding.service.app != null) {
12495 // This could have made the service less important.
12496 updateOomAdjLocked(r.binding.service.app);
12497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012498 }
12499
12500 Binder.restoreCallingIdentity(origId);
12501 }
12502
12503 return true;
12504 }
12505
12506 public void publishService(IBinder token, Intent intent, IBinder service) {
12507 // Refuse possible leaked file descriptors
12508 if (intent != null && intent.hasFileDescriptors() == true) {
12509 throw new IllegalArgumentException("File descriptors passed in Intent");
12510 }
12511
12512 synchronized(this) {
12513 if (!(token instanceof ServiceRecord)) {
12514 throw new IllegalArgumentException("Invalid service token");
12515 }
12516 ServiceRecord r = (ServiceRecord)token;
12517
12518 final long origId = Binder.clearCallingIdentity();
12519
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012520 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012521 + " " + intent + ": " + service);
12522 if (r != null) {
12523 Intent.FilterComparison filter
12524 = new Intent.FilterComparison(intent);
12525 IntentBindRecord b = r.bindings.get(filter);
12526 if (b != null && !b.received) {
12527 b.binder = service;
12528 b.requested = true;
12529 b.received = true;
12530 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012531 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012532 = r.connections.values().iterator();
12533 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012534 ArrayList<ConnectionRecord> clist = it.next();
12535 for (int i=0; i<clist.size(); i++) {
12536 ConnectionRecord c = clist.get(i);
12537 if (!filter.equals(c.binding.intent.intent)) {
12538 if (DEBUG_SERVICE) Slog.v(
12539 TAG, "Not publishing to: " + c);
12540 if (DEBUG_SERVICE) Slog.v(
12541 TAG, "Bound intent: " + c.binding.intent.intent);
12542 if (DEBUG_SERVICE) Slog.v(
12543 TAG, "Published intent: " + intent);
12544 continue;
12545 }
12546 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12547 try {
12548 c.conn.connected(r.name, service);
12549 } catch (Exception e) {
12550 Slog.w(TAG, "Failure sending service " + r.name +
12551 " to connection " + c.conn.asBinder() +
12552 " (in " + c.binding.client.processName + ")", e);
12553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012554 }
12555 }
12556 }
12557 }
12558
12559 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12560
12561 Binder.restoreCallingIdentity(origId);
12562 }
12563 }
12564 }
12565
12566 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12567 // Refuse possible leaked file descriptors
12568 if (intent != null && intent.hasFileDescriptors() == true) {
12569 throw new IllegalArgumentException("File descriptors passed in Intent");
12570 }
12571
12572 synchronized(this) {
12573 if (!(token instanceof ServiceRecord)) {
12574 throw new IllegalArgumentException("Invalid service token");
12575 }
12576 ServiceRecord r = (ServiceRecord)token;
12577
12578 final long origId = Binder.clearCallingIdentity();
12579
12580 if (r != null) {
12581 Intent.FilterComparison filter
12582 = new Intent.FilterComparison(intent);
12583 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012584 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585 + " at " + b + ": apps="
12586 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012587
12588 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012589 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012590 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012591 // Applications have already bound since the last
12592 // unbind, so just rebind right here.
12593 requestServiceBindingLocked(r, b, true);
12594 } else {
12595 // Note to tell the service the next time there is
12596 // a new client.
12597 b.doRebind = true;
12598 }
12599 }
12600
Per Edelberg78f9fff2010-08-30 20:01:35 +020012601 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012602
12603 Binder.restoreCallingIdentity(origId);
12604 }
12605 }
12606 }
12607
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012608 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012609 synchronized(this) {
12610 if (!(token instanceof ServiceRecord)) {
12611 throw new IllegalArgumentException("Invalid service token");
12612 }
12613 ServiceRecord r = (ServiceRecord)token;
12614 boolean inStopping = mStoppingServices.contains(token);
12615 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012616 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012617 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012618 + " with incorrect token: given " + token
12619 + ", expected " + r);
12620 return;
12621 }
12622
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012623 if (type == 1) {
12624 // This is a call from a service start... take care of
12625 // book-keeping.
12626 r.callStart = true;
12627 switch (res) {
12628 case Service.START_STICKY_COMPATIBILITY:
12629 case Service.START_STICKY: {
12630 // We are done with the associated start arguments.
12631 r.findDeliveredStart(startId, true);
12632 // Don't stop if killed.
12633 r.stopIfKilled = false;
12634 break;
12635 }
12636 case Service.START_NOT_STICKY: {
12637 // We are done with the associated start arguments.
12638 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012639 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012640 // There is no more work, and this service
12641 // doesn't want to hang around if killed.
12642 r.stopIfKilled = true;
12643 }
12644 break;
12645 }
12646 case Service.START_REDELIVER_INTENT: {
12647 // We'll keep this item until they explicitly
12648 // call stop for it, but keep track of the fact
12649 // that it was delivered.
12650 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12651 if (si != null) {
12652 si.deliveryCount = 0;
12653 si.doneExecutingCount++;
12654 // Don't stop if killed.
12655 r.stopIfKilled = true;
12656 }
12657 break;
12658 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012659 case Service.START_TASK_REMOVED_COMPLETE: {
12660 // Special processing for onTaskRemoved(). Don't
12661 // impact normal onStartCommand() processing.
12662 r.findDeliveredStart(startId, true);
12663 break;
12664 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012665 default:
12666 throw new IllegalArgumentException(
12667 "Unknown service start result: " + res);
12668 }
12669 if (res == Service.START_STICKY_COMPATIBILITY) {
12670 r.callStart = false;
12671 }
12672 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012673 if (DEBUG_MU)
12674 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12675 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012676 final long origId = Binder.clearCallingIdentity();
12677 serviceDoneExecutingLocked(r, inStopping);
12678 Binder.restoreCallingIdentity(origId);
12679 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012680 Slog.w(TAG, "Done executing unknown service from pid "
12681 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012682 }
12683 }
12684 }
12685
12686 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012687 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12688 + ": nesting=" + r.executeNesting
12689 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012690 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012691 r.executeNesting--;
12692 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012693 if (DEBUG_SERVICE) Slog.v(TAG,
12694 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012695 r.app.executingServices.remove(r);
12696 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012697 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12698 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012699 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12700 }
12701 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012702 if (DEBUG_SERVICE) Slog.v(TAG,
12703 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012704 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012705 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012706 }
12707 updateOomAdjLocked(r.app);
12708 }
12709 }
12710
12711 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012712 String anrMessage = null;
12713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012714 synchronized(this) {
12715 if (proc.executingServices.size() == 0 || proc.thread == null) {
12716 return;
12717 }
12718 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12719 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12720 ServiceRecord timeout = null;
12721 long nextTime = 0;
12722 while (it.hasNext()) {
12723 ServiceRecord sr = it.next();
12724 if (sr.executingStart < maxTime) {
12725 timeout = sr;
12726 break;
12727 }
12728 if (sr.executingStart > nextTime) {
12729 nextTime = sr.executingStart;
12730 }
12731 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012732 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012733 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012734 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012735 } else {
12736 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12737 msg.obj = proc;
12738 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12739 }
12740 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012741
12742 if (anrMessage != null) {
12743 appNotResponding(proc, null, null, anrMessage);
12744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012745 }
12746
12747 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012748 // BACKUP AND RESTORE
12749 // =========================================================
12750
12751 // Cause the target app to be launched if necessary and its backup agent
12752 // instantiated. The backup agent will invoke backupAgentCreated() on the
12753 // activity manager to announce its creation.
12754 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012755 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012756 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12757
12758 synchronized(this) {
12759 // !!! TODO: currently no check here that we're already bound
12760 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12761 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12762 synchronized (stats) {
12763 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12764 }
12765
Dianne Hackborne7f97212011-02-24 14:40:20 -080012766 // Backup agent is now in use, its package can't be stopped.
12767 try {
12768 AppGlobals.getPackageManager().setPackageStoppedState(
12769 app.packageName, false);
12770 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012771 } catch (IllegalArgumentException e) {
12772 Slog.w(TAG, "Failed trying to unstop package "
12773 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012774 }
12775
Christopher Tate181fafa2009-05-14 11:12:14 -070012776 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012777 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12778 ? new ComponentName(app.packageName, app.backupAgentName)
12779 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012780 // startProcessLocked() returns existing proc's record if it's already running
12781 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012782 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012783 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012784 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012785 return false;
12786 }
12787
12788 r.app = proc;
12789 mBackupTarget = r;
12790 mBackupAppName = app.packageName;
12791
Christopher Tate6fa95972009-06-05 18:43:55 -070012792 // Try not to kill the process during backup
12793 updateOomAdjLocked(proc);
12794
Christopher Tate181fafa2009-05-14 11:12:14 -070012795 // If the process is already attached, schedule the creation of the backup agent now.
12796 // If it is not yet live, this will be done when it attaches to the framework.
12797 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012798 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012799 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012800 proc.thread.scheduleCreateBackupAgent(app,
12801 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012802 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012803 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012804 }
12805 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012806 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012807 }
12808 // Invariants: at this point, the target app process exists and the application
12809 // is either already running or in the process of coming up. mBackupTarget and
12810 // mBackupAppName describe the app, so that when it binds back to the AM we
12811 // know that it's scheduled for a backup-agent operation.
12812 }
12813
12814 return true;
12815 }
12816
12817 // A backup agent has just come up
12818 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012819 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012820 + " = " + agent);
12821
12822 synchronized(this) {
12823 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012824 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012825 return;
12826 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012827 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012828
Dianne Hackborn06740692010-09-22 22:46:21 -070012829 long oldIdent = Binder.clearCallingIdentity();
12830 try {
12831 IBackupManager bm = IBackupManager.Stub.asInterface(
12832 ServiceManager.getService(Context.BACKUP_SERVICE));
12833 bm.agentConnected(agentPackageName, agent);
12834 } catch (RemoteException e) {
12835 // can't happen; the backup manager service is local
12836 } catch (Exception e) {
12837 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12838 e.printStackTrace();
12839 } finally {
12840 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012841 }
12842 }
12843
12844 // done with this agent
12845 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012846 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012847 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012848 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012849 return;
12850 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012851
12852 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012853 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012854 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012855 return;
12856 }
12857
Christopher Tate181fafa2009-05-14 11:12:14 -070012858 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012859 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012860 return;
12861 }
12862
Christopher Tate6fa95972009-06-05 18:43:55 -070012863 ProcessRecord proc = mBackupTarget.app;
12864 mBackupTarget = null;
12865 mBackupAppName = null;
12866
12867 // Not backing this app up any more; reset its OOM adjustment
12868 updateOomAdjLocked(proc);
12869
Christopher Tatec7b31e32009-06-10 15:49:30 -070012870 // If the app crashed during backup, 'thread' will be null here
12871 if (proc.thread != null) {
12872 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012873 proc.thread.scheduleDestroyBackupAgent(appInfo,
12874 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012875 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012876 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012877 e.printStackTrace();
12878 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012879 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012880 }
12881 }
12882 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012883 // BROADCASTS
12884 // =========================================================
12885
Josh Bartel7f208742010-02-25 11:01:44 -060012886 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012887 List cur) {
12888 final ContentResolver resolver = mContext.getContentResolver();
12889 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12890 if (list == null) {
12891 return cur;
12892 }
12893 int N = list.size();
12894 for (int i=0; i<N; i++) {
12895 Intent intent = list.get(i);
12896 if (filter.match(resolver, intent, true, TAG) >= 0) {
12897 if (cur == null) {
12898 cur = new ArrayList<Intent>();
12899 }
12900 cur.add(intent);
12901 }
12902 }
12903 return cur;
12904 }
12905
Christopher Tatef46723b2012-01-26 14:19:24 -080012906 boolean isPendingBroadcastProcessLocked(int pid) {
12907 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12908 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012910
Christopher Tatef46723b2012-01-26 14:19:24 -080012911 void skipPendingBroadcastLocked(int pid) {
12912 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12913 for (BroadcastQueue queue : mBroadcastQueues) {
12914 queue.skipPendingBroadcastLocked(pid);
12915 }
12916 }
12917
12918 // The app just attached; send any pending broadcasts that it should receive
12919 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12920 boolean didSomething = false;
12921 for (BroadcastQueue queue : mBroadcastQueues) {
12922 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012923 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012924 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012925 }
12926
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012927 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012929 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012930 synchronized(this) {
12931 ProcessRecord callerApp = null;
12932 if (caller != null) {
12933 callerApp = getRecordForAppLocked(caller);
12934 if (callerApp == null) {
12935 throw new SecurityException(
12936 "Unable to find app for caller " + caller
12937 + " (pid=" + Binder.getCallingPid()
12938 + ") when registering receiver " + receiver);
12939 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012940 if (callerApp.info.uid != Process.SYSTEM_UID &&
12941 !callerApp.pkgList.contains(callerPackage)) {
12942 throw new SecurityException("Given caller package " + callerPackage
12943 + " is not running in process " + callerApp);
12944 }
12945 } else {
12946 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012947 }
12948
12949 List allSticky = null;
12950
12951 // Look for any matching sticky broadcasts...
12952 Iterator actions = filter.actionsIterator();
12953 if (actions != null) {
12954 while (actions.hasNext()) {
12955 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012956 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012957 }
12958 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012959 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012960 }
12961
12962 // The first sticky in the list is returned directly back to
12963 // the client.
12964 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12965
Joe Onorato8a9b2202010-02-26 18:56:32 -080012966 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012967 + ": " + sticky);
12968
12969 if (receiver == null) {
12970 return sticky;
12971 }
12972
12973 ReceiverList rl
12974 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12975 if (rl == null) {
12976 rl = new ReceiverList(this, callerApp,
12977 Binder.getCallingPid(),
12978 Binder.getCallingUid(), receiver);
12979 if (rl.app != null) {
12980 rl.app.receivers.add(rl);
12981 } else {
12982 try {
12983 receiver.asBinder().linkToDeath(rl, 0);
12984 } catch (RemoteException e) {
12985 return sticky;
12986 }
12987 rl.linkedToDeath = true;
12988 }
12989 mRegisteredReceivers.put(receiver.asBinder(), rl);
12990 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012991 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012992 rl.add(bf);
12993 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012994 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012995 }
12996 mReceiverResolver.addFilter(bf);
12997
12998 // Enqueue broadcasts for all existing stickies that match
12999 // this filter.
13000 if (allSticky != null) {
13001 ArrayList receivers = new ArrayList();
13002 receivers.add(bf);
13003
13004 int N = allSticky.size();
13005 for (int i=0; i<N; i++) {
13006 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080013007 BroadcastQueue queue = broadcastQueueForIntent(intent);
13008 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013009 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013010 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080013011 queue.enqueueParallelBroadcastLocked(r);
13012 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013013 }
13014 }
13015
13016 return sticky;
13017 }
13018 }
13019
13020 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013021 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013022
Christopher Tatef46723b2012-01-26 14:19:24 -080013023 final long origId = Binder.clearCallingIdentity();
13024 try {
13025 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013026
Christopher Tatef46723b2012-01-26 14:19:24 -080013027 synchronized(this) {
13028 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013029 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080013030 if (rl != null) {
13031 if (rl.curBroadcast != null) {
13032 BroadcastRecord r = rl.curBroadcast;
13033 final boolean doNext = finishReceiverLocked(
13034 receiver.asBinder(), r.resultCode, r.resultData,
13035 r.resultExtras, r.resultAbort, true);
13036 if (doNext) {
13037 doTrim = true;
13038 r.queue.processNextBroadcast(false);
13039 }
13040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013041
Christopher Tatef46723b2012-01-26 14:19:24 -080013042 if (rl.app != null) {
13043 rl.app.receivers.remove(rl);
13044 }
13045 removeReceiverLocked(rl);
13046 if (rl.linkedToDeath) {
13047 rl.linkedToDeath = false;
13048 rl.receiver.asBinder().unlinkToDeath(rl, 0);
13049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013050 }
13051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013052
Christopher Tatef46723b2012-01-26 14:19:24 -080013053 // If we actually concluded any broadcasts, we might now be able
13054 // to trim the recipients' apps from our working set
13055 if (doTrim) {
13056 trimApplications();
13057 return;
13058 }
13059
13060 } finally {
13061 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063 }
13064
13065 void removeReceiverLocked(ReceiverList rl) {
13066 mRegisteredReceivers.remove(rl.receiver.asBinder());
13067 int N = rl.size();
13068 for (int i=0; i<N; i++) {
13069 mReceiverResolver.removeFilter(rl.get(i));
13070 }
13071 }
13072
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070013073 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
13074 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13075 ProcessRecord r = mLruProcesses.get(i);
13076 if (r.thread != null) {
13077 try {
13078 r.thread.dispatchPackageBroadcast(cmd, packages);
13079 } catch (RemoteException ex) {
13080 }
13081 }
13082 }
13083 }
13084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013085 private final int broadcastIntentLocked(ProcessRecord callerApp,
13086 String callerPackage, Intent intent, String resolvedType,
13087 IIntentReceiver resultTo, int resultCode, String resultData,
13088 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013089 boolean ordered, boolean sticky, int callingPid, int callingUid,
13090 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013091 intent = new Intent(intent);
13092
Dianne Hackborne7f97212011-02-24 14:40:20 -080013093 // By default broadcasts do not go to stopped apps.
13094 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
13095
Joe Onorato8a9b2202010-02-26 18:56:32 -080013096 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013097 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
13098 + " ordered=" + ordered);
13099 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013100 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013101 }
13102
13103 // Handle special intents: if this broadcast is from the package
13104 // manager about a package being removed, we need to remove all of
13105 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013106 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013107 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013108 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
13109 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080013110 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013111 || uidRemoved) {
13112 if (checkComponentPermission(
13113 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080013114 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013115 == PackageManager.PERMISSION_GRANTED) {
13116 if (uidRemoved) {
13117 final Bundle intentExtras = intent.getExtras();
13118 final int uid = intentExtras != null
13119 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
13120 if (uid >= 0) {
13121 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
13122 synchronized (bs) {
13123 bs.removeUidStatsLocked(uid);
13124 }
13125 }
13126 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013127 // If resources are unvailble just force stop all
13128 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080013129 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013130 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
13131 if (list != null && (list.length > 0)) {
13132 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070013133 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013134 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070013135 sendPackageBroadcastLocked(
13136 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013137 }
13138 } else {
13139 Uri data = intent.getData();
13140 String ssp;
13141 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
13142 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
13143 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070013144 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070013145 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013146 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070013147 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
13148 new String[] {ssp});
13149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013150 }
13151 }
13152 }
13153 } else {
13154 String msg = "Permission Denial: " + intent.getAction()
13155 + " broadcast from " + callerPackage + " (pid=" + callingPid
13156 + ", uid=" + callingUid + ")"
13157 + " requires "
13158 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013159 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013160 throw new SecurityException(msg);
13161 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013162
13163 // Special case for adding a package: by default turn on compatibility
13164 // mode.
13165 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070013166 Uri data = intent.getData();
13167 String ssp;
13168 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
13169 mCompatModePackages.handlePackageAddedLocked(ssp,
13170 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013172 }
13173
13174 /*
13175 * If this is the time zone changed action, queue up a message that will reset the timezone
13176 * of all currently running processes. This message will get queued up before the broadcast
13177 * happens.
13178 */
13179 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
13180 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
13181 }
13182
Robert Greenwalt03595d02010-11-02 14:08:23 -070013183 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
13184 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
13185 }
13186
Robert Greenwalt434203a2010-10-11 16:00:27 -070013187 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
13188 ProxyProperties proxy = intent.getParcelableExtra("proxy");
13189 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
13190 }
13191
Dianne Hackborn854060af2009-07-09 18:14:31 -070013192 /*
13193 * Prevent non-system code (defined here to be non-persistent
13194 * processes) from sending protected broadcasts.
13195 */
13196 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
13197 || callingUid == Process.SHELL_UID || callingUid == 0) {
13198 // Always okay.
13199 } else if (callerApp == null || !callerApp.persistent) {
13200 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013201 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070013202 intent.getAction())) {
13203 String msg = "Permission Denial: not allowed to send broadcast "
13204 + intent.getAction() + " from pid="
13205 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013206 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070013207 throw new SecurityException(msg);
13208 }
13209 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013210 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070013211 return BROADCAST_SUCCESS;
13212 }
13213 }
13214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013215 // Add to the sticky list if requested.
13216 if (sticky) {
13217 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
13218 callingPid, callingUid)
13219 != PackageManager.PERMISSION_GRANTED) {
13220 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
13221 + callingPid + ", uid=" + callingUid
13222 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013223 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013224 throw new SecurityException(msg);
13225 }
13226 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013227 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013228 + " and enforce permission " + requiredPermission);
13229 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
13230 }
13231 if (intent.getComponent() != null) {
13232 throw new SecurityException(
13233 "Sticky broadcasts can't target a specific component");
13234 }
13235 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13236 if (list == null) {
13237 list = new ArrayList<Intent>();
13238 mStickyBroadcasts.put(intent.getAction(), list);
13239 }
13240 int N = list.size();
13241 int i;
13242 for (i=0; i<N; i++) {
13243 if (intent.filterEquals(list.get(i))) {
13244 // This sticky already exists, replace it.
13245 list.set(i, new Intent(intent));
13246 break;
13247 }
13248 }
13249 if (i >= N) {
13250 list.add(new Intent(intent));
13251 }
13252 }
13253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013254 // Figure out who all will receive this broadcast.
13255 List receivers = null;
13256 List<BroadcastFilter> registeredReceivers = null;
13257 try {
13258 if (intent.getComponent() != null) {
13259 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013260 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070013261 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013262 if (ai != null) {
13263 receivers = new ArrayList();
13264 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070013265 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013266 receivers.add(ri);
13267 }
13268 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070013269 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013270 // Need to resolve the intent to interested receivers...
13271 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
13272 == 0) {
13273 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013274 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013275 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013276 }
Mihai Preda074edef2009-05-18 17:13:31 +020013277 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013278 }
13279 } catch (RemoteException ex) {
13280 // pm is in same process, this will never happen.
13281 }
13282
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013283 final boolean replacePending =
13284 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
13285
Joe Onorato8a9b2202010-02-26 18:56:32 -080013286 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013287 + " replacePending=" + replacePending);
13288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013289 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
13290 if (!ordered && NR > 0) {
13291 // If we are not serializing this broadcast, then send the
13292 // registered receivers separately so they don't wait for the
13293 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080013294 final BroadcastQueue queue = broadcastQueueForIntent(intent);
13295 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013296 callerPackage, callingPid, callingUid, requiredPermission,
13297 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013298 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013299 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080013300 TAG, "Enqueueing parallel broadcast " + r);
13301 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013302 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013303 queue.enqueueParallelBroadcastLocked(r);
13304 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013306 registeredReceivers = null;
13307 NR = 0;
13308 }
13309
13310 // Merge into one list.
13311 int ir = 0;
13312 if (receivers != null) {
13313 // A special case for PACKAGE_ADDED: do not allow the package
13314 // being added to see this broadcast. This prevents them from
13315 // using this as a back door to get run as soon as they are
13316 // installed. Maybe in the future we want to have a special install
13317 // broadcast or such for apps, but we'd like to deliberately make
13318 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013319 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013320 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
13321 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
13322 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013323 Uri data = intent.getData();
13324 if (data != null) {
13325 String pkgName = data.getSchemeSpecificPart();
13326 if (pkgName != null) {
13327 skipPackages = new String[] { pkgName };
13328 }
13329 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013330 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013331 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070013332 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013333 if (skipPackages != null && (skipPackages.length > 0)) {
13334 for (String skipPackage : skipPackages) {
13335 if (skipPackage != null) {
13336 int NT = receivers.size();
13337 for (int it=0; it<NT; it++) {
13338 ResolveInfo curt = (ResolveInfo)receivers.get(it);
13339 if (curt.activityInfo.packageName.equals(skipPackage)) {
13340 receivers.remove(it);
13341 it--;
13342 NT--;
13343 }
13344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013345 }
13346 }
13347 }
13348
13349 int NT = receivers != null ? receivers.size() : 0;
13350 int it = 0;
13351 ResolveInfo curt = null;
13352 BroadcastFilter curr = null;
13353 while (it < NT && ir < NR) {
13354 if (curt == null) {
13355 curt = (ResolveInfo)receivers.get(it);
13356 }
13357 if (curr == null) {
13358 curr = registeredReceivers.get(ir);
13359 }
13360 if (curr.getPriority() >= curt.priority) {
13361 // Insert this broadcast record into the final list.
13362 receivers.add(it, curr);
13363 ir++;
13364 curr = null;
13365 it++;
13366 NT++;
13367 } else {
13368 // Skip to the next ResolveInfo in the final list.
13369 it++;
13370 curt = null;
13371 }
13372 }
13373 }
13374 while (ir < NR) {
13375 if (receivers == null) {
13376 receivers = new ArrayList();
13377 }
13378 receivers.add(registeredReceivers.get(ir));
13379 ir++;
13380 }
13381
13382 if ((receivers != null && receivers.size() > 0)
13383 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013384 BroadcastQueue queue = broadcastQueueForIntent(intent);
13385 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013386 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013387 receivers, resultTo, resultCode, resultData, map, ordered,
13388 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013389 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013390 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080013391 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013392 if (DEBUG_BROADCAST) {
13393 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013394 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013395 }
Christopher Tatef46723b2012-01-26 14:19:24 -080013396 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013397 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013398 queue.enqueueOrderedBroadcastLocked(r);
13399 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013401 }
13402
13403 return BROADCAST_SUCCESS;
13404 }
13405
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013406 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013407 // Refuse possible leaked file descriptors
13408 if (intent != null && intent.hasFileDescriptors() == true) {
13409 throw new IllegalArgumentException("File descriptors passed in Intent");
13410 }
13411
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013412 int flags = intent.getFlags();
13413
13414 if (!mProcessesReady) {
13415 // if the caller really truly claims to know what they're doing, go
13416 // ahead and allow the broadcast without launching any receivers
13417 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
13418 intent = new Intent(intent);
13419 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13420 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
13421 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
13422 + " before boot completion");
13423 throw new IllegalStateException("Cannot broadcast before boot completed");
13424 }
13425 }
13426
13427 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
13428 throw new IllegalArgumentException(
13429 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
13430 }
13431
13432 return intent;
13433 }
13434
13435 public final int broadcastIntent(IApplicationThread caller,
13436 Intent intent, String resolvedType, IIntentReceiver resultTo,
13437 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013438 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013439 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013440 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013441 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070013442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013443 final ProcessRecord callerApp = getRecordForAppLocked(caller);
13444 final int callingPid = Binder.getCallingPid();
13445 final int callingUid = Binder.getCallingUid();
13446 final long origId = Binder.clearCallingIdentity();
13447 int res = broadcastIntentLocked(callerApp,
13448 callerApp != null ? callerApp.info.packageName : null,
13449 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070013450 resultCode, resultData, map, requiredPermission, serialized, sticky,
13451 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013452 Binder.restoreCallingIdentity(origId);
13453 return res;
13454 }
13455 }
13456
13457 int broadcastIntentInPackage(String packageName, int uid,
13458 Intent intent, String resolvedType, IIntentReceiver resultTo,
13459 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013460 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013461 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013462 intent = verifyBroadcastLocked(intent);
13463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013464 final long origId = Binder.clearCallingIdentity();
13465 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
13466 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013467 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013468 Binder.restoreCallingIdentity(origId);
13469 return res;
13470 }
13471 }
13472
Amith Yamasani742a6712011-05-04 14:49:28 -070013473 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
13474 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013475 // Refuse possible leaked file descriptors
13476 if (intent != null && intent.hasFileDescriptors() == true) {
13477 throw new IllegalArgumentException("File descriptors passed in Intent");
13478 }
13479
13480 synchronized(this) {
13481 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13482 != PackageManager.PERMISSION_GRANTED) {
13483 String msg = "Permission Denial: unbroadcastIntent() from pid="
13484 + Binder.getCallingPid()
13485 + ", uid=" + Binder.getCallingUid()
13486 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013487 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013488 throw new SecurityException(msg);
13489 }
13490 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13491 if (list != null) {
13492 int N = list.size();
13493 int i;
13494 for (i=0; i<N; i++) {
13495 if (intent.filterEquals(list.get(i))) {
13496 list.remove(i);
13497 break;
13498 }
13499 }
13500 }
13501 }
13502 }
13503
13504 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13505 String resultData, Bundle resultExtras, boolean resultAbort,
13506 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013507 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13508 if (r == null) {
13509 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013510 return false;
13511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013512
Christopher Tatef46723b2012-01-26 14:19:24 -080013513 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13514 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013515 }
13516
13517 public void finishReceiver(IBinder who, int resultCode, String resultData,
13518 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013519 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013520
13521 // Refuse possible leaked file descriptors
13522 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13523 throw new IllegalArgumentException("File descriptors passed in Bundle");
13524 }
13525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013526 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013527 try {
13528 boolean doNext = false;
13529 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013530
Christopher Tatef46723b2012-01-26 14:19:24 -080013531 synchronized(this) {
13532 r = broadcastRecordForReceiverLocked(who);
13533 if (r != null) {
13534 doNext = r.queue.finishReceiverLocked(r, resultCode,
13535 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013537 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013538
Christopher Tatef46723b2012-01-26 14:19:24 -080013539 if (doNext) {
13540 r.queue.processNextBroadcast(false);
13541 }
13542 trimApplications();
13543 } finally {
13544 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013546 }
13547
13548 private final void processCurBroadcastLocked(BroadcastRecord r,
13549 ProcessRecord app) throws RemoteException {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013550 if (DEBUG_BROADCAST) Slog.v(TAG,
13551 "Process cur broadcast " + r + " for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013552 if (app.thread == null) {
13553 throw new RemoteException();
13554 }
13555 r.receiver = app.thread.asBinder();
13556 r.curApp = app;
13557 app.curReceiver = r;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013558 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013559
13560 // Tell the application to launch this receiver.
13561 r.intent.setComponent(r.curComponent);
13562
13563 boolean started = false;
13564 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013565 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013566 "Delivering to component " + r.curComponent
13567 + ": " + r);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070013568 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013569 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
Dianne Hackborne2515ee2011-04-27 18:52:56 -040013570 compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013571 r.resultCode, r.resultData, r.resultExtras, r.ordered);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013572 if (DEBUG_BROADCAST) Slog.v(TAG,
13573 "Process cur broadcast " + r + " DELIVERED for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013574 started = true;
13575 } finally {
13576 if (!started) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013577 if (DEBUG_BROADCAST) Slog.v(TAG,
13578 "Process cur broadcast " + r + ": NOT STARTED!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013579 r.receiver = null;
13580 r.curApp = null;
13581 app.curReceiver = null;
13582 }
13583 }
13584
13585 }
13586
Jeff Brown4d94a762010-09-23 11:33:28 -070013587 static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013588 Intent intent, int resultCode, String data, Bundle extras,
13589 boolean ordered, boolean sticky) throws RemoteException {
Jeff Brown4d94a762010-09-23 11:33:28 -070013590 // Send the intent to the receiver asynchronously using one-way binder calls.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013591 if (app != null && app.thread != null) {
13592 // If we have an app thread, do the call through that so it is
13593 // correctly ordered with other one-way calls.
13594 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013595 data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013596 } else {
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013597 receiver.performReceive(intent, resultCode, data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013598 }
13599 }
13600
Jeff Brown4d94a762010-09-23 11:33:28 -070013601 private final void deliverToRegisteredReceiverLocked(BroadcastRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013602 BroadcastFilter filter, boolean ordered) {
13603 boolean skip = false;
13604 if (filter.requiredPermission != null) {
13605 int perm = checkComponentPermission(filter.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080013606 r.callingPid, r.callingUid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013607 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013608 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013609 + r.intent.toString()
13610 + " from " + r.callerPackage + " (pid="
13611 + r.callingPid + ", uid=" + r.callingUid + ")"
13612 + " requires " + filter.requiredPermission
13613 + " due to registered receiver " + filter);
13614 skip = true;
13615 }
13616 }
13617 if (r.requiredPermission != null) {
13618 int perm = checkComponentPermission(r.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080013619 filter.receiverList.pid, filter.receiverList.uid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013620 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013621 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013622 + r.intent.toString()
13623 + " to " + filter.receiverList.app
13624 + " (pid=" + filter.receiverList.pid
13625 + ", uid=" + filter.receiverList.uid + ")"
13626 + " requires " + r.requiredPermission
13627 + " due to sender " + r.callerPackage
13628 + " (uid " + r.callingUid + ")");
13629 skip = true;
13630 }
13631 }
13632
13633 if (!skip) {
13634 // If this is not being sent as an ordered broadcast, then we
13635 // don't want to touch the fields that keep track of the current
13636 // state of ordered broadcasts.
13637 if (ordered) {
13638 r.receiver = filter.receiverList.receiver.asBinder();
13639 r.curFilter = filter;
13640 filter.receiverList.curBroadcast = r;
13641 r.state = BroadcastRecord.CALL_IN_RECEIVE;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013642 if (filter.receiverList.app != null) {
13643 // Bump hosting application to no longer be in background
13644 // scheduling class. Note that we can't do that if there
13645 // isn't an app... but we can only be in that case for
13646 // things that directly call the IActivityManager API, which
13647 // are already core system stuff so don't matter for this.
13648 r.curApp = filter.receiverList.app;
13649 filter.receiverList.app.curReceiver = r;
13650 updateOomAdjLocked();
13651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013652 }
13653 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013654 if (DEBUG_BROADCAST_LIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013655 int seq = r.intent.getIntExtra("seq", -1);
Dianne Hackborn399cccb2010-04-13 22:57:49 -070013656 Slog.i(TAG, "Delivering to " + filter
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013657 + " (seq=" + seq + "): " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013658 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013659 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013660 new Intent(r.intent), r.resultCode,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013661 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013662 if (ordered) {
13663 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
13664 }
13665 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013666 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013667 if (ordered) {
13668 r.receiver = null;
13669 r.curFilter = null;
13670 filter.receiverList.curBroadcast = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013671 if (filter.receiverList.app != null) {
13672 filter.receiverList.app.curReceiver = null;
13673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013674 }
13675 }
13676 }
13677 }
13678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013679 // =========================================================
13680 // INSTRUMENTATION
13681 // =========================================================
13682
13683 public boolean startInstrumentation(ComponentName className,
13684 String profileFile, int flags, Bundle arguments,
13685 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013686 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013687 // Refuse possible leaked file descriptors
13688 if (arguments != null && arguments.hasFileDescriptors()) {
13689 throw new IllegalArgumentException("File descriptors passed in Bundle");
13690 }
13691
13692 synchronized(this) {
13693 InstrumentationInfo ii = null;
13694 ApplicationInfo ai = null;
13695 try {
13696 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013697 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013698 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013699 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013700 } catch (PackageManager.NameNotFoundException e) {
13701 }
13702 if (ii == null) {
13703 reportStartInstrumentationFailure(watcher, className,
13704 "Unable to find instrumentation info for: " + className);
13705 return false;
13706 }
13707 if (ai == null) {
13708 reportStartInstrumentationFailure(watcher, className,
13709 "Unable to find instrumentation target package: " + ii.targetPackage);
13710 return false;
13711 }
13712
13713 int match = mContext.getPackageManager().checkSignatures(
13714 ii.targetPackage, ii.packageName);
13715 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13716 String msg = "Permission Denial: starting instrumentation "
13717 + className + " from pid="
13718 + Binder.getCallingPid()
13719 + ", uid=" + Binder.getCallingPid()
13720 + " not allowed because package " + ii.packageName
13721 + " does not have a signature matching the target "
13722 + ii.targetPackage;
13723 reportStartInstrumentationFailure(watcher, className, msg);
13724 throw new SecurityException(msg);
13725 }
13726
13727 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013728 // Instrumentation can kill and relaunch even persistent processes
13729 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013730 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013731 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013732 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013733 app.instrumentationProfileFile = profileFile;
13734 app.instrumentationArguments = arguments;
13735 app.instrumentationWatcher = watcher;
13736 app.instrumentationResultClass = className;
13737 Binder.restoreCallingIdentity(origId);
13738 }
13739
13740 return true;
13741 }
13742
13743 /**
13744 * Report errors that occur while attempting to start Instrumentation. Always writes the
13745 * error to the logs, but if somebody is watching, send the report there too. This enables
13746 * the "am" command to report errors with more information.
13747 *
13748 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13749 * @param cn The component name of the instrumentation.
13750 * @param report The error report.
13751 */
13752 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13753 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013754 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013755 try {
13756 if (watcher != null) {
13757 Bundle results = new Bundle();
13758 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13759 results.putString("Error", report);
13760 watcher.instrumentationStatus(cn, -1, results);
13761 }
13762 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013763 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013764 }
13765 }
13766
13767 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13768 if (app.instrumentationWatcher != null) {
13769 try {
13770 // NOTE: IInstrumentationWatcher *must* be oneway here
13771 app.instrumentationWatcher.instrumentationFinished(
13772 app.instrumentationClass,
13773 resultCode,
13774 results);
13775 } catch (RemoteException e) {
13776 }
13777 }
13778 app.instrumentationWatcher = null;
13779 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013780 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013781 app.instrumentationProfileFile = null;
13782 app.instrumentationArguments = null;
13783
Christopher Tate3dacd842011-08-19 14:56:15 -070013784 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013785 }
13786
13787 public void finishInstrumentation(IApplicationThread target,
13788 int resultCode, Bundle results) {
13789 // Refuse possible leaked file descriptors
13790 if (results != null && results.hasFileDescriptors()) {
13791 throw new IllegalArgumentException("File descriptors passed in Intent");
13792 }
13793
13794 synchronized(this) {
13795 ProcessRecord app = getRecordForAppLocked(target);
13796 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013797 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013798 return;
13799 }
13800 final long origId = Binder.clearCallingIdentity();
13801 finishInstrumentationLocked(app, resultCode, results);
13802 Binder.restoreCallingIdentity(origId);
13803 }
13804 }
13805
13806 // =========================================================
13807 // CONFIGURATION
13808 // =========================================================
13809
13810 public ConfigurationInfo getDeviceConfigurationInfo() {
13811 ConfigurationInfo config = new ConfigurationInfo();
13812 synchronized (this) {
13813 config.reqTouchScreen = mConfiguration.touchscreen;
13814 config.reqKeyboardType = mConfiguration.keyboard;
13815 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013816 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13817 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013818 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13819 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013820 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13821 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013822 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13823 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013824 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013825 }
13826 return config;
13827 }
13828
13829 public Configuration getConfiguration() {
13830 Configuration ci;
13831 synchronized(this) {
13832 ci = new Configuration(mConfiguration);
13833 }
13834 return ci;
13835 }
13836
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013837 public void updatePersistentConfiguration(Configuration values) {
13838 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13839 "updateConfiguration()");
13840 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13841 "updateConfiguration()");
13842 if (values == null) {
13843 throw new NullPointerException("Configuration must not be null");
13844 }
13845
13846 synchronized(this) {
13847 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013848 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013849 Binder.restoreCallingIdentity(origId);
13850 }
13851 }
13852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013853 public void updateConfiguration(Configuration values) {
13854 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13855 "updateConfiguration()");
13856
13857 synchronized(this) {
13858 if (values == null && mWindowManager != null) {
13859 // sentinel: fetch the current configuration from the window manager
13860 values = mWindowManager.computeNewConfiguration();
13861 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013862
13863 if (mWindowManager != null) {
13864 mProcessList.applyDisplaySize(mWindowManager);
13865 }
13866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013867 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013868 if (values != null) {
13869 Settings.System.clearConfiguration(values);
13870 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013871 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013872 Binder.restoreCallingIdentity(origId);
13873 }
13874 }
13875
13876 /**
13877 * Do either or both things: (1) change the current configuration, and (2)
13878 * make sure the given activity is running with the (now) current
13879 * configuration. Returns true if the activity has been left running, or
13880 * false if <var>starting</var> is being destroyed to match the new
13881 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013882 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013883 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013884 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013885 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013886 // do nothing if we are headless
13887 if (mHeadless) return true;
13888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013889 int changes = 0;
13890
13891 boolean kept = true;
13892
13893 if (values != null) {
13894 Configuration newConfig = new Configuration(mConfiguration);
13895 changes = newConfig.updateFrom(values);
13896 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013897 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013898 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013899 }
13900
Doug Zongker2bec3d42009-12-04 12:52:44 -080013901 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013902
Dianne Hackborn813075a62011-11-14 17:45:19 -080013903 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013904 saveLocaleLocked(values.locale,
13905 !values.locale.equals(mConfiguration.locale),
13906 values.userSetLocale);
13907 }
13908
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013909 mConfigurationSeq++;
13910 if (mConfigurationSeq <= 0) {
13911 mConfigurationSeq = 1;
13912 }
13913 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013914 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013915 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013916
13917 final Configuration configCopy = new Configuration(mConfiguration);
13918
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013919 AttributeCache ac = AttributeCache.instance();
13920 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013921 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013923
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013924 // Make sure all resources in our process are updated
13925 // right now, so that anyone who is going to retrieve
13926 // resource values after we return will be sure to get
13927 // the new ones. This is especially important during
13928 // boot, where the first config change needs to guarantee
13929 // all resources have that config before following boot
13930 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013931 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013932
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013933 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013934 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013935 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013936 mHandler.sendMessage(msg);
13937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013938
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013939 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13940 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013941 try {
13942 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013943 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013944 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013945 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013946 }
13947 } catch (Exception e) {
13948 }
13949 }
13950 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013951 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13952 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013953 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013954 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013955 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13956 broadcastIntentLocked(null, null,
13957 new Intent(Intent.ACTION_LOCALE_CHANGED),
13958 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013959 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013961 }
13962 }
13963
13964 if (changes != 0 && starting == null) {
13965 // If the configuration changed, and the caller is not already
13966 // in the process of starting an activity, then find the top
13967 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013968 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013969 }
13970
13971 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013972 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013973 // And we need to make sure at this point that all other activities
13974 // are made visible with the correct configuration.
13975 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013976 }
13977
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013978 if (values != null && mWindowManager != null) {
13979 mWindowManager.setNewConfiguration(mConfiguration);
13980 }
13981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013982 return kept;
13983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013984
13985 /**
13986 * Save the locale. You must be inside a synchronized (this) block.
13987 */
13988 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13989 if(isDiff) {
13990 SystemProperties.set("user.language", l.getLanguage());
13991 SystemProperties.set("user.region", l.getCountry());
13992 }
13993
13994 if(isPersist) {
13995 SystemProperties.set("persist.sys.language", l.getLanguage());
13996 SystemProperties.set("persist.sys.country", l.getCountry());
13997 SystemProperties.set("persist.sys.localevar", l.getVariant());
13998 }
13999 }
14000
14001 // =========================================================
14002 // LIFETIME MANAGEMENT
14003 // =========================================================
14004
Christopher Tatef46723b2012-01-26 14:19:24 -080014005 // Returns which broadcast queue the app is the current [or imminent] receiver
14006 // on, or 'null' if the app is not an active broadcast recipient.
14007 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
14008 BroadcastRecord r = app.curReceiver;
14009 if (r != null) {
14010 return r.queue;
14011 }
14012
14013 // It's not the current receiver, but it might be starting up to become one
14014 synchronized (this) {
14015 for (BroadcastQueue queue : mBroadcastQueues) {
14016 r = queue.mPendingBroadcast;
14017 if (r != null && r.curApp == app) {
14018 // found it; report which queue it's in
14019 return queue;
14020 }
14021 }
14022 }
14023
14024 return null;
14025 }
14026
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014027 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014028 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014029 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014030 // This adjustment has already been computed. If we are calling
14031 // from the top, we may have already computed our adjustment with
14032 // an earlier hidden adjustment that isn't really for us... if
14033 // so, use the new hidden adjustment.
14034 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014035 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014036 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014037 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014038 }
14039
14040 if (app.thread == null) {
14041 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014042 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014043 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014044 }
14045
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014046 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
14047 app.adjSource = null;
14048 app.adjTarget = null;
14049 app.empty = false;
14050 app.hidden = false;
14051
14052 final int activitiesSize = app.activities.size();
14053
Dianne Hackborn7d608422011-08-07 16:24:18 -070014054 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014055 // The max adjustment doesn't allow this app to be anything
14056 // below foreground, so it is not worth doing work for it.
14057 app.adjType = "fixed";
14058 app.adjSeq = mAdjSeq;
14059 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014060 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014061 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014062 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014063 // System process can do UI, and when they do we want to have
14064 // them trim their memory after the user leaves the UI. To
14065 // facilitate this, here we need to determine whether or not it
14066 // is currently showing UI.
14067 app.systemNoUi = true;
14068 if (app == TOP_APP) {
14069 app.systemNoUi = false;
14070 } else if (activitiesSize > 0) {
14071 for (int j = 0; j < activitiesSize; j++) {
14072 final ActivityRecord r = app.activities.get(j);
14073 if (r.visible) {
14074 app.systemNoUi = false;
14075 break;
14076 }
14077 }
14078 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014079 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014080 }
14081
14082 final boolean hadForegroundActivities = app.foregroundActivities;
14083
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014084 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014085 app.keeping = false;
14086 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014087
The Android Open Source Project4df24232009-03-05 14:34:35 -080014088 // Determine the importance of the process, starting with most
14089 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014090 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014091 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080014092 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014093 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014094 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014095 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014096 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014097 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014098 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014099 } else if (app.instrumentationClass != null) {
14100 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014101 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014102 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014103 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080014104 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014105 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080014106 // counts as being in the foreground for OOM killer purposes.
14107 // It's placed in a sched group based on the nature of the
14108 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014109 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080014110 schedGroup = (queue == mFgBroadcastQueue)
14111 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014112 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014113 } else if (app.executingServices.size() > 0) {
14114 // An app that is currently executing a service callback also
14115 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014116 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014117 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014118 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014119 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014120 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014121 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014122 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014123 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014124 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014125 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014126 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014127 // A very not-needed process. If this is lower in the lru list,
14128 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014129 adj = hiddenAdj;
14130 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014131 app.hidden = true;
14132 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014133 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014134 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014135
14136 // Examine all activities if not already foreground.
14137 if (!app.foregroundActivities && activitiesSize > 0) {
14138 for (int j = 0; j < activitiesSize; j++) {
14139 final ActivityRecord r = app.activities.get(j);
14140 if (r.visible) {
14141 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014142 if (adj > ProcessList.VISIBLE_APP_ADJ) {
14143 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014144 app.adjType = "visible";
14145 }
14146 schedGroup = Process.THREAD_GROUP_DEFAULT;
14147 app.hidden = false;
14148 app.foregroundActivities = true;
14149 break;
14150 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
14151 || r.state == ActivityState.STOPPING) {
14152 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014153 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14154 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014155 app.adjType = "stopping";
14156 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080014157 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014158 app.foregroundActivities = true;
14159 }
14160 }
14161 }
14162
Dianne Hackborn7d608422011-08-07 16:24:18 -070014163 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014164 if (app.foregroundServices) {
14165 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014166 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014167 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014168 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014169 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014170 } else if (app.forcingToForeground != null) {
14171 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014172 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014173 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014174 app.adjType = "force-foreground";
14175 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014176 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014177 }
14178 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014179
Dianne Hackborn7d608422011-08-07 16:24:18 -070014180 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014181 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014182 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014183 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014184 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014185 app.adjType = "heavy";
14186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014187
Dianne Hackborn7d608422011-08-07 16:24:18 -070014188 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014189 // This process is hosting what we currently consider to be the
14190 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014191 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014192 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014193 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014194 app.adjType = "home";
14195 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014196
Dianne Hackbornf35fe232011-11-01 19:25:20 -070014197 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
14198 && app.activities.size() > 0) {
14199 // This was the previous process that showed UI to the user.
14200 // We want to try to keep it around more aggressively, to give
14201 // a good experience around switching between two apps.
14202 adj = ProcessList.PREVIOUS_APP_ADJ;
14203 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
14204 app.hidden = false;
14205 app.adjType = "previous";
14206 }
14207
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014208 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
14209 + " reason=" + app.adjType);
14210
The Android Open Source Project4df24232009-03-05 14:34:35 -080014211 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014212 // there are applications dependent on our services or providers, but
14213 // this gives us a baseline and makes sure we don't get into an
14214 // infinite recursion.
14215 app.adjSeq = mAdjSeq;
14216 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014217
Christopher Tate6fa95972009-06-05 18:43:55 -070014218 if (mBackupTarget != null && app == mBackupTarget.app) {
14219 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070014220 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014221 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014222 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014223 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014224 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070014225 }
14226 }
14227
Dianne Hackborn7d608422011-08-07 16:24:18 -070014228 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014229 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014230 final long now = SystemClock.uptimeMillis();
14231 // This process is more important if the top activity is
14232 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070014233 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014234 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014235 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014236 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014237 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014238 // If this process has shown some UI, let it immediately
14239 // go to the LRU list because it may be pretty heavy with
14240 // UI stuff. We'll tag it with a label just to help
14241 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014242 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014243 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014244 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014245 } else {
14246 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
14247 // This service has seen some activity within
14248 // recent memory, so we will keep its process ahead
14249 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014250 if (adj > ProcessList.SERVICE_ADJ) {
14251 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014252 app.adjType = "started-services";
14253 app.hidden = false;
14254 }
14255 }
14256 // If we have let the service slide into the background
14257 // state, still have some text describing what it is doing
14258 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014259 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014260 app.adjType = "started-bg-services";
14261 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014262 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014263 // Don't kill this process because it is doing work; it
14264 // has said it is doing work.
14265 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014266 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014267 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014268 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014269 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014270 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014271 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014272 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014273 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014274 // XXX should compute this based on the max of
14275 // all connected clients.
14276 ConnectionRecord cr = clist.get(i);
14277 if (cr.binding.client == app) {
14278 // Binding to ourself is not interesting.
14279 continue;
14280 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014281 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014282 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014283 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014284 int myHiddenAdj = hiddenAdj;
14285 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014286 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014287 myHiddenAdj = client.hiddenAdj;
14288 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014289 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014290 }
14291 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014292 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014293 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014294 String adjType = null;
14295 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
14296 // Not doing bind OOM management, so treat
14297 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014298 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014299 // If this process has shown some UI, let it immediately
14300 // go to the LRU list because it may be pretty heavy with
14301 // UI stuff. We'll tag it with a label just to help
14302 // debug and understand what is going on.
14303 if (adj > clientAdj) {
14304 adjType = "bound-bg-ui-services";
14305 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014306 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014307 clientAdj = adj;
14308 } else {
14309 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
14310 // This service has not seen activity within
14311 // recent memory, so allow it to drop to the
14312 // LRU list if there is no other reason to keep
14313 // it around. We'll also tag it with a label just
14314 // to help debug and undertand what is going on.
14315 if (adj > clientAdj) {
14316 adjType = "bound-bg-services";
14317 }
14318 clientAdj = adj;
14319 }
14320 }
14321 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014322 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014323 // If this process has recently shown UI, and
14324 // the process that is binding to it is less
14325 // important than being visible, then we don't
14326 // care about the binding as much as we care
14327 // about letting this process get into the LRU
14328 // list to be killed and restarted if needed for
14329 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014330 if (app.hasShownUi && app != mHomeProcess
14331 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014332 adjType = "bound-bg-ui-services";
14333 } else {
14334 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
14335 |Context.BIND_IMPORTANT)) != 0) {
14336 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014337 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
14338 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
14339 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14340 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14341 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014342 adj = clientAdj;
14343 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014344 app.pendingUiClean = true;
14345 if (adj > ProcessList.VISIBLE_APP_ADJ) {
14346 adj = ProcessList.VISIBLE_APP_ADJ;
14347 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014348 }
14349 if (!client.hidden) {
14350 app.hidden = false;
14351 }
14352 if (client.keeping) {
14353 app.keeping = true;
14354 }
14355 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014356 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014357 }
14358 if (adjType != null) {
14359 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014360 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14361 .REASON_SERVICE_IN_USE;
14362 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014363 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014364 app.adjTarget = s.name;
14365 }
14366 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14367 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14368 schedGroup = Process.THREAD_GROUP_DEFAULT;
14369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014370 }
14371 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014372 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
14373 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014374 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014375 (a.visible || a.state == ActivityState.RESUMED
14376 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014377 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014378 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14379 schedGroup = Process.THREAD_GROUP_DEFAULT;
14380 }
14381 app.hidden = false;
14382 app.adjType = "service";
14383 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14384 .REASON_SERVICE_IN_USE;
14385 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014386 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014387 app.adjTarget = s.name;
14388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014390 }
14391 }
14392 }
14393 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014394
Dianne Hackborn287952c2010-09-22 22:34:31 -070014395 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014396 // would like to avoid killing it unless it would prevent the current
14397 // application from running. By default we put the process in
14398 // with the rest of the background processes; as we scan through
14399 // its services we may bump it up from there.
14400 if (adj > hiddenAdj) {
14401 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014402 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014403 app.adjType = "bg-services";
14404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014405 }
14406
Dianne Hackborn7d608422011-08-07 16:24:18 -070014407 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014408 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014409 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014410 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014411 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014412 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014413 if (cpr.clients.size() != 0) {
14414 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014415 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014416 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070014417 if (client == app) {
14418 // Being our own client is not interesting.
14419 continue;
14420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014421 int myHiddenAdj = hiddenAdj;
14422 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014423 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014424 myHiddenAdj = client.hiddenAdj;
14425 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014426 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014427 }
14428 }
14429 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014430 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014431 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014432 if (app.hasShownUi && app != mHomeProcess
14433 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014434 app.adjType = "bg-ui-provider";
14435 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014436 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
14437 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014438 app.adjType = "provider";
14439 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014440 if (!client.hidden) {
14441 app.hidden = false;
14442 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014443 if (client.keeping) {
14444 app.keeping = true;
14445 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070014446 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14447 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014448 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014449 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014450 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014451 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014452 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14453 schedGroup = Process.THREAD_GROUP_DEFAULT;
14454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014455 }
14456 }
14457 // If the provider has external (non-framework) process
14458 // dependencies, ensure that its adjustment is at least
14459 // FOREGROUND_APP_ADJ.
14460 if (cpr.externals != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014461 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
14462 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014463 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014464 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014465 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014466 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014467 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014468 }
14469 }
14470 }
14471 }
14472
14473 app.curRawAdj = adj;
14474
Joe Onorato8a9b2202010-02-26 18:56:32 -080014475 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014476 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14477 if (adj > app.maxAdj) {
14478 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014479 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014480 schedGroup = Process.THREAD_GROUP_DEFAULT;
14481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014482 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014483 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014484 app.keeping = true;
14485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014486
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014487 if (app.hasAboveClient) {
14488 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14489 // then we need to drop its adjustment to be lower than the service's
14490 // in order to honor the request. We want to drop it by one adjustment
14491 // level... but there is special meaning applied to various levels so
14492 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014493 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014494 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014495 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14496 adj = ProcessList.VISIBLE_APP_ADJ;
14497 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14498 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14499 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14500 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014501 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014502 adj++;
14503 }
14504 }
14505
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014506 if (adj == ProcessList.SERVICE_ADJ) {
14507 if (doingAll) {
14508 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
14509 mNewNumServiceProcs++;
14510 }
14511 if (app.serviceb) {
14512 adj = ProcessList.SERVICE_B_ADJ;
14513 }
14514 } else {
14515 app.serviceb = false;
14516 }
14517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014518 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014519 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014520
14521 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014522 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14523 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014524 }
14525
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014526 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014527 }
14528
14529 /**
14530 * Ask a given process to GC right now.
14531 */
14532 final void performAppGcLocked(ProcessRecord app) {
14533 try {
14534 app.lastRequestedGc = SystemClock.uptimeMillis();
14535 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014536 if (app.reportLowMemory) {
14537 app.reportLowMemory = false;
14538 app.thread.scheduleLowMemory();
14539 } else {
14540 app.thread.processInBackground();
14541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014542 }
14543 } catch (Exception e) {
14544 // whatever.
14545 }
14546 }
14547
14548 /**
14549 * Returns true if things are idle enough to perform GCs.
14550 */
Josh Bartel7f208742010-02-25 11:01:44 -060014551 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014552 boolean processingBroadcasts = false;
14553 for (BroadcastQueue q : mBroadcastQueues) {
14554 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14555 processingBroadcasts = true;
14556 }
14557 }
14558 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014559 && (mSleeping || (mMainStack.mResumedActivity != null &&
14560 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014561 }
14562
14563 /**
14564 * Perform GCs on all processes that are waiting for it, but only
14565 * if things are idle.
14566 */
14567 final void performAppGcsLocked() {
14568 final int N = mProcessesToGc.size();
14569 if (N <= 0) {
14570 return;
14571 }
Josh Bartel7f208742010-02-25 11:01:44 -060014572 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014573 while (mProcessesToGc.size() > 0) {
14574 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014575 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014576 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14577 <= SystemClock.uptimeMillis()) {
14578 // To avoid spamming the system, we will GC processes one
14579 // at a time, waiting a few seconds between each.
14580 performAppGcLocked(proc);
14581 scheduleAppGcsLocked();
14582 return;
14583 } else {
14584 // It hasn't been long enough since we last GCed this
14585 // process... put it in the list to wait for its time.
14586 addProcessToGcListLocked(proc);
14587 break;
14588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014589 }
14590 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014591
14592 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014593 }
14594 }
14595
14596 /**
14597 * If all looks good, perform GCs on all processes waiting for them.
14598 */
14599 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014600 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014601 performAppGcsLocked();
14602 return;
14603 }
14604 // Still not idle, wait some more.
14605 scheduleAppGcsLocked();
14606 }
14607
14608 /**
14609 * Schedule the execution of all pending app GCs.
14610 */
14611 final void scheduleAppGcsLocked() {
14612 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014613
14614 if (mProcessesToGc.size() > 0) {
14615 // Schedule a GC for the time to the next process.
14616 ProcessRecord proc = mProcessesToGc.get(0);
14617 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14618
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014619 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014620 long now = SystemClock.uptimeMillis();
14621 if (when < (now+GC_TIMEOUT)) {
14622 when = now + GC_TIMEOUT;
14623 }
14624 mHandler.sendMessageAtTime(msg, when);
14625 }
14626 }
14627
14628 /**
14629 * Add a process to the array of processes waiting to be GCed. Keeps the
14630 * list in sorted order by the last GC time. The process can't already be
14631 * on the list.
14632 */
14633 final void addProcessToGcListLocked(ProcessRecord proc) {
14634 boolean added = false;
14635 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14636 if (mProcessesToGc.get(i).lastRequestedGc <
14637 proc.lastRequestedGc) {
14638 added = true;
14639 mProcessesToGc.add(i+1, proc);
14640 break;
14641 }
14642 }
14643 if (!added) {
14644 mProcessesToGc.add(0, proc);
14645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014646 }
14647
14648 /**
14649 * Set up to ask a process to GC itself. This will either do it
14650 * immediately, or put it on the list of processes to gc the next
14651 * time things are idle.
14652 */
14653 final void scheduleAppGcLocked(ProcessRecord app) {
14654 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014655 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014656 return;
14657 }
14658 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014659 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014660 scheduleAppGcsLocked();
14661 }
14662 }
14663
Dianne Hackborn287952c2010-09-22 22:34:31 -070014664 final void checkExcessivePowerUsageLocked(boolean doKills) {
14665 updateCpuStatsNow();
14666
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014667 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014668 boolean doWakeKills = doKills;
14669 boolean doCpuKills = doKills;
14670 if (mLastPowerCheckRealtime == 0) {
14671 doWakeKills = false;
14672 }
14673 if (mLastPowerCheckUptime == 0) {
14674 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014675 }
14676 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014677 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014678 }
14679 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014680 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14681 final long curUptime = SystemClock.uptimeMillis();
14682 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14683 mLastPowerCheckRealtime = curRealtime;
14684 mLastPowerCheckUptime = curUptime;
14685 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14686 doWakeKills = false;
14687 }
14688 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14689 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014690 }
14691 int i = mLruProcesses.size();
14692 while (i > 0) {
14693 i--;
14694 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014695 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014696 long wtime;
14697 synchronized (stats) {
14698 wtime = stats.getProcessWakeTime(app.info.uid,
14699 app.pid, curRealtime);
14700 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014701 long wtimeUsed = wtime - app.lastWakeTime;
14702 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14703 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014704 StringBuilder sb = new StringBuilder(128);
14705 sb.append("Wake for ");
14706 app.toShortString(sb);
14707 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014708 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014709 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014710 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014711 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014712 sb.append((wtimeUsed*100)/realtimeSince);
14713 sb.append("%)");
14714 Slog.i(TAG, sb.toString());
14715 sb.setLength(0);
14716 sb.append("CPU for ");
14717 app.toShortString(sb);
14718 sb.append(": over ");
14719 TimeUtils.formatDuration(uptimeSince, sb);
14720 sb.append(" used ");
14721 TimeUtils.formatDuration(cputimeUsed, sb);
14722 sb.append(" (");
14723 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014724 sb.append("%)");
14725 Slog.i(TAG, sb.toString());
14726 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014727 // If a process has held a wake lock for more
14728 // than 50% of the time during this period,
14729 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014730 if (doWakeKills && realtimeSince > 0
14731 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14732 synchronized (stats) {
14733 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14734 realtimeSince, wtimeUsed);
14735 }
14736 Slog.w(TAG, "Excessive wake lock in " + app.processName
14737 + " (pid " + app.pid + "): held " + wtimeUsed
14738 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014739 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14740 app.processName, app.setAdj, "excessive wake lock");
14741 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014742 } else if (doCpuKills && uptimeSince > 0
14743 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14744 synchronized (stats) {
14745 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14746 uptimeSince, cputimeUsed);
14747 }
14748 Slog.w(TAG, "Excessive CPU in " + app.processName
14749 + " (pid " + app.pid + "): used " + cputimeUsed
14750 + " during " + uptimeSince);
14751 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14752 app.processName, app.setAdj, "excessive cpu");
14753 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014754 } else {
14755 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014756 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014757 }
14758 }
14759 }
14760 }
14761
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014762 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014763 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014764 app.hiddenAdj = hiddenAdj;
14765
14766 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014767 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014768 }
14769
Dianne Hackborn287952c2010-09-22 22:34:31 -070014770 final boolean wasKeeping = app.keeping;
14771
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014772 boolean success = true;
14773
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014774 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014775
Jeff Brown10e89712011-07-08 18:52:57 -070014776 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070014777 if (false) {
14778 // Removing for now. Forcing GCs is not so useful anymore
14779 // with Dalvik, and the new memory level hint facility is
14780 // better for what we need to do these days.
14781 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14782 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14783 // If this app is transitioning from foreground to
14784 // non-foreground, have it do a gc.
14785 scheduleAppGcLocked(app);
14786 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14787 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14788 // Likewise do a gc when an app is moving in to the
14789 // background (such as a service stopping).
14790 scheduleAppGcLocked(app);
14791 }
Jeff Brown10e89712011-07-08 18:52:57 -070014792 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014793
Jeff Brown10e89712011-07-08 18:52:57 -070014794 if (wasKeeping && !app.keeping) {
14795 // This app is no longer something we want to keep. Note
14796 // its current wake lock time to later know to kill it if
14797 // it is not behaving well.
14798 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14799 synchronized (stats) {
14800 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14801 app.pid, SystemClock.elapsedRealtime());
14802 }
14803 app.lastCpuTime = app.curCpuTime;
14804 }
14805
14806 app.setRawAdj = app.curRawAdj;
14807 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014808
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014809 if (app.curAdj != app.setAdj) {
14810 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014811 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014812 TAG, "Set " + app.pid + " " + app.processName +
14813 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014814 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014815 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014816 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014817 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014818 }
14819 }
14820 if (app.setSchedGroup != app.curSchedGroup) {
14821 app.setSchedGroup = app.curSchedGroup;
14822 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14823 "Setting process group of " + app.processName
14824 + " to " + app.curSchedGroup);
14825 if (app.waitingToKill != null &&
14826 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14827 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14828 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14829 app.processName, app.setAdj, app.waitingToKill);
14830 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014831 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014832 } else {
14833 if (true) {
14834 long oldId = Binder.clearCallingIdentity();
14835 try {
14836 Process.setProcessGroup(app.pid, app.curSchedGroup);
14837 } catch (Exception e) {
14838 Slog.w(TAG, "Failed setting process group of " + app.pid
14839 + " to " + app.curSchedGroup);
14840 e.printStackTrace();
14841 } finally {
14842 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014843 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014844 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014845 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014846 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014847 app.thread.setSchedulingGroup(app.curSchedGroup);
14848 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014849 }
14850 }
14851 }
14852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014853 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014854 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014855 }
14856
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014857 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014858 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014859 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborncbb722e2012-02-07 18:33:49 -080014860 for (int i=mMainStack.mPausingActivities.size()-1; i>=0; i--) {
14861 ActivityRecord r = mMainStack.mPausingActivities.get(i);
14862 if (r.app != null) {
14863 resumedActivity = r;
14864 break;
14865 }
14866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014867 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014868 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014869 }
14870 }
14871 return resumedActivity;
14872 }
14873
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014874 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014875 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014876 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14877 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014878 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14879 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014880
14881 mAdjSeq++;
14882
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014883 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014884 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14885 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014886 if (nowHidden != wasHidden) {
14887 // Changed to/from hidden state, so apps after it in the LRU
14888 // list may also be changed.
14889 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014890 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014891 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014892 }
14893
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014894 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014895 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014896 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14897
14898 if (false) {
14899 RuntimeException e = new RuntimeException();
14900 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014901 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014902 }
14903
14904 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014905 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014906
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014907 // Let's determine how many processes we have running vs.
14908 // how many slots we have for background processes; we may want
14909 // to put multiple processes in a slot of there are enough of
14910 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014911 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014912 int factor = (mLruProcesses.size()-4)/numSlots;
14913 if (factor < 1) factor = 1;
14914 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014915 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014916
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014917 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014918 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014919 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014920 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014921 while (i > 0) {
14922 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014923 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014924 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014925 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14926 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014927 && app.curAdj == curHiddenAdj) {
14928 step++;
14929 if (step >= factor) {
14930 step = 0;
14931 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014932 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014933 }
14934 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014935 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014936 numHidden++;
14937 if (numHidden > mProcessLimit) {
14938 Slog.i(TAG, "No longer want " + app.processName
14939 + " (pid " + app.pid + "): hidden #" + numHidden);
14940 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14941 app.processName, app.setAdj, "too many background");
14942 app.killedBackground = true;
14943 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014944 }
14945 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014946 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14947 // If this is an isolated process, and there are no
14948 // services running in it, then the process is no longer
14949 // needed. We agressively kill these because we can by
14950 // definition not re-use the same process again, and it is
14951 // good to avoid having whatever code was running in them
14952 // left sitting around after no longer needed.
14953 Slog.i(TAG, "Isolated process " + app.processName
14954 + " (pid " + app.pid + ") no longer needed");
14955 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14956 app.processName, app.setAdj, "isolated not needed");
14957 app.killedBackground = true;
14958 Process.killProcessQuiet(app.pid);
14959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014960 }
14961 }
14962
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014963 mNumServiceProcs = mNewNumServiceProcs;
14964
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014965 // Now determine the memory trimming level of background processes.
14966 // Unfortunately we need to start at the back of the list to do this
14967 // properly. We only do this if the number of background apps we
14968 // are managing to keep around is less than half the maximum we desire;
14969 // if we are keeping a good number around, we'll let them use whatever
14970 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014971 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014972 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014973 factor = numHidden/3;
14974 int minFactor = 2;
14975 if (mHomeProcess != null) minFactor++;
14976 if (mPreviousProcess != null) minFactor++;
14977 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014978 step = 0;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014979 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014980 for (i=0; i<N; i++) {
14981 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014982 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14983 && app.curAdj != ProcessList.SERVICE_B_ADJ
14984 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014985 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14986 try {
14987 app.thread.scheduleTrimMemory(curLevel);
14988 } catch (RemoteException e) {
14989 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014990 if (false) {
14991 // For now we won't do this; our memory trimming seems
14992 // to be good enough at this point that destroying
14993 // activities causes more harm than good.
14994 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14995 && app != mHomeProcess && app != mPreviousProcess) {
14996 // For these apps we will also finish their activities
14997 // to help them free memory.
14998 mMainStack.destroyActivitiesLocked(app, false, "trim");
14999 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015000 }
15001 }
15002 app.trimMemoryLevel = curLevel;
15003 step++;
15004 if (step >= factor) {
15005 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015006 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
15007 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015008 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015009 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
15010 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015011 break;
15012 }
15013 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070015014 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015015 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015016 && app.thread != null) {
15017 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015018 app.thread.scheduleTrimMemory(
15019 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015020 } catch (RemoteException e) {
15021 }
15022 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015023 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn7d608422011-08-07 16:24:18 -070015024 } else if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015025 && app.pendingUiClean) {
15026 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
15027 && app.thread != null) {
15028 try {
15029 app.thread.scheduleTrimMemory(
15030 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
15031 } catch (RemoteException e) {
15032 }
15033 }
15034 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
15035 app.pendingUiClean = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015036 } else {
15037 app.trimMemoryLevel = 0;
15038 }
15039 }
15040 } else {
15041 final int N = mLruProcesses.size();
15042 for (i=0; i<N; i++) {
15043 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070015044 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015045 && app.pendingUiClean) {
15046 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
15047 && app.thread != null) {
15048 try {
15049 app.thread.scheduleTrimMemory(
15050 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
15051 } catch (RemoteException e) {
15052 }
15053 }
15054 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
15055 app.pendingUiClean = false;
15056 } else {
15057 app.trimMemoryLevel = 0;
15058 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015059 }
15060 }
15061
15062 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070015063 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015065 }
15066
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070015067 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015068 synchronized (this) {
15069 int i;
15070
15071 // First remove any unused application processes whose package
15072 // has been removed.
15073 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
15074 final ProcessRecord app = mRemovedProcesses.get(i);
15075 if (app.activities.size() == 0
15076 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080015077 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015078 TAG, "Exiting empty application process "
15079 + app.processName + " ("
15080 + (app.thread != null ? app.thread.asBinder() : null)
15081 + ")\n");
15082 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070015083 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
15084 app.processName, app.setAdj, "empty");
15085 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015086 } else {
15087 try {
15088 app.thread.scheduleExit();
15089 } catch (Exception e) {
15090 // Ignore exceptions.
15091 }
15092 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070015093 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015094 mRemovedProcesses.remove(i);
15095
15096 if (app.persistent) {
15097 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080015098 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015099 }
15100 }
15101 }
15102 }
15103
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015104 // Now update the oom adj for all processes.
15105 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015106 }
15107 }
15108
15109 /** This method sends the specified signal to each of the persistent apps */
15110 public void signalPersistentProcesses(int sig) throws RemoteException {
15111 if (sig != Process.SIGNAL_USR1) {
15112 throw new SecurityException("Only SIGNAL_USR1 is allowed");
15113 }
15114
15115 synchronized (this) {
15116 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
15117 != PackageManager.PERMISSION_GRANTED) {
15118 throw new SecurityException("Requires permission "
15119 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
15120 }
15121
Dianne Hackborndd71fc82009-12-16 19:24:32 -080015122 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
15123 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015124 if (r.thread != null && r.persistent) {
15125 Process.sendSignal(r.pid, sig);
15126 }
15127 }
15128 }
15129 }
15130
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015131 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
15132 if (proc == null || proc == mProfileProc) {
15133 proc = mProfileProc;
15134 path = mProfileFile;
15135 profileType = mProfileType;
15136 clearProfilerLocked();
15137 }
15138 if (proc == null) {
15139 return;
15140 }
15141 try {
15142 proc.thread.profilerControl(false, path, null, profileType);
15143 } catch (RemoteException e) {
15144 throw new IllegalStateException("Process disappeared");
15145 }
15146 }
15147
15148 private void clearProfilerLocked() {
15149 if (mProfileFd != null) {
15150 try {
15151 mProfileFd.close();
15152 } catch (IOException e) {
15153 }
15154 }
15155 mProfileApp = null;
15156 mProfileProc = null;
15157 mProfileFile = null;
15158 mProfileType = 0;
15159 mAutoStopProfiler = false;
15160 }
15161
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015162 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070015163 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015164
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015165 try {
15166 synchronized (this) {
15167 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
15168 // its own permission.
15169 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15170 != PackageManager.PERMISSION_GRANTED) {
15171 throw new SecurityException("Requires permission "
15172 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015173 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015174
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015175 if (start && fd == null) {
15176 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015177 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015178
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015179 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015180 if (process != null) {
15181 try {
15182 int pid = Integer.parseInt(process);
15183 synchronized (mPidsSelfLocked) {
15184 proc = mPidsSelfLocked.get(pid);
15185 }
15186 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015187 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015188
15189 if (proc == null) {
15190 HashMap<String, SparseArray<ProcessRecord>> all
15191 = mProcessNames.getMap();
15192 SparseArray<ProcessRecord> procs = all.get(process);
15193 if (procs != null && procs.size() > 0) {
15194 proc = procs.valueAt(0);
15195 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015196 }
15197 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015198
15199 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015200 throw new IllegalArgumentException("Unknown process: " + process);
15201 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015202
15203 if (start) {
15204 stopProfilerLocked(null, null, 0);
15205 setProfileApp(proc.info, proc.processName, path, fd, false);
15206 mProfileProc = proc;
15207 mProfileType = profileType;
15208 try {
15209 fd = fd.dup();
15210 } catch (IOException e) {
15211 fd = null;
15212 }
15213 proc.thread.profilerControl(start, path, fd, profileType);
15214 fd = null;
15215 mProfileFd = null;
15216 } else {
15217 stopProfilerLocked(proc, path, profileType);
15218 if (fd != null) {
15219 try {
15220 fd.close();
15221 } catch (IOException e) {
15222 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015223 }
15224 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015225
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015226 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015227 }
15228 } catch (RemoteException e) {
15229 throw new IllegalStateException("Process disappeared");
15230 } finally {
15231 if (fd != null) {
15232 try {
15233 fd.close();
15234 } catch (IOException e) {
15235 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015236 }
15237 }
15238 }
Andy McFadden824c5102010-07-09 16:26:57 -070015239
15240 public boolean dumpHeap(String process, boolean managed,
15241 String path, ParcelFileDescriptor fd) throws RemoteException {
15242
15243 try {
15244 synchronized (this) {
15245 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
15246 // its own permission (same as profileControl).
15247 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15248 != PackageManager.PERMISSION_GRANTED) {
15249 throw new SecurityException("Requires permission "
15250 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
15251 }
15252
15253 if (fd == null) {
15254 throw new IllegalArgumentException("null fd");
15255 }
15256
15257 ProcessRecord proc = null;
15258 try {
15259 int pid = Integer.parseInt(process);
15260 synchronized (mPidsSelfLocked) {
15261 proc = mPidsSelfLocked.get(pid);
15262 }
15263 } catch (NumberFormatException e) {
15264 }
15265
15266 if (proc == null) {
15267 HashMap<String, SparseArray<ProcessRecord>> all
15268 = mProcessNames.getMap();
15269 SparseArray<ProcessRecord> procs = all.get(process);
15270 if (procs != null && procs.size() > 0) {
15271 proc = procs.valueAt(0);
15272 }
15273 }
15274
15275 if (proc == null || proc.thread == null) {
15276 throw new IllegalArgumentException("Unknown process: " + process);
15277 }
15278
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080015279 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
15280 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070015281 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
15282 throw new SecurityException("Process not debuggable: " + proc);
15283 }
15284 }
15285
15286 proc.thread.dumpHeap(managed, path, fd);
15287 fd = null;
15288 return true;
15289 }
15290 } catch (RemoteException e) {
15291 throw new IllegalStateException("Process disappeared");
15292 } finally {
15293 if (fd != null) {
15294 try {
15295 fd.close();
15296 } catch (IOException e) {
15297 }
15298 }
15299 }
15300 }
15301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015302 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
15303 public void monitor() {
15304 synchronized (this) { }
15305 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015306
Dianne Hackborna573f6a2012-02-09 16:12:18 -080015307 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015308 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
15309 ProcessRecord processRecord = mLruProcesses.get(i);
15310 try {
15311 if (processRecord.thread != null) {
15312 processRecord.thread.setCoreSettings(settings);
15313 }
15314 } catch (RemoteException re) {
15315 /* ignore */
15316 }
15317 }
15318 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015319
15320 // Multi-user methods
15321
Amith Yamasani742a6712011-05-04 14:49:28 -070015322 private int mCurrentUserId;
15323 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
15324
15325 public boolean switchUser(int userId) {
15326 final int callingUid = Binder.getCallingUid();
15327 if (callingUid != 0 && callingUid != Process.myUid()) {
15328 Slog.e(TAG, "Trying to switch user from unauthorized app");
15329 return false;
15330 }
15331 if (mCurrentUserId == userId)
15332 return true;
15333
15334 synchronized (this) {
15335 // Check if user is already logged in, otherwise check if user exists first before
15336 // adding to the list of logged in users.
15337 if (mLoggedInUsers.indexOfKey(userId) < 0) {
15338 if (!userExists(userId)) {
15339 return false;
15340 }
15341 mLoggedInUsers.append(userId, userId);
15342 }
15343
15344 mCurrentUserId = userId;
15345 boolean haveActivities = mMainStack.switchUser(userId);
15346 if (!haveActivities) {
15347 startHomeActivityLocked(userId);
15348 }
15349 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015350 return true;
15351 }
Amith Yamasani742a6712011-05-04 14:49:28 -070015352
15353 private boolean userExists(int userId) {
15354 try {
15355 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
15356 for (UserInfo user : users) {
15357 if (user.id == userId) {
15358 return true;
15359 }
15360 }
15361 } catch (RemoteException re) {
15362 // Won't happen, in same process
15363 }
15364
15365 return false;
15366 }
15367
15368
15369 private int applyUserId(int uid, int userId) {
15370 return UserId.getUid(userId, uid);
15371 }
15372
15373 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080015374 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070015375 ApplicationInfo newInfo = new ApplicationInfo(info);
15376 newInfo.uid = applyUserId(info.uid, userId);
15377 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
15378 newInfo.dataDir = USER_DATA_DIR + userId + "/"
15379 + info.packageName;
15380 }
15381 return newInfo;
15382 }
15383
15384 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080015385 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070015386 || userId < 1) {
15387 return aInfo;
15388 }
15389
15390 ActivityInfo info = new ActivityInfo(aInfo);
15391 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
15392 return info;
15393 }
15394
15395 static class ServiceMap {
15396
15397 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
15398 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
15399 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
15400 mServicesByIntentPerUser = new SparseArray<
15401 HashMap<Intent.FilterComparison, ServiceRecord>>();
15402
15403 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
15404 // TODO: Deal with global services
15405 if (DEBUG_MU)
15406 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
15407 return getServices(callingUser).get(name);
15408 }
15409
15410 ServiceRecord getServiceByName(ComponentName name) {
15411 return getServiceByName(name, -1);
15412 }
15413
15414 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15415 // TODO: Deal with global services
15416 if (DEBUG_MU)
15417 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
15418 return getServicesByIntent(callingUser).get(filter);
15419 }
15420
15421 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
15422 return getServiceByIntent(filter, -1);
15423 }
15424
15425 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
15426 // TODO: Deal with global services
15427 getServices(callingUser).put(name, value);
15428 }
15429
15430 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
15431 ServiceRecord value) {
15432 // TODO: Deal with global services
15433 getServicesByIntent(callingUser).put(filter, value);
15434 }
15435
15436 void removeServiceByName(ComponentName name, int callingUser) {
15437 // TODO: Deal with global services
15438 ServiceRecord removed = getServices(callingUser).remove(name);
15439 if (DEBUG_MU)
15440 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15441 + " removed=" + removed);
15442 }
15443
15444 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15445 // TODO: Deal with global services
15446 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15447 if (DEBUG_MU)
15448 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15449 + " removed=" + removed);
15450 }
15451
15452 Collection<ServiceRecord> getAllServices(int callingUser) {
15453 // TODO: Deal with global services
15454 return getServices(callingUser).values();
15455 }
15456
15457 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15458 HashMap map = mServicesByNamePerUser.get(callingUser);
15459 if (map == null) {
15460 map = new HashMap<ComponentName, ServiceRecord>();
15461 mServicesByNamePerUser.put(callingUser, map);
15462 }
15463 return map;
15464 }
15465
15466 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15467 int callingUser) {
15468 HashMap map = mServicesByIntentPerUser.get(callingUser);
15469 if (map == null) {
15470 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15471 mServicesByIntentPerUser.put(callingUser, map);
15472 }
15473 return map;
15474 }
15475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015476}