blob: 4e1e9d97a75fe607a787720cd0dd74e14cd8d14d [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.IApplicationThread;
42import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070043import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070044import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.app.IServiceConnection;
46import android.app.IThumbnailReceiver;
47import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070048import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070049import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070051import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080052import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020053import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080054import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070055import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.ComponentName;
57import android.content.ContentResolver;
58import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020059import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.Intent;
61import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070062import android.content.IIntentReceiver;
63import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070064import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.content.pm.ActivityInfo;
66import android.content.pm.ApplicationInfo;
67import android.content.pm.ConfigurationInfo;
68import android.content.pm.IPackageDataObserver;
69import android.content.pm.IPackageManager;
70import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080071import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070073import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.content.pm.ProviderInfo;
75import android.content.pm.ResolveInfo;
76import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070077import android.content.pm.UserInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070078import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040079import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.content.res.Configuration;
81import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070082import android.net.Proxy;
83import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.net.Uri;
85import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080086import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080087import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070088import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080089import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080091import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.FileUtils;
93import android.os.Handler;
94import android.os.IBinder;
95import android.os.IPermissionController;
96import android.os.Looper;
97import android.os.Message;
98import android.os.Parcel;
99import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700101import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.os.RemoteException;
103import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700104import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.SystemClock;
106import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700107import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700110import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800111import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800112import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.util.PrintWriterPrinter;
114import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700115import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700116import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.view.Gravity;
118import android.view.LayoutInflater;
119import android.view.View;
120import android.view.WindowManager;
121import android.view.WindowManagerPolicy;
122
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700123import java.io.BufferedInputStream;
124import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700125import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700126import java.io.DataInputStream;
127import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128import java.io.File;
129import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700130import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700132import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200133import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800134import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700136import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.lang.IllegalStateException;
138import java.lang.ref.WeakReference;
139import java.util.ArrayList;
Dianne Hackborncbb722e2012-02-07 18:33:49 -0800140import java.util.Arrays;
Amith Yamasani742a6712011-05-04 14:49:28 -0700141import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700142import java.util.Collections;
143import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.util.HashMap;
145import java.util.HashSet;
146import java.util.Iterator;
147import java.util.List;
148import java.util.Locale;
149import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700150import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700151import java.util.concurrent.atomic.AtomicBoolean;
152import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700154public final class ActivityManagerService extends ActivityManagerNative
155 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700156 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700158 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400160 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 static final boolean DEBUG_SWITCH = localLOGV || false;
162 static final boolean DEBUG_TASKS = localLOGV || false;
163 static final boolean DEBUG_PAUSE = localLOGV || false;
164 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
165 static final boolean DEBUG_TRANSITION = localLOGV || false;
166 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800167 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700168 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700170 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 static final boolean DEBUG_VISBILITY = localLOGV || false;
172 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700173 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800174 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700176 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700177 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700178 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700179 static final boolean DEBUG_POWER = localLOGV || false;
180 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700181 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 static final boolean VALIDATE_TOKENS = false;
183 static final boolean SHOW_ACTIVITY_START_TIME = true;
184
185 // Control over CPU and battery monitoring.
186 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
187 static final boolean MONITOR_CPU_USAGE = true;
188 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
189 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
190 static final boolean MONITOR_THREAD_CPU_USAGE = false;
191
Dianne Hackborn1655be42009-05-08 14:29:01 -0700192 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700193 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700194
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800195 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 // Maximum number of recent tasks that we can remember.
198 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700199
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700200 // Amount of time after a call to stopAppSwitches() during which we will
201 // prevent further untrusted switches from happening.
202 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
204 // How long we wait for a launched process to attach to the activity manager
205 // before we decide it's never going to come up for real.
206 static final int PROC_START_TIMEOUT = 10*1000;
207
Jeff Brown3f9dd282011-07-08 20:02:19 -0700208 // How long we wait for a launched process to attach to the activity manager
209 // before we decide it's never going to come up for real, when the process was
210 // started with a wrapper for instrumentation (such as Valgrind) because it
211 // could take much longer than usual.
212 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 // How long to wait after going idle before forcing apps to GC.
215 static final int GC_TIMEOUT = 5*1000;
216
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700217 // The minimum amount of time between successive GC requests for a process.
218 static final int GC_MIN_INTERVAL = 60*1000;
219
Dianne Hackborn287952c2010-09-22 22:34:31 -0700220 // The rate at which we check for apps using excessive power -- 15 mins.
221 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
222
223 // The minimum sample duration we will allow before deciding we have
224 // enough data on wake locks to start killing things.
225 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
226
227 // The minimum sample duration we will allow before deciding we have
228 // enough data on CPU usage to start killing things.
229 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800232 static final int BROADCAST_FG_TIMEOUT = 10*1000;
233 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234
235 // How long we wait for a service to finish executing.
236 static final int SERVICE_TIMEOUT = 20*1000;
237
238 // How long a service needs to be running until restarting its process
239 // is no longer considered to be a relaunch of the service.
240 static final int SERVICE_RESTART_DURATION = 5*1000;
241
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700242 // How long a service needs to be running until it will start back at
243 // SERVICE_RESTART_DURATION after being killed.
244 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
245
246 // Multiplying factor to increase restart duration time by, for each time
247 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
248 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
249
250 // The minimum amount of time between restarting services that we allow.
251 // That is, when multiple services are restarting, we won't allow each
252 // to restart less than this amount of time from the last one.
253 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 // Maximum amount of time for there to be no activity on a service before
256 // we consider it non-essential and allow its process to go on the
257 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700258 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259
260 // How long we wait until we timeout on key dispatching.
261 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 // How long we wait until we timeout on key dispatching during instrumentation.
264 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
265
Dan Egnor42471dd2010-01-07 17:25:22 -0800266 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267
268 static final String[] EMPTY_STRING_ARRAY = new String[0];
269
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700270 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700271
272 private final boolean mHeadless;
273
Joe Onorato54a4a412011-11-02 20:50:08 -0700274 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
275 // default actuion automatically. Important for devices without direct input
276 // devices.
277 private boolean mShowDialogs = true;
278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700280 * Description of a request to start a new activity, which has been held
281 * due to app switches being disabled.
282 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700283 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700284 ActivityRecord r;
285 ActivityRecord sourceRecord;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700286 Uri[] grantedUriPermissions;
287 int grantedMode;
288 boolean onlyIfNeeded;
289 }
290
291 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
292 = new ArrayList<PendingActivityLaunch>();
293
294 /**
Christopher Tatef46723b2012-01-26 14:19:24 -0800295 * BROADCASTS
296 *
297 * We keep two broadcast queues and associated bookkeeping, one for those at
298 * foreground priority, and one for normal (background-priority) broadcasts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 */
Christopher Tatef46723b2012-01-26 14:19:24 -0800300 public class BroadcastQueue {
301 static final String TAG = "BroadcastQueue";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302
Christopher Tatef46723b2012-01-26 14:19:24 -0800303 static final int MAX_BROADCAST_HISTORY = 25;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304
Christopher Tatef46723b2012-01-26 14:19:24 -0800305 /**
306 * Recognizable moniker for this queue
307 */
308 String mQueueName;
Dianne Hackborn12527f92009-11-11 17:39:50 -0800309
Christopher Tatef46723b2012-01-26 14:19:24 -0800310 /**
311 * Timeout period for this queue's broadcasts
312 */
313 long mTimeoutPeriod;
314
315 /**
316 * Lists of all active broadcasts that are to be executed immediately
317 * (without waiting for another broadcast to finish). Currently this only
318 * contains broadcasts to registered receivers, to avoid spinning up
319 * a bunch of processes to execute IntentReceiver components. Background-
320 * and foreground-priority broadcasts are queued separately.
321 */
322 final ArrayList<BroadcastRecord> mParallelBroadcasts
323 = new ArrayList<BroadcastRecord>();
324 /**
325 * List of all active broadcasts that are to be executed one at a time.
326 * The object at the top of the list is the currently activity broadcasts;
327 * those after it are waiting for the top to finish. As with parallel
328 * broadcasts, separate background- and foreground-priority queues are
329 * maintained.
330 */
331 final ArrayList<BroadcastRecord> mOrderedBroadcasts
332 = new ArrayList<BroadcastRecord>();
333
334 /**
335 * Historical data of past broadcasts, for debugging.
336 */
337 final BroadcastRecord[] mBroadcastHistory
338 = new BroadcastRecord[MAX_BROADCAST_HISTORY];
339
340 /**
341 * Set when we current have a BROADCAST_INTENT_MSG in flight.
342 */
343 boolean mBroadcastsScheduled = false;
344
345 /**
346 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
347 */
348 boolean mPendingBroadcastTimeoutMessage;
349
350 /**
351 * Intent broadcasts that we have tried to start, but are
352 * waiting for the application's process to be created. We only
353 * need one per scheduling class (instead of a list) because we always
354 * process broadcasts one at a time, so no others can be started while
355 * waiting for this one.
356 */
357 BroadcastRecord mPendingBroadcast = null;
358
359 /**
360 * The receiver index that is pending, to restart the broadcast if needed.
361 */
362 int mPendingBroadcastRecvIndex;
363
364 BroadcastQueue(String name, long timeoutPeriod) {
365 mQueueName = name;
366 mTimeoutPeriod = timeoutPeriod;
367 }
368
369 public boolean isPendingBroadcastProcessLocked(int pid) {
370 return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
371 }
372
373 public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
374 mParallelBroadcasts.add(r);
375 }
376
377 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
378 mOrderedBroadcasts.add(r);
379 }
380
381 public final boolean replaceParallelBroadcastLocked(BroadcastRecord r) {
382 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
383 if (r.intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
384 if (DEBUG_BROADCAST) Slog.v(TAG,
385 "***** DROPPING PARALLEL ["
386 + mQueueName + "]: " + r.intent);
387 mParallelBroadcasts.set(i, r);
388 return true;
389 }
390 }
391 return false;
392 }
393
394 public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
395 for (int i=mOrderedBroadcasts.size()-1; i>0; i--) {
396 if (r.intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
397 if (DEBUG_BROADCAST) Slog.v(TAG,
398 "***** DROPPING ORDERED ["
399 + mQueueName + "]: " + r.intent);
400 mOrderedBroadcasts.set(i, r);
401 return true;
402 }
403 }
404 return false;
405 }
406
407 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
408 boolean didSomething = false;
409 final BroadcastRecord br = mPendingBroadcast;
410 if (br != null && br.curApp.pid == app.pid) {
411 try {
412 mPendingBroadcast = null;
413 processCurBroadcastLocked(br, app);
414 didSomething = true;
415 } catch (Exception e) {
416 Slog.w(TAG, "Exception in new application when starting receiver "
417 + br.curComponent.flattenToShortString(), e);
418 logBroadcastReceiverDiscardLocked(br);
419 finishReceiverLocked(br, br.resultCode, br.resultData,
420 br.resultExtras, br.resultAbort, true);
421 scheduleBroadcastsLocked();
422 // We need to reset the state if we fails to start the receiver.
423 br.state = BroadcastRecord.IDLE;
424 throw new RuntimeException(e.getMessage());
425 }
426 }
427 return didSomething;
428 }
429
430 public void skipPendingBroadcastLocked(int pid) {
431 final BroadcastRecord br = mPendingBroadcast;
432 if (br != null && br.curApp.pid == pid) {
433 br.state = BroadcastRecord.IDLE;
434 br.nextReceiver = mPendingBroadcastRecvIndex;
435 mPendingBroadcast = null;
436 scheduleBroadcastsLocked();
437 }
438 }
439
440 public void skipCurrentReceiverLocked(ProcessRecord app) {
441 boolean reschedule = false;
442 BroadcastRecord r = app.curReceiver;
443 if (r != null) {
444 // The current broadcast is waiting for this app's receiver
445 // to be finished. Looks like that's not going to happen, so
446 // let the broadcast continue.
447 logBroadcastReceiverDiscardLocked(r);
448 finishReceiverLocked(r, r.resultCode, r.resultData,
449 r.resultExtras, r.resultAbort, true);
450 reschedule = true;
451 }
452
453 r = mPendingBroadcast;
454 if (r != null && r.curApp == app) {
455 if (DEBUG_BROADCAST) Slog.v(TAG,
456 "[" + mQueueName + "] skip & discard pending app " + r);
457 logBroadcastReceiverDiscardLocked(r);
458 finishReceiverLocked(r, r.resultCode, r.resultData,
459 r.resultExtras, r.resultAbort, true);
460 reschedule = true;
461 }
462 if (reschedule) {
463 scheduleBroadcastsLocked();
464 }
465 }
466
467 public void scheduleBroadcastsLocked() {
468 if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts ["
469 + mQueueName + "]: current="
470 + mBroadcastsScheduled);
471
472 if (mBroadcastsScheduled) {
473 return;
474 }
475 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
476 mBroadcastsScheduled = true;
477 }
478
479 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
480 if (mOrderedBroadcasts.size() > 0) {
481 final BroadcastRecord r = mOrderedBroadcasts.get(0);
482 if (r != null && r.receiver == receiver) {
483 return r;
484 }
485 }
486 return null;
487 }
488
489 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
490 String resultData, Bundle resultExtras, boolean resultAbort,
491 boolean explicit) {
492 int state = r.state;
493 r.state = BroadcastRecord.IDLE;
494 if (state == BroadcastRecord.IDLE) {
495 if (explicit) {
496 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
497 }
498 }
499 r.receiver = null;
500 r.intent.setComponent(null);
501 if (r.curApp != null) {
502 r.curApp.curReceiver = null;
503 }
504 if (r.curFilter != null) {
505 r.curFilter.receiverList.curBroadcast = null;
506 }
507 r.curFilter = null;
508 r.curApp = null;
509 r.curComponent = null;
510 r.curReceiver = null;
511 mPendingBroadcast = null;
512
513 r.resultCode = resultCode;
514 r.resultData = resultData;
515 r.resultExtras = resultExtras;
516 r.resultAbort = resultAbort;
517
518 // We will process the next receiver right now if this is finishing
519 // an app receiver (which is always asynchronous) or after we have
520 // come back from calling a receiver.
521 return state == BroadcastRecord.APP_RECEIVE
522 || state == BroadcastRecord.CALL_DONE_RECEIVE;
523 }
524
525 private final void processNextBroadcast(boolean fromMsg) {
526 synchronized(ActivityManagerService.this) {
527 BroadcastRecord r;
528
529 if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast ["
530 + mQueueName + "]: "
531 + mParallelBroadcasts.size() + " broadcasts, "
532 + mOrderedBroadcasts.size() + " ordered broadcasts");
533
534 updateCpuStats();
535
536 if (fromMsg) {
537 mBroadcastsScheduled = false;
538 }
539
540 // First, deliver any non-serialized broadcasts right away.
541 while (mParallelBroadcasts.size() > 0) {
542 r = mParallelBroadcasts.remove(0);
543 r.dispatchTime = SystemClock.uptimeMillis();
544 r.dispatchClockTime = System.currentTimeMillis();
545 final int N = r.receivers.size();
546 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast ["
547 + mQueueName + "] " + r);
548 for (int i=0; i<N; i++) {
549 Object target = r.receivers.get(i);
550 if (DEBUG_BROADCAST) Slog.v(TAG,
551 "Delivering non-ordered on [" + mQueueName + "] to registered "
552 + target + ": " + r);
553 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
554 }
555 addBroadcastToHistoryLocked(r);
556 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast ["
557 + mQueueName + "] " + r);
558 }
559
560 // Now take care of the next serialized one...
561
562 // If we are waiting for a process to come up to handle the next
563 // broadcast, then do nothing at this point. Just in case, we
564 // check that the process we're waiting for still exists.
565 if (mPendingBroadcast != null) {
566 if (DEBUG_BROADCAST_LIGHT) {
567 Slog.v(TAG, "processNextBroadcast ["
568 + mQueueName + "]: waiting for "
569 + mPendingBroadcast.curApp);
570 }
571
572 boolean isDead;
573 synchronized (mPidsSelfLocked) {
574 isDead = (mPidsSelfLocked.get(mPendingBroadcast.curApp.pid) == null);
575 }
576 if (!isDead) {
577 // It's still alive, so keep waiting
578 return;
579 } else {
580 Slog.w(TAG, "pending app ["
581 + mQueueName + "]" + mPendingBroadcast.curApp
582 + " died before responding to broadcast");
583 mPendingBroadcast.state = BroadcastRecord.IDLE;
584 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
585 mPendingBroadcast = null;
586 }
587 }
588
589 boolean looped = false;
590
591 do {
592 if (mOrderedBroadcasts.size() == 0) {
593 // No more broadcasts pending, so all done!
594 scheduleAppGcsLocked();
595 if (looped) {
596 // If we had finished the last ordered broadcast, then
597 // make sure all processes have correct oom and sched
598 // adjustments.
599 updateOomAdjLocked();
600 }
601 return;
602 }
603 r = mOrderedBroadcasts.get(0);
604 boolean forceReceive = false;
605
606 // Ensure that even if something goes awry with the timeout
607 // detection, we catch "hung" broadcasts here, discard them,
608 // and continue to make progress.
609 //
610 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
611 // receivers don't get executed with timeouts. They're intended for
612 // one time heavy lifting after system upgrades and can take
613 // significant amounts of time.
614 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
615 if (mProcessesReady && r.dispatchTime > 0) {
616 long now = SystemClock.uptimeMillis();
617 if ((numReceivers > 0) &&
618 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
619 Slog.w(TAG, "Hung broadcast ["
620 + mQueueName + "] discarded after timeout failure:"
621 + " now=" + now
622 + " dispatchTime=" + r.dispatchTime
623 + " startTime=" + r.receiverTime
624 + " intent=" + r.intent
625 + " numReceivers=" + numReceivers
626 + " nextReceiver=" + r.nextReceiver
627 + " state=" + r.state);
628 broadcastTimeoutLocked(false); // forcibly finish this broadcast
629 forceReceive = true;
630 r.state = BroadcastRecord.IDLE;
631 }
632 }
633
634 if (r.state != BroadcastRecord.IDLE) {
635 if (DEBUG_BROADCAST) Slog.d(TAG,
636 "processNextBroadcast("
637 + mQueueName + ") called when not idle (state="
638 + r.state + ")");
639 return;
640 }
641
642 if (r.receivers == null || r.nextReceiver >= numReceivers
643 || r.resultAbort || forceReceive) {
644 // No more receivers for this broadcast! Send the final
645 // result if requested...
646 if (r.resultTo != null) {
647 try {
648 if (DEBUG_BROADCAST) {
649 int seq = r.intent.getIntExtra("seq", -1);
650 Slog.i(TAG, "Finishing broadcast ["
651 + mQueueName + "] " + r.intent.getAction()
652 + " seq=" + seq + " app=" + r.callerApp);
653 }
654 performReceiveLocked(r.callerApp, r.resultTo,
655 new Intent(r.intent), r.resultCode,
656 r.resultData, r.resultExtras, false, false);
657 // Set this to null so that the reference
658 // (local and remote) isnt kept in the mBroadcastHistory.
659 r.resultTo = null;
660 } catch (RemoteException e) {
661 Slog.w(TAG, "Failure ["
662 + mQueueName + "] sending broadcast result of "
663 + r.intent, e);
664 }
665 }
666
667 if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
668 cancelBroadcastTimeoutLocked();
669
670 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
671 + r);
672
673 // ... and on to the next...
674 addBroadcastToHistoryLocked(r);
675 mOrderedBroadcasts.remove(0);
676 r = null;
677 looped = true;
678 continue;
679 }
680 } while (r == null);
681
682 // Get the next receiver...
683 int recIdx = r.nextReceiver++;
684
685 // Keep track of when this receiver started, and make sure there
686 // is a timeout message pending to kill it if need be.
687 r.receiverTime = SystemClock.uptimeMillis();
688 if (recIdx == 0) {
689 r.dispatchTime = r.receiverTime;
690 r.dispatchClockTime = System.currentTimeMillis();
691 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast ["
692 + mQueueName + "] " + r);
693 }
694 if (! mPendingBroadcastTimeoutMessage) {
695 long timeoutTime = r.receiverTime + mTimeoutPeriod;
696 if (DEBUG_BROADCAST) Slog.v(TAG,
697 "Submitting BROADCAST_TIMEOUT_MSG ["
698 + mQueueName + "] for " + r + " at " + timeoutTime);
699 setBroadcastTimeoutLocked(timeoutTime);
700 }
701
702 Object nextReceiver = r.receivers.get(recIdx);
703 if (nextReceiver instanceof BroadcastFilter) {
704 // Simple case: this is a registered receiver who gets
705 // a direct call.
706 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
707 if (DEBUG_BROADCAST) Slog.v(TAG,
708 "Delivering ordered ["
709 + mQueueName + "] to registered "
710 + filter + ": " + r);
711 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
712 if (r.receiver == null || !r.ordered) {
713 // The receiver has already finished, so schedule to
714 // process the next one.
715 if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing ["
716 + mQueueName + "]: ordered="
717 + r.ordered + " receiver=" + r.receiver);
718 r.state = BroadcastRecord.IDLE;
719 scheduleBroadcastsLocked();
720 }
721 return;
722 }
723
724 // Hard case: need to instantiate the receiver, possibly
725 // starting its application process to host it.
726
727 ResolveInfo info =
728 (ResolveInfo)nextReceiver;
729
730 boolean skip = false;
731 int perm = checkComponentPermission(info.activityInfo.permission,
732 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
733 info.activityInfo.exported);
734 if (perm != PackageManager.PERMISSION_GRANTED) {
735 if (!info.activityInfo.exported) {
736 Slog.w(TAG, "Permission Denial: broadcasting "
737 + r.intent.toString()
738 + " from " + r.callerPackage + " (pid=" + r.callingPid
739 + ", uid=" + r.callingUid + ")"
740 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
741 + " due to receiver " + info.activityInfo.packageName
742 + "/" + info.activityInfo.name);
743 } else {
744 Slog.w(TAG, "Permission Denial: broadcasting "
745 + r.intent.toString()
746 + " from " + r.callerPackage + " (pid=" + r.callingPid
747 + ", uid=" + r.callingUid + ")"
748 + " requires " + info.activityInfo.permission
749 + " due to receiver " + info.activityInfo.packageName
750 + "/" + info.activityInfo.name);
751 }
752 skip = true;
753 }
754 if (info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
755 r.requiredPermission != null) {
756 try {
757 perm = AppGlobals.getPackageManager().
758 checkPermission(r.requiredPermission,
759 info.activityInfo.applicationInfo.packageName);
760 } catch (RemoteException e) {
761 perm = PackageManager.PERMISSION_DENIED;
762 }
763 if (perm != PackageManager.PERMISSION_GRANTED) {
764 Slog.w(TAG, "Permission Denial: receiving "
765 + r.intent + " to "
766 + info.activityInfo.applicationInfo.packageName
767 + " requires " + r.requiredPermission
768 + " due to sender " + r.callerPackage
769 + " (uid " + r.callingUid + ")");
770 skip = true;
771 }
772 }
773 if (r.curApp != null && r.curApp.crashing) {
774 // If the target process is crashing, just skip it.
775 if (DEBUG_BROADCAST) Slog.v(TAG,
776 "Skipping deliver ordered ["
777 + mQueueName + "] " + r + " to " + r.curApp
778 + ": process crashing");
779 skip = true;
780 }
781
782 if (skip) {
783 if (DEBUG_BROADCAST) Slog.v(TAG,
784 "Skipping delivery of ordered ["
785 + mQueueName + "] " + r + " for whatever reason");
786 r.receiver = null;
787 r.curFilter = null;
788 r.state = BroadcastRecord.IDLE;
789 scheduleBroadcastsLocked();
790 return;
791 }
792
793 r.state = BroadcastRecord.APP_RECEIVE;
794 String targetProcess = info.activityInfo.processName;
795 r.curComponent = new ComponentName(
796 info.activityInfo.applicationInfo.packageName,
797 info.activityInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -0700798 if (r.callingUid != Process.SYSTEM_UID) {
799 info.activityInfo = getActivityInfoForUser(info.activityInfo, UserId
800 .getUserId(r.callingUid));
801 }
Christopher Tatef46723b2012-01-26 14:19:24 -0800802 r.curReceiver = info.activityInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -0700803 if (DEBUG_MU && r.callingUid > UserId.PER_USER_RANGE) {
804 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
805 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
806 + info.activityInfo.applicationInfo.uid);
807 }
Christopher Tatef46723b2012-01-26 14:19:24 -0800808
809 // Broadcast is being executed, its package can't be stopped.
810 try {
811 AppGlobals.getPackageManager().setPackageStoppedState(
812 r.curComponent.getPackageName(), false);
813 } catch (RemoteException e) {
814 } catch (IllegalArgumentException e) {
815 Slog.w(TAG, "Failed trying to unstop package "
816 + r.curComponent.getPackageName() + ": " + e);
817 }
818
819 // Is this receiver's application already running?
820 ProcessRecord app = getProcessRecordLocked(targetProcess,
821 info.activityInfo.applicationInfo.uid);
822 if (app != null && app.thread != null) {
823 try {
824 app.addPackage(info.activityInfo.packageName);
825 processCurBroadcastLocked(r, app);
826 return;
827 } catch (RemoteException e) {
828 Slog.w(TAG, "Exception when sending broadcast to "
829 + r.curComponent, e);
830 }
831
832 // If a dead object exception was thrown -- fall through to
833 // restart the application.
834 }
835
836 // Not running -- get it started, to be executed when the app comes up.
837 if (DEBUG_BROADCAST) Slog.v(TAG,
838 "Need to start app ["
839 + mQueueName + "] " + targetProcess + " for broadcast " + r);
840 if ((r.curApp=startProcessLocked(targetProcess,
841 info.activityInfo.applicationInfo, true,
842 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
843 "broadcast", r.curComponent,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800844 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false))
Christopher Tatef46723b2012-01-26 14:19:24 -0800845 == null) {
846 // Ah, this recipient is unavailable. Finish it if necessary,
847 // and mark the broadcast record as ready for the next.
848 Slog.w(TAG, "Unable to launch app "
849 + info.activityInfo.applicationInfo.packageName + "/"
850 + info.activityInfo.applicationInfo.uid + " for broadcast "
851 + r.intent + ": process is bad");
852 logBroadcastReceiverDiscardLocked(r);
853 finishReceiverLocked(r, r.resultCode, r.resultData,
854 r.resultExtras, r.resultAbort, true);
855 scheduleBroadcastsLocked();
856 r.state = BroadcastRecord.IDLE;
857 return;
858 }
859
860 mPendingBroadcast = r;
861 mPendingBroadcastRecvIndex = recIdx;
862 }
863 }
864
865 final void setBroadcastTimeoutLocked(long timeoutTime) {
866 if (! mPendingBroadcastTimeoutMessage) {
867 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
868 mHandler.sendMessageAtTime(msg, timeoutTime);
869 mPendingBroadcastTimeoutMessage = true;
870 }
871 }
872
873 final void cancelBroadcastTimeoutLocked() {
874 if (mPendingBroadcastTimeoutMessage) {
875 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
876 mPendingBroadcastTimeoutMessage = false;
877 }
878 }
879
880 final void broadcastTimeoutLocked(boolean fromMsg) {
881 if (fromMsg) {
882 mPendingBroadcastTimeoutMessage = false;
883 }
884
885 if (mOrderedBroadcasts.size() == 0) {
886 return;
887 }
888
889 long now = SystemClock.uptimeMillis();
890 BroadcastRecord r = mOrderedBroadcasts.get(0);
891 if (fromMsg) {
892 if (mDidDexOpt) {
893 // Delay timeouts until dexopt finishes.
894 mDidDexOpt = false;
895 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
896 setBroadcastTimeoutLocked(timeoutTime);
897 return;
898 }
899 if (! mProcessesReady) {
900 // Only process broadcast timeouts if the system is ready. That way
901 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
902 // to do heavy lifting for system up.
903 return;
904 }
905
906 long timeoutTime = r.receiverTime + mTimeoutPeriod;
907 if (timeoutTime > now) {
908 // We can observe premature timeouts because we do not cancel and reset the
909 // broadcast timeout message after each receiver finishes. Instead, we set up
910 // an initial timeout then kick it down the road a little further as needed
911 // when it expires.
912 if (DEBUG_BROADCAST) Slog.v(TAG,
913 "Premature timeout ["
914 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
915 + timeoutTime);
916 setBroadcastTimeoutLocked(timeoutTime);
917 return;
918 }
919 }
920
921 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
922 + ", started " + (now - r.receiverTime) + "ms ago");
923 r.receiverTime = now;
924 r.anrCount++;
925
926 // Current receiver has passed its expiration date.
927 if (r.nextReceiver <= 0) {
928 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
929 return;
930 }
931
932 ProcessRecord app = null;
933 String anrMessage = null;
934
935 Object curReceiver = r.receivers.get(r.nextReceiver-1);
936 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
937 logBroadcastReceiverDiscardLocked(r);
938 if (curReceiver instanceof BroadcastFilter) {
939 BroadcastFilter bf = (BroadcastFilter)curReceiver;
940 if (bf.receiverList.pid != 0
941 && bf.receiverList.pid != MY_PID) {
942 synchronized (ActivityManagerService.this.mPidsSelfLocked) {
943 app = ActivityManagerService.this.mPidsSelfLocked.get(
944 bf.receiverList.pid);
945 }
946 }
947 } else {
948 app = r.curApp;
949 }
950
951 if (app != null) {
952 anrMessage = "Broadcast of " + r.intent.toString();
953 }
954
955 if (mPendingBroadcast == r) {
956 mPendingBroadcast = null;
957 }
958
959 // Move on to the next receiver.
960 finishReceiverLocked(r, r.resultCode, r.resultData,
961 r.resultExtras, r.resultAbort, true);
962 scheduleBroadcastsLocked();
963
964 if (anrMessage != null) {
965 // Post the ANR to the handler since we do not want to process ANRs while
966 // potentially holding our lock.
967 mHandler.post(new AppNotResponding(app, anrMessage));
968 }
969 }
970
971 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
972 if (r.callingUid < 0) {
973 // This was from a registerReceiver() call; ignore it.
974 return;
975 }
976 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
977 MAX_BROADCAST_HISTORY-1);
978 r.finishTime = SystemClock.uptimeMillis();
979 mBroadcastHistory[0] = r;
980 }
981
982 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
983 if (r.nextReceiver > 0) {
984 Object curReceiver = r.receivers.get(r.nextReceiver-1);
985 if (curReceiver instanceof BroadcastFilter) {
986 BroadcastFilter bf = (BroadcastFilter) curReceiver;
987 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
988 System.identityHashCode(r),
989 r.intent.getAction(),
990 r.nextReceiver - 1,
991 System.identityHashCode(bf));
992 } else {
993 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
994 System.identityHashCode(r),
995 r.intent.getAction(),
996 r.nextReceiver - 1,
997 ((ResolveInfo)curReceiver).toString());
998 }
999 } else {
1000 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
1001 + r);
1002 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1003 System.identityHashCode(r),
1004 r.intent.getAction(),
1005 r.nextReceiver,
1006 "NONE");
1007 }
1008 }
1009
1010 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1011 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
1012 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1013 || mPendingBroadcast != null) {
1014 boolean printed = false;
1015 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
1016 BroadcastRecord br = mParallelBroadcasts.get(i);
1017 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1018 continue;
1019 }
1020 if (!printed) {
1021 if (needSep) {
1022 pw.println();
1023 needSep = false;
1024 }
1025 printed = true;
1026 pw.println(" Active broadcasts [" + mQueueName + "]:");
1027 }
1028 pw.println(" Broadcast #" + i + ":");
1029 br.dump(pw, " ");
1030 }
1031 printed = false;
1032 needSep = true;
1033 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
1034 BroadcastRecord br = mOrderedBroadcasts.get(i);
1035 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1036 continue;
1037 }
1038 if (!printed) {
1039 if (needSep) {
1040 pw.println();
1041 }
1042 needSep = true;
1043 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1044 }
1045 pw.println(" Ordered Broadcast #" + i + ":");
1046 mOrderedBroadcasts.get(i).dump(pw, " ");
1047 }
1048 if (dumpPackage == null || (mPendingBroadcast != null
1049 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1050 if (needSep) {
1051 pw.println();
1052 }
1053 pw.println(" Pending broadcast [" + mQueueName + "]:");
1054 if (mPendingBroadcast != null) {
1055 mPendingBroadcast.dump(pw, " ");
1056 } else {
1057 pw.println(" (null)");
1058 }
1059 needSep = true;
1060 }
1061 }
1062
1063 boolean printed = false;
1064 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
1065 BroadcastRecord r = mBroadcastHistory[i];
1066 if (r == null) {
1067 break;
1068 }
1069 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1070 continue;
1071 }
1072 if (!printed) {
1073 if (needSep) {
1074 pw.println();
1075 }
1076 needSep = true;
1077 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1078 printed = true;
1079 }
1080 if (dumpAll) {
1081 pw.print(" Historical Broadcast #"); pw.print(i); pw.println(":");
1082 r.dump(pw, " ");
1083 } else {
1084 if (i >= 50) {
1085 pw.println(" ...");
1086 break;
1087 }
1088 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1089 }
1090 }
1091
1092 return needSep;
1093 }
1094 }
1095
1096 final BroadcastQueue mFgBroadcastQueue = new BroadcastQueue("foreground", BROADCAST_FG_TIMEOUT);
1097 final BroadcastQueue mBgBroadcastQueue = new BroadcastQueue("background", BROADCAST_BG_TIMEOUT);
1098 // Convenient for easy iteration over the queues. Foreground is first
1099 // so that dispatch of foreground broadcasts gets precedence.
1100 final BroadcastQueue[] mBroadcastQueues = { mFgBroadcastQueue, mBgBroadcastQueue };
1101
1102 BroadcastQueue broadcastQueueForIntent(Intent intent) {
1103 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
1104 if (DEBUG_BACKGROUND_BROADCAST) {
1105 Slog.i(TAG, "Broadcast intent " + intent + " on "
1106 + (isFg ? "foreground" : "background")
1107 + " queue");
1108 }
1109 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
1110 }
1111
1112 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
1113 for (BroadcastQueue queue : mBroadcastQueues) {
1114 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
1115 if (r != null) {
1116 return r;
1117 }
1118 }
1119 return null;
1120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121
1122 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 * Activity we have told the window manager to have key focus.
1124 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001125 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07001126 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 * List of intents that were used to start the most recent tasks.
1128 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001129 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130
1131 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -07001132 * Process management.
1133 */
1134 final ProcessList mProcessList = new ProcessList();
1135
1136 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 * All of the applications we currently have running organized by name.
1138 * The keys are strings of the application package name (as
1139 * returned by the package manager), and the keys are ApplicationRecord
1140 * objects.
1141 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001142 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143
1144 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001145 * The currently running isolated processes.
1146 */
1147 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
1148
1149 /**
1150 * Counter for assigning isolated process uids, to avoid frequently reusing the
1151 * same ones.
1152 */
1153 int mNextIsolatedProcessUid = 0;
1154
1155 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -07001156 * The currently running heavy-weight process, if any.
1157 */
1158 ProcessRecord mHeavyWeightProcess = null;
1159
1160 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 * The last time that various processes have crashed.
1162 */
1163 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
1164
1165 /**
1166 * Set of applications that we consider to be bad, and will reject
1167 * incoming broadcasts from (which the user has no control over).
1168 * Processes are added to this set when they have crashed twice within
1169 * a minimum amount of time; they are removed from it when they are
1170 * later restarted (hopefully due to some user action). The value is the
1171 * time it was added to the list.
1172 */
1173 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
1174
1175 /**
1176 * All of the processes we currently have running organized by pid.
1177 * The keys are the pid running the application.
1178 *
1179 * <p>NOTE: This object is protected by its own lock, NOT the global
1180 * activity manager lock!
1181 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001182 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183
1184 /**
1185 * All of the processes that have been forced to be foreground. The key
1186 * is the pid of the caller who requested it (we hold a death
1187 * link on it).
1188 */
1189 abstract class ForegroundToken implements IBinder.DeathRecipient {
1190 int pid;
1191 IBinder token;
1192 }
1193 final SparseArray<ForegroundToken> mForegroundProcesses
1194 = new SparseArray<ForegroundToken>();
1195
1196 /**
1197 * List of records for processes that someone had tried to start before the
1198 * system was ready. We don't start them at that point, but ensure they
1199 * are started by the time booting is complete.
1200 */
1201 final ArrayList<ProcessRecord> mProcessesOnHold
1202 = new ArrayList<ProcessRecord>();
1203
1204 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 * List of persistent applications that are in the process
1206 * of being started.
1207 */
1208 final ArrayList<ProcessRecord> mPersistentStartingProcesses
1209 = new ArrayList<ProcessRecord>();
1210
1211 /**
1212 * Processes that are being forcibly torn down.
1213 */
1214 final ArrayList<ProcessRecord> mRemovedProcesses
1215 = new ArrayList<ProcessRecord>();
1216
1217 /**
1218 * List of running applications, sorted by recent usage.
1219 * The first entry in the list is the least recently used.
1220 * It contains ApplicationRecord objects. This list does NOT include
1221 * any persistent application records (since we never want to exit them).
1222 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001223 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 = new ArrayList<ProcessRecord>();
1225
1226 /**
1227 * List of processes that should gc as soon as things are idle.
1228 */
1229 final ArrayList<ProcessRecord> mProcessesToGc
1230 = new ArrayList<ProcessRecord>();
1231
1232 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -08001233 * This is the process holding what we currently consider to be
1234 * the "home" activity.
1235 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001236 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -08001237
1238 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -07001239 * This is the process holding the activity the user last visited that
1240 * is in a different process from the one they are currently in.
1241 */
1242 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -08001243
1244 /**
1245 * The time at which the previous process was last visible.
1246 */
1247 long mPreviousProcessVisibleTime;
1248
Dianne Hackbornf35fe232011-11-01 19:25:20 -07001249 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001250 * Packages that the user has asked to have run in screen size
1251 * compatibility mode instead of filling the screen.
1252 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001253 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001254
1255 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 * Set of PendingResultRecord objects that are currently active.
1257 */
1258 final HashSet mPendingResultRecords = new HashSet();
1259
1260 /**
1261 * Set of IntentSenderRecord objects that are currently active.
1262 */
1263 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
1264 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
1265
1266 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08001267 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07001268 * already logged DropBox entries for. Guarded by itself. If
1269 * something (rogue user app) forces this over
1270 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
1271 */
1272 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
1273 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
1274
1275 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07001276 * Strict Mode background batched logging state.
1277 *
1278 * The string buffer is guarded by itself, and its lock is also
1279 * used to determine if another batched write is already
1280 * in-flight.
1281 */
1282 private final StringBuilder mStrictModeBuffer = new StringBuilder();
1283
1284 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 * Keeps track of all IIntentReceivers that have been registered for
1286 * broadcasts. Hash keys are the receiver IBinder, hash value is
1287 * a ReceiverList.
1288 */
1289 final HashMap mRegisteredReceivers = new HashMap();
1290
1291 /**
1292 * Resolver for broadcast intents to registered receivers.
1293 * Holds BroadcastFilter (subclass of IntentFilter).
1294 */
1295 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
1296 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
1297 @Override
1298 protected boolean allowFilterResult(
1299 BroadcastFilter filter, List<BroadcastFilter> dest) {
1300 IBinder target = filter.receiverList.receiver.asBinder();
1301 for (int i=dest.size()-1; i>=0; i--) {
1302 if (dest.get(i).receiverList.receiver.asBinder() == target) {
1303 return false;
1304 }
1305 }
1306 return true;
1307 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001308
1309 @Override
1310 protected String packageForFilter(BroadcastFilter filter) {
1311 return filter.packageName;
1312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 };
1314
1315 /**
1316 * State of all active sticky broadcasts. Keys are the action of the
1317 * sticky Intent, values are an ArrayList of all broadcasted intents with
1318 * that action (which should usually be one).
1319 */
1320 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
1321 new HashMap<String, ArrayList<Intent>>();
1322
Amith Yamasani742a6712011-05-04 14:49:28 -07001323 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324
1325 /**
1326 * All currently bound service connections. Keys are the IBinder of
1327 * the client's IServiceConnection.
1328 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07001329 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
1330 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331
1332 /**
1333 * List of services that we have been asked to start,
1334 * but haven't yet been able to. It is used to hold start requests
1335 * while waiting for their corresponding application thread to get
1336 * going.
1337 */
1338 final ArrayList<ServiceRecord> mPendingServices
1339 = new ArrayList<ServiceRecord>();
1340
1341 /**
1342 * List of services that are scheduled to restart following a crash.
1343 */
1344 final ArrayList<ServiceRecord> mRestartingServices
1345 = new ArrayList<ServiceRecord>();
1346
1347 /**
1348 * List of services that are in the process of being stopped.
1349 */
1350 final ArrayList<ServiceRecord> mStoppingServices
1351 = new ArrayList<ServiceRecord>();
1352
1353 /**
Christopher Tate181fafa2009-05-14 11:12:14 -07001354 * Backup/restore process management
1355 */
1356 String mBackupAppName = null;
1357 BackupRecord mBackupTarget = null;
1358
1359 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 * List of PendingThumbnailsRecord objects of clients who are still
1361 * waiting to receive all of the thumbnails for a task.
1362 */
1363 final ArrayList mPendingThumbnails = new ArrayList();
1364
1365 /**
1366 * List of HistoryRecord objects that have been finished and must
1367 * still report back to a pending thumbnail receiver.
1368 */
1369 final ArrayList mCancelledThumbnails = new ArrayList();
1370
1371 /**
1372 * All of the currently running global content providers. Keys are a
1373 * string containing the provider name and values are a
1374 * ContentProviderRecord object containing the data about it. Note
1375 * that a single provider may be published under multiple names, so
1376 * there may be multiple entries here for a single one in mProvidersByClass.
1377 */
Dianne Hackborn860755f2010-06-03 18:47:52 -07001378 final HashMap<String, ContentProviderRecord> mProvidersByName
1379 = new HashMap<String, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380
1381 /**
1382 * All of the currently running global content providers. Keys are a
1383 * string containing the provider's implementation class and values are a
1384 * ContentProviderRecord object containing the data about it.
1385 */
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07001386 final HashMap<ComponentName, ContentProviderRecord> mProvidersByClass
1387 = new HashMap<ComponentName, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388
Amith Yamasani742a6712011-05-04 14:49:28 -07001389 final ProviderMap mProviderMap = new ProviderMap();
1390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 /**
1392 * List of content providers who have clients waiting for them. The
1393 * application is currently being launched and the provider will be
1394 * removed from this list once it is published.
1395 */
Dianne Hackborn860755f2010-06-03 18:47:52 -07001396 final ArrayList<ContentProviderRecord> mLaunchingProviders
1397 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398
1399 /**
1400 * Global set of specific Uri permissions that have been granted.
1401 */
1402 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
1403 = new SparseArray<HashMap<Uri, UriPermission>>();
1404
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001405 CoreSettingsObserver mCoreSettingsObserver;
1406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 /**
1408 * Thread-local storage used to carry caller permissions over through
1409 * indirect content-provider access.
1410 * @see #ActivityManagerService.openContentUri()
1411 */
1412 private class Identity {
1413 public int pid;
1414 public int uid;
1415
1416 Identity(int _pid, int _uid) {
1417 pid = _pid;
1418 uid = _uid;
1419 }
1420 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
1423
1424 /**
1425 * All information we have collected about the runtime performance of
1426 * any user id that can impact battery performance.
1427 */
1428 final BatteryStatsService mBatteryStatsService;
1429
1430 /**
1431 * information about component usage
1432 */
1433 final UsageStatsService mUsageStatsService;
1434
1435 /**
1436 * Current configuration information. HistoryRecord objects are given
1437 * a reference to this object to indicate which configuration they are
1438 * currently running in, so this object must be kept immutable.
1439 */
1440 Configuration mConfiguration = new Configuration();
1441
1442 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001443 * Current sequencing integer of the configuration, for skipping old
1444 * configurations.
1445 */
1446 int mConfigurationSeq = 0;
1447
1448 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -07001449 * Hardware-reported OpenGLES version.
1450 */
1451 final int GL_ES_VERSION;
1452
1453 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 * List of initialization arguments to pass to all processes when binding applications to them.
1455 * For example, references to the commonly used services.
1456 */
1457 HashMap<String, IBinder> mAppBindArgs;
1458
1459 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07001460 * Temporary to avoid allocations. Protected by main lock.
1461 */
1462 final StringBuilder mStringBuilder = new StringBuilder(256);
1463
1464 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 * Used to control how we initialize the service.
1466 */
1467 boolean mStartRunning = false;
1468 ComponentName mTopComponent;
1469 String mTopAction;
1470 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001471 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 boolean mSystemReady = false;
1473 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001474 boolean mWaitingUpdate = false;
1475 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001476 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001477 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478
1479 Context mContext;
1480
1481 int mFactoryTest;
1482
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001483 boolean mCheckedForSetup;
1484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001486 * The time at which we will allow normal application switches again,
1487 * after a call to {@link #stopAppSwitches()}.
1488 */
1489 long mAppSwitchesAllowedTime;
1490
1491 /**
1492 * This is set to true after the first switch after mAppSwitchesAllowedTime
1493 * is set; any switches after that will clear the time.
1494 */
1495 boolean mDidAppSwitch;
1496
1497 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -07001498 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001499 */
Dianne Hackborn287952c2010-09-22 22:34:31 -07001500 long mLastPowerCheckRealtime;
1501
1502 /**
1503 * Last time (in uptime) at which we checked for power usage.
1504 */
1505 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001506
1507 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 * Set while we are wanting to sleep, to prevent any
1509 * activities from being started/resumed.
1510 */
1511 boolean mSleeping = false;
1512
1513 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -07001514 * Set if we are shutting down the system, similar to sleeping.
1515 */
1516 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517
1518 /**
1519 * Task identifier that activities are currently being started
1520 * in. Incremented each time a new task is created.
1521 * todo: Replace this with a TokenSpace class that generates non-repeating
1522 * integers that won't wrap.
1523 */
1524 int mCurTask = 1;
1525
1526 /**
1527 * Current sequence id for oom_adj computation traversal.
1528 */
1529 int mAdjSeq = 0;
1530
1531 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -07001532 * Current sequence id for process LRU updating.
1533 */
1534 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535
1536 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -07001537 * Keep track of the number of service processes we last found, to
1538 * determine on the next iteration which should be B services.
1539 */
1540 int mNumServiceProcs = 0;
1541 int mNewNumServiceProcs = 0;
1542
1543 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 * System monitoring: number of processes that died since the last
1545 * N procs were started.
1546 */
1547 int[] mProcDeaths = new int[20];
1548
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001549 /**
1550 * This is set if we had to do a delayed dexopt of an app before launching
1551 * it, to increasing the ANR timeouts in that case.
1552 */
1553 boolean mDidDexOpt;
1554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 String mDebugApp = null;
1556 boolean mWaitForDebugger = false;
1557 boolean mDebugTransient = false;
1558 String mOrigDebugApp = null;
1559 boolean mOrigWaitForDebugger = false;
1560 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001561 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001562 String mProfileApp = null;
1563 ProcessRecord mProfileProc = null;
1564 String mProfileFile;
1565 ParcelFileDescriptor mProfileFd;
1566 int mProfileType = 0;
1567 boolean mAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568
Jeff Sharkeya4620792011-05-20 15:29:23 -07001569 final RemoteCallbackList<IProcessObserver> mProcessObservers
1570 = new RemoteCallbackList<IProcessObserver>();
1571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 /**
1573 * Callback of last caller to {@link #requestPss}.
1574 */
1575 Runnable mRequestPssCallback;
1576
1577 /**
1578 * Remaining processes for which we are waiting results from the last
1579 * call to {@link #requestPss}.
1580 */
1581 final ArrayList<ProcessRecord> mRequestPssList
1582 = new ArrayList<ProcessRecord>();
1583
1584 /**
1585 * Runtime statistics collection thread. This object's lock is used to
1586 * protect all related state.
1587 */
1588 final Thread mProcessStatsThread;
1589
1590 /**
1591 * Used to collect process stats when showing not responding dialog.
1592 * Protected by mProcessStatsThread.
1593 */
1594 final ProcessStats mProcessStats = new ProcessStats(
1595 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001596 final AtomicLong mLastCpuTime = new AtomicLong(0);
1597 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
1598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 long mLastWriteTime = 0;
1600
1601 /**
1602 * Set to true after the system has finished booting.
1603 */
1604 boolean mBooted = false;
1605
Dianne Hackborn7d608422011-08-07 16:24:18 -07001606 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001607 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608
1609 WindowManagerService mWindowManager;
1610
1611 static ActivityManagerService mSelf;
1612 static ActivityThread mSystemThread;
1613
1614 private final class AppDeathRecipient implements IBinder.DeathRecipient {
1615 final ProcessRecord mApp;
1616 final int mPid;
1617 final IApplicationThread mAppThread;
1618
1619 AppDeathRecipient(ProcessRecord app, int pid,
1620 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001621 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 TAG, "New death recipient " + this
1623 + " for thread " + thread.asBinder());
1624 mApp = app;
1625 mPid = pid;
1626 mAppThread = thread;
1627 }
1628
1629 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001630 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 TAG, "Death received in " + this
1632 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 synchronized(ActivityManagerService.this) {
1634 appDiedLocked(mApp, mPid, mAppThread);
1635 }
1636 }
1637 }
1638
1639 static final int SHOW_ERROR_MSG = 1;
1640 static final int SHOW_NOT_RESPONDING_MSG = 2;
1641 static final int SHOW_FACTORY_ERROR_MSG = 3;
1642 static final int UPDATE_CONFIGURATION_MSG = 4;
1643 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1644 static final int WAIT_FOR_DEBUGGER_MSG = 6;
1645 static final int BROADCAST_INTENT_MSG = 7;
1646 static final int BROADCAST_TIMEOUT_MSG = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 static final int SERVICE_TIMEOUT_MSG = 12;
1648 static final int UPDATE_TIME_ZONE = 13;
1649 static final int SHOW_UID_ERROR_MSG = 14;
1650 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001652 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001653 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001654 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001655 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
1656 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001657 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001658 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001659 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001660 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001661 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001662 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
1663 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001664 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665
1666 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001667 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001668 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669
1670 final Handler mHandler = new Handler() {
1671 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001672 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 //}
1674
1675 public void handleMessage(Message msg) {
1676 switch (msg.what) {
1677 case SHOW_ERROR_MSG: {
1678 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 synchronized (ActivityManagerService.this) {
1680 ProcessRecord proc = (ProcessRecord)data.get("app");
1681 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001682 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 return;
1684 }
1685 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -07001686 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -08001687 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 d.show();
1689 proc.crashDialog = d;
1690 } else {
1691 // The device is asleep, so just pretend that the user
1692 // saw a crash dialog and hit "force quit".
1693 res.set(0);
1694 }
1695 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001696
1697 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 } break;
1699 case SHOW_NOT_RESPONDING_MSG: {
1700 synchronized (ActivityManagerService.this) {
1701 HashMap data = (HashMap) msg.obj;
1702 ProcessRecord proc = (ProcessRecord)data.get("app");
1703 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001704 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 return;
1706 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001707
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001708 Intent intent = new Intent("android.intent.action.ANR");
1709 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -08001710 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1711 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001712 }
1713 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -08001714 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07001715 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -08001716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001718 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 d.show();
1720 proc.anrDialog = d;
1721 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001722
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001723 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001725 case SHOW_STRICT_MODE_VIOLATION_MSG: {
1726 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1727 synchronized (ActivityManagerService.this) {
1728 ProcessRecord proc = (ProcessRecord) data.get("app");
1729 if (proc == null) {
1730 Slog.e(TAG, "App not found when showing strict mode dialog.");
1731 break;
1732 }
1733 if (proc.crashDialog != null) {
1734 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1735 return;
1736 }
1737 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -07001738 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001739 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
1740 d.show();
1741 proc.crashDialog = d;
1742 } else {
1743 // The device is asleep, so just pretend that the user
1744 // saw a crash dialog and hit "force quit".
1745 res.set(0);
1746 }
1747 }
1748 ensureBootCompleted();
1749 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 case SHOW_FACTORY_ERROR_MSG: {
1751 Dialog d = new FactoryErrorDialog(
1752 mContext, msg.getData().getCharSequence("msg"));
1753 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001754 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 } break;
1756 case UPDATE_CONFIGURATION_MSG: {
1757 final ContentResolver resolver = mContext.getContentResolver();
1758 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1759 } break;
1760 case GC_BACKGROUND_PROCESSES_MSG: {
1761 synchronized (ActivityManagerService.this) {
1762 performAppGcsIfAppropriateLocked();
1763 }
1764 } break;
1765 case WAIT_FOR_DEBUGGER_MSG: {
1766 synchronized (ActivityManagerService.this) {
1767 ProcessRecord app = (ProcessRecord)msg.obj;
1768 if (msg.arg1 != 0) {
1769 if (!app.waitedForDebugger) {
1770 Dialog d = new AppWaitingForDebuggerDialog(
1771 ActivityManagerService.this,
1772 mContext, app);
1773 app.waitDialog = d;
1774 app.waitedForDebugger = true;
1775 d.show();
1776 }
1777 } else {
1778 if (app.waitDialog != null) {
1779 app.waitDialog.dismiss();
1780 app.waitDialog = null;
1781 }
1782 }
1783 }
1784 } break;
1785 case BROADCAST_INTENT_MSG: {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001786 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 TAG, "Received BROADCAST_INTENT_MSG");
Christopher Tatef46723b2012-01-26 14:19:24 -08001788 BroadcastQueue queue = (BroadcastQueue) msg.obj;
1789 queue.processNextBroadcast(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 } break;
1791 case BROADCAST_TIMEOUT_MSG: {
Christopher Tatef46723b2012-01-26 14:19:24 -08001792 final BroadcastQueue queue = (BroadcastQueue) msg.obj;
Jeff Brown4d94a762010-09-23 11:33:28 -07001793 synchronized (ActivityManagerService.this) {
Christopher Tatef46723b2012-01-26 14:19:24 -08001794 queue.broadcastTimeoutLocked(true);
Jeff Hamiltonacf84742010-05-25 22:10:18 -05001795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001798 if (mDidDexOpt) {
1799 mDidDexOpt = false;
1800 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1801 nmsg.obj = msg.obj;
1802 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
1803 return;
1804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 serviceTimeout((ProcessRecord)msg.obj);
1806 } break;
1807 case UPDATE_TIME_ZONE: {
1808 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001809 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1810 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 if (r.thread != null) {
1812 try {
1813 r.thread.updateTimeZone();
1814 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001815 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 }
1817 }
1818 }
1819 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001820 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001821 case CLEAR_DNS_CACHE: {
1822 synchronized (ActivityManagerService.this) {
1823 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1824 ProcessRecord r = mLruProcesses.get(i);
1825 if (r.thread != null) {
1826 try {
1827 r.thread.clearDnsCache();
1828 } catch (RemoteException ex) {
1829 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1830 }
1831 }
1832 }
1833 }
1834 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001835 case UPDATE_HTTP_PROXY: {
1836 ProxyProperties proxy = (ProxyProperties)msg.obj;
1837 String host = "";
1838 String port = "";
1839 String exclList = "";
1840 if (proxy != null) {
1841 host = proxy.getHost();
1842 port = Integer.toString(proxy.getPort());
1843 exclList = proxy.getExclusionList();
1844 }
1845 synchronized (ActivityManagerService.this) {
1846 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1847 ProcessRecord r = mLruProcesses.get(i);
1848 if (r.thread != null) {
1849 try {
1850 r.thread.setHttpProxy(host, port, exclList);
1851 } catch (RemoteException ex) {
1852 Slog.w(TAG, "Failed to update http proxy for: " +
1853 r.info.processName);
1854 }
1855 }
1856 }
1857 }
1858 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001860 String title = "System UIDs Inconsistent";
1861 String text = "UIDs on the system are inconsistent, you need to wipe your"
1862 + " data partition or your device will be unstable.";
1863 Log.e(TAG, title + ": " + text);
1864 if (mShowDialogs) {
1865 // XXX This is a temporary dialog, no need to localize.
1866 AlertDialog d = new BaseErrorDialog(mContext);
1867 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1868 d.setCancelable(false);
1869 d.setTitle(title);
1870 d.setMessage(text);
1871 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1872 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1873 mUidAlert = d;
1874 d.show();
1875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 } break;
1877 case IM_FEELING_LUCKY_MSG: {
1878 if (mUidAlert != null) {
1879 mUidAlert.dismiss();
1880 mUidAlert = null;
1881 }
1882 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001884 if (mDidDexOpt) {
1885 mDidDexOpt = false;
1886 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1887 nmsg.obj = msg.obj;
1888 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1889 return;
1890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 ProcessRecord app = (ProcessRecord)msg.obj;
1892 synchronized (ActivityManagerService.this) {
1893 processStartTimedOutLocked(app);
1894 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001895 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001896 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1897 synchronized (ActivityManagerService.this) {
1898 doPendingActivityLaunchesLocked(true);
1899 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001900 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001901 case KILL_APPLICATION_MSG: {
1902 synchronized (ActivityManagerService.this) {
1903 int uid = msg.arg1;
1904 boolean restart = (msg.arg2 == 1);
1905 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001906 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001907 }
1908 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001909 case FINALIZE_PENDING_INTENT_MSG: {
1910 ((PendingIntentRecord)msg.obj).completeFinalize();
1911 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001912 case POST_HEAVY_NOTIFICATION_MSG: {
1913 INotificationManager inm = NotificationManager.getService();
1914 if (inm == null) {
1915 return;
1916 }
1917
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001918 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001919 ProcessRecord process = root.app;
1920 if (process == null) {
1921 return;
1922 }
1923
1924 try {
1925 Context context = mContext.createPackageContext(process.info.packageName, 0);
1926 String text = mContext.getString(R.string.heavy_weight_notification,
1927 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1928 Notification notification = new Notification();
1929 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1930 notification.when = 0;
1931 notification.flags = Notification.FLAG_ONGOING_EVENT;
1932 notification.tickerText = text;
1933 notification.defaults = 0; // please be quiet
1934 notification.sound = null;
1935 notification.vibrate = null;
1936 notification.setLatestEventInfo(context, text,
1937 mContext.getText(R.string.heavy_weight_notification_detail),
1938 PendingIntent.getActivity(mContext, 0, root.intent,
1939 PendingIntent.FLAG_CANCEL_CURRENT));
1940
1941 try {
1942 int[] outId = new int[1];
1943 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1944 notification, outId);
1945 } catch (RuntimeException e) {
1946 Slog.w(ActivityManagerService.TAG,
1947 "Error showing notification for heavy-weight app", e);
1948 } catch (RemoteException e) {
1949 }
1950 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001951 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001952 }
1953 } break;
1954 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1955 INotificationManager inm = NotificationManager.getService();
1956 if (inm == null) {
1957 return;
1958 }
1959 try {
1960 inm.cancelNotification("android",
1961 R.string.heavy_weight_notification);
1962 } catch (RuntimeException e) {
1963 Slog.w(ActivityManagerService.TAG,
1964 "Error canceling notification for service", e);
1965 } catch (RemoteException e) {
1966 }
1967 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001968 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1969 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001970 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001971 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001972 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1973 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001974 }
1975 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001976 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1977 synchronized (ActivityManagerService.this) {
1978 ActivityRecord ar = (ActivityRecord)msg.obj;
1979 if (mCompatModeDialog != null) {
1980 if (mCompatModeDialog.mAppInfo.packageName.equals(
1981 ar.info.applicationInfo.packageName)) {
1982 return;
1983 }
1984 mCompatModeDialog.dismiss();
1985 mCompatModeDialog = null;
1986 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001987 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001988 if (mCompatModePackages.getPackageAskCompatModeLocked(
1989 ar.packageName)) {
1990 int mode = mCompatModePackages.computeCompatModeLocked(
1991 ar.info.applicationInfo);
1992 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1993 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1994 mCompatModeDialog = new CompatModeDialog(
1995 ActivityManagerService.this, mContext,
1996 ar.info.applicationInfo);
1997 mCompatModeDialog.show();
1998 }
1999 }
2000 }
2001 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07002002 break;
2003 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002004 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07002005 final int pid = msg.arg1;
2006 final int uid = msg.arg2;
2007 final boolean foregroundActivities = (Boolean) msg.obj;
2008 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002009 break;
2010 }
2011 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07002012 final int pid = msg.arg1;
2013 final int uid = msg.arg2;
2014 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002015 break;
2016 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002017 case REPORT_MEM_USAGE: {
2018 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
2019 if (!isDebuggable) {
2020 return;
2021 }
2022 synchronized (ActivityManagerService.this) {
2023 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002024 if (now < (mLastMemUsageReportTime+5*60*1000)) {
2025 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002026 // avoid spamming.
2027 return;
2028 }
2029 mLastMemUsageReportTime = now;
2030 }
2031 Thread thread = new Thread() {
2032 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002033 StringBuilder dropBuilder = new StringBuilder(1024);
2034 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08002035 StringWriter oomSw = new StringWriter();
2036 PrintWriter oomPw = new PrintWriter(oomSw);
2037 StringWriter catSw = new StringWriter();
2038 PrintWriter catPw = new PrintWriter(catSw);
2039 String[] emptyArgs = new String[] { };
2040 StringBuilder tag = new StringBuilder(128);
2041 StringBuilder stack = new StringBuilder(128);
2042 tag.append("Low on memory -- ");
2043 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
2044 tag, stack);
2045 dropBuilder.append(stack);
2046 dropBuilder.append('\n');
2047 dropBuilder.append('\n');
2048 String oomString = oomSw.toString();
2049 dropBuilder.append(oomString);
2050 dropBuilder.append('\n');
2051 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002052 try {
2053 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
2054 "procrank", });
2055 final InputStreamReader converter = new InputStreamReader(
2056 proc.getInputStream());
2057 BufferedReader in = new BufferedReader(converter);
2058 String line;
2059 while (true) {
2060 line = in.readLine();
2061 if (line == null) {
2062 break;
2063 }
2064 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002065 logBuilder.append(line);
2066 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002067 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002068 dropBuilder.append(line);
2069 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002070 }
2071 converter.close();
2072 } catch (IOException e) {
2073 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002074 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08002075 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002076 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002077 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002078 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002079 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002080 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002081 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002082 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08002083 addErrorToDropBox("lowmem", null, "system_server", null,
2084 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002085 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002086 synchronized (ActivityManagerService.this) {
2087 long now = SystemClock.uptimeMillis();
2088 if (mLastMemUsageReportTime < now) {
2089 mLastMemUsageReportTime = now;
2090 }
2091 }
2092 }
2093 };
2094 thread.start();
2095 break;
2096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 }
2098 }
2099 };
2100
2101 public static void setSystemProcess() {
2102 try {
2103 ActivityManagerService m = mSelf;
2104
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002105 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07002107 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08002108 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 if (MONITOR_CPU_USAGE) {
2110 ServiceManager.addService("cpuinfo", new CpuBinder(m));
2111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 ServiceManager.addService("permission", new PermissionController(m));
2113
2114 ApplicationInfo info =
2115 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07002116 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07002117 mSystemThread.installSystemApplicationInfo(info);
2118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 synchronized (mSelf) {
2120 ProcessRecord app = mSelf.newProcessRecordLocked(
2121 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002122 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08002124 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07002125 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002126 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 synchronized (mSelf.mPidsSelfLocked) {
2128 mSelf.mPidsSelfLocked.put(app.pid, app);
2129 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002130 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 }
2132 } catch (PackageManager.NameNotFoundException e) {
2133 throw new RuntimeException(
2134 "Unable to find android system package", e);
2135 }
2136 }
2137
2138 public void setWindowManager(WindowManagerService wm) {
2139 mWindowManager = wm;
2140 }
2141
2142 public static final Context main(int factoryTest) {
2143 AThread thr = new AThread();
2144 thr.start();
2145
2146 synchronized (thr) {
2147 while (thr.mService == null) {
2148 try {
2149 thr.wait();
2150 } catch (InterruptedException e) {
2151 }
2152 }
2153 }
2154
2155 ActivityManagerService m = thr.mService;
2156 mSelf = m;
2157 ActivityThread at = ActivityThread.systemMain();
2158 mSystemThread = at;
2159 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08002160 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 m.mContext = context;
2162 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002163 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164
2165 m.mBatteryStatsService.publish(context);
2166 m.mUsageStatsService.publish(context);
2167
2168 synchronized (thr) {
2169 thr.mReady = true;
2170 thr.notifyAll();
2171 }
2172
2173 m.startRunning(null, null, null, null);
2174
2175 return context;
2176 }
2177
2178 public static ActivityManagerService self() {
2179 return mSelf;
2180 }
2181
2182 static class AThread extends Thread {
2183 ActivityManagerService mService;
2184 boolean mReady = false;
2185
2186 public AThread() {
2187 super("ActivityManager");
2188 }
2189
2190 public void run() {
2191 Looper.prepare();
2192
2193 android.os.Process.setThreadPriority(
2194 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07002195 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196
2197 ActivityManagerService m = new ActivityManagerService();
2198
2199 synchronized (this) {
2200 mService = m;
2201 notifyAll();
2202 }
2203
2204 synchronized (this) {
2205 while (!mReady) {
2206 try {
2207 wait();
2208 } catch (InterruptedException e) {
2209 }
2210 }
2211 }
2212
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07002213 // For debug builds, log event loop stalls to dropbox for analysis.
2214 if (StrictMode.conditionallyEnableDebugLogging()) {
2215 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
2216 }
2217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 Looper.loop();
2219 }
2220 }
2221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002222 static class MemBinder extends Binder {
2223 ActivityManagerService mActivityManagerService;
2224 MemBinder(ActivityManagerService activityManagerService) {
2225 mActivityManagerService = activityManagerService;
2226 }
2227
2228 @Override
2229 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002230 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2231 != PackageManager.PERMISSION_GRANTED) {
2232 pw.println("Permission Denial: can't dump meminfo from from pid="
2233 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2234 + " without permission " + android.Manifest.permission.DUMP);
2235 return;
2236 }
2237
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08002238 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08002239 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 }
2241 }
2242
Chet Haase9c1e23b2011-03-24 10:51:31 -07002243 static class GraphicsBinder extends Binder {
2244 ActivityManagerService mActivityManagerService;
2245 GraphicsBinder(ActivityManagerService activityManagerService) {
2246 mActivityManagerService = activityManagerService;
2247 }
2248
2249 @Override
2250 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002251 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2252 != PackageManager.PERMISSION_GRANTED) {
2253 pw.println("Permission Denial: can't dump gfxinfo from from pid="
2254 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2255 + " without permission " + android.Manifest.permission.DUMP);
2256 return;
2257 }
2258
Dianne Hackborne17aeb32011-04-07 15:11:57 -07002259 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07002260 }
2261 }
2262
Jeff Brown6754ba22011-12-14 20:20:01 -08002263 static class DbBinder extends Binder {
2264 ActivityManagerService mActivityManagerService;
2265 DbBinder(ActivityManagerService activityManagerService) {
2266 mActivityManagerService = activityManagerService;
2267 }
2268
2269 @Override
2270 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2271 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2272 != PackageManager.PERMISSION_GRANTED) {
2273 pw.println("Permission Denial: can't dump dbinfo from from pid="
2274 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2275 + " without permission " + android.Manifest.permission.DUMP);
2276 return;
2277 }
2278
2279 mActivityManagerService.dumpDbInfo(fd, pw, args);
2280 }
2281 }
2282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 static class CpuBinder extends Binder {
2284 ActivityManagerService mActivityManagerService;
2285 CpuBinder(ActivityManagerService activityManagerService) {
2286 mActivityManagerService = activityManagerService;
2287 }
2288
2289 @Override
2290 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002291 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2292 != PackageManager.PERMISSION_GRANTED) {
2293 pw.println("Permission Denial: can't dump cpuinfo from from pid="
2294 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2295 + " without permission " + android.Manifest.permission.DUMP);
2296 return;
2297 }
2298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002299 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002300 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
2301 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
2302 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 }
2304 }
2305 }
2306
2307 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002308 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07002309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 File dataDir = Environment.getDataDirectory();
2311 File systemDir = new File(dataDir, "system");
2312 systemDir.mkdirs();
2313 mBatteryStatsService = new BatteryStatsService(new File(
2314 systemDir, "batterystats.bin").toString());
2315 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07002316 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07002317 mOnBattery = DEBUG_POWER ? true
2318 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002319 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002321 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07002322 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07002323 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324
Jack Palevichb90d28c2009-07-22 15:35:24 -07002325 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
2326 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
2327
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002328 mConfiguration.setToDefaults();
2329 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08002330 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 mProcessStats.init();
2332
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002333 mCompatModePackages = new CompatModePackages(this, systemDir);
2334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 // Add ourself to the Watchdog monitors.
2336 Watchdog.getInstance().addMonitor(this);
2337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 mProcessStatsThread = new Thread("ProcessStats") {
2339 public void run() {
2340 while (true) {
2341 try {
2342 try {
2343 synchronized(this) {
2344 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002345 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002347 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 // + ", write delay=" + nextWriteDelay);
2349 if (nextWriteDelay < nextCpuDelay) {
2350 nextCpuDelay = nextWriteDelay;
2351 }
2352 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002353 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 this.wait(nextCpuDelay);
2355 }
2356 }
2357 } catch (InterruptedException e) {
2358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 updateCpuStatsNow();
2360 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002361 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 }
2363 }
2364 }
2365 };
2366 mProcessStatsThread.start();
2367 }
2368
2369 @Override
2370 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2371 throws RemoteException {
2372 try {
2373 return super.onTransact(code, data, reply, flags);
2374 } catch (RuntimeException e) {
2375 // The activity manager only throws security exceptions, so let's
2376 // log all others.
2377 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002378 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 }
2380 throw e;
2381 }
2382 }
2383
2384 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002385 final long now = SystemClock.uptimeMillis();
2386 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
2387 return;
2388 }
2389 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
2390 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 mProcessStatsThread.notify();
2392 }
2393 }
2394 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 void updateCpuStatsNow() {
2397 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002398 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399 final long now = SystemClock.uptimeMillis();
2400 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07002401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002403 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
2404 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 haveNewCpuStats = true;
2406 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002407 //Slog.i(TAG, mProcessStats.printCurrentState());
2408 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 // + mProcessStats.getTotalCpuPercent() + "%");
2410
Joe Onorato8a9b2202010-02-26 18:56:32 -08002411 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 if ("true".equals(SystemProperties.get("events.cpu"))) {
2413 int user = mProcessStats.getLastUserTime();
2414 int system = mProcessStats.getLastSystemTime();
2415 int iowait = mProcessStats.getLastIoWaitTime();
2416 int irq = mProcessStats.getLastIrqTime();
2417 int softIrq = mProcessStats.getLastSoftIrqTime();
2418 int idle = mProcessStats.getLastIdleTime();
2419
2420 int total = user + system + iowait + irq + softIrq + idle;
2421 if (total == 0) total = 1;
2422
Doug Zongker2bec3d42009-12-04 12:52:44 -08002423 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 ((user+system+iowait+irq+softIrq) * 100) / total,
2425 (user * 100) / total,
2426 (system * 100) / total,
2427 (iowait * 100) / total,
2428 (irq * 100) / total,
2429 (softIrq * 100) / total);
2430 }
2431 }
2432
Amith Yamasanie43530a2009-08-21 13:11:37 -07002433 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07002434 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002435 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 synchronized(mPidsSelfLocked) {
2437 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002438 if (mOnBattery) {
2439 int perc = bstats.startAddingCpuLocked();
2440 int totalUTime = 0;
2441 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07002442 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07002444 ProcessStats.Stats st = mProcessStats.getStats(i);
2445 if (!st.working) {
2446 continue;
2447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002449 int otherUTime = (st.rel_utime*perc)/100;
2450 int otherSTime = (st.rel_stime*perc)/100;
2451 totalUTime += otherUTime;
2452 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 if (pr != null) {
2454 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002455 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
2456 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07002457 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07002458 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002459 } else {
2460 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07002461 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002462 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002463 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
2464 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07002465 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 }
2468 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002469 bstats.finishAddingCpuLocked(perc, totalUTime,
2470 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 }
2472 }
2473 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
2476 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07002477 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 }
2479 }
2480 }
2481 }
2482
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002483 @Override
2484 public void batteryNeedsCpuUpdate() {
2485 updateCpuStatsNow();
2486 }
2487
2488 @Override
2489 public void batteryPowerChanged(boolean onBattery) {
2490 // When plugging in, update the CPU stats first before changing
2491 // the plug state.
2492 updateCpuStatsNow();
2493 synchronized (this) {
2494 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07002495 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002496 }
2497 }
2498 }
2499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 /**
2501 * Initialize the application bind args. These are passed to each
2502 * process when the bindApplication() IPC is sent to the process. They're
2503 * lazily setup to make sure the services are running when they're asked for.
2504 */
2505 private HashMap<String, IBinder> getCommonServicesLocked() {
2506 if (mAppBindArgs == null) {
2507 mAppBindArgs = new HashMap<String, IBinder>();
2508
2509 // Setup the application init args
2510 mAppBindArgs.put("package", ServiceManager.getService("package"));
2511 mAppBindArgs.put("window", ServiceManager.getService("window"));
2512 mAppBindArgs.put(Context.ALARM_SERVICE,
2513 ServiceManager.getService(Context.ALARM_SERVICE));
2514 }
2515 return mAppBindArgs;
2516 }
2517
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002518 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 if (mFocusedActivity != r) {
2520 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002521 if (r != null) {
2522 mWindowManager.setFocusedApp(r.appToken, true);
2523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 }
2525 }
2526
Dianne Hackborn906497c2010-05-10 15:57:38 -07002527 private final void updateLruProcessInternalLocked(ProcessRecord app,
2528 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002530 int lrui = mLruProcesses.indexOf(app);
2531 if (lrui >= 0) mLruProcesses.remove(lrui);
2532
2533 int i = mLruProcesses.size()-1;
2534 int skipTop = 0;
2535
Dianne Hackborn906497c2010-05-10 15:57:38 -07002536 app.lruSeq = mLruSeq;
2537
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002538 // compute the new weight for this process.
2539 if (updateActivityTime) {
2540 app.lastActivityTime = SystemClock.uptimeMillis();
2541 }
2542 if (app.activities.size() > 0) {
2543 // If this process has activities, we more strongly want to keep
2544 // it around.
2545 app.lruWeight = app.lastActivityTime;
2546 } else if (app.pubProviders.size() > 0) {
2547 // If this process contains content providers, we want to keep
2548 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002549 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_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 } else {
2553 // If this process doesn't have activities, we less strongly
2554 // want to keep it around, and generally want to avoid getting
2555 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002556 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002557 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002558 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002559 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07002560
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002561 while (i >= 0) {
2562 ProcessRecord p = mLruProcesses.get(i);
2563 // If this app shouldn't be in front of the first N background
2564 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002565 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002566 skipTop--;
2567 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07002568 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002569 mLruProcesses.add(i+1, app);
2570 break;
2571 }
2572 i--;
2573 }
2574 if (i < 0) {
2575 mLruProcesses.add(0, app);
2576 }
2577
Dianne Hackborn906497c2010-05-10 15:57:38 -07002578 // If the app is currently using a content provider or service,
2579 // bump those processes as well.
2580 if (app.connections.size() > 0) {
2581 for (ConnectionRecord cr : app.connections) {
2582 if (cr.binding != null && cr.binding.service != null
2583 && cr.binding.service.app != null
2584 && cr.binding.service.app.lruSeq != mLruSeq) {
2585 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
2586 updateActivityTime, i+1);
2587 }
2588 }
2589 }
2590 if (app.conProviders.size() > 0) {
2591 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07002592 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
2593 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07002594 updateActivityTime, i+1);
2595 }
2596 }
2597 }
2598
Joe Onorato8a9b2202010-02-26 18:56:32 -08002599 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 if (oomAdj) {
2601 updateOomAdjLocked();
2602 }
2603 }
2604
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002605 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07002606 boolean oomAdj, boolean updateActivityTime) {
2607 mLruSeq++;
2608 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
2609 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002610
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002611 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 String processName, int uid) {
2613 if (uid == Process.SYSTEM_UID) {
2614 // The system gets to run in any process. If there are multiple
2615 // processes with the same uid, just pick the first (this
2616 // should never happen).
2617 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
2618 processName);
2619 return procs != null ? procs.valueAt(0) : null;
2620 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002621 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 ProcessRecord proc = mProcessNames.get(processName, uid);
2623 return proc;
2624 }
2625
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002626 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002627 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002628 try {
2629 if (pm.performDexOpt(packageName)) {
2630 mDidDexOpt = true;
2631 }
2632 } catch (RemoteException e) {
2633 }
2634 }
2635
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002636 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 int transit = mWindowManager.getPendingAppTransition();
2638 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
2639 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
2640 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
2641 }
2642
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002643 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002645 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
2646 boolean isolated) {
2647 ProcessRecord app;
2648 if (!isolated) {
2649 app = getProcessRecordLocked(processName, info.uid);
2650 } else {
2651 // If this is an isolated process, it can't re-use an existing process.
2652 app = null;
2653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 // We don't have to do anything more if:
2655 // (1) There is an existing application record; and
2656 // (2) The caller doesn't think it is dead, OR there is no thread
2657 // object attached to it so we know it couldn't have crashed; and
2658 // (3) There is a pid assigned to it, so it is either starting or
2659 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002660 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 + " app=" + app + " knownToBeDead=" + knownToBeDead
2662 + " thread=" + (app != null ? app.thread : null)
2663 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01002664 if (app != null && app.pid > 0) {
2665 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002666 // We already have the app running, or are waiting for it to
2667 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002668 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002669 // If this is a new package in the process, add the package to the list
2670 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002671 return app;
2672 } else {
2673 // An application record is attached to a previous process,
2674 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002675 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002676 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 String hostingNameStr = hostingName != null
2681 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002682
2683 if (!isolated) {
2684 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2685 // If we are in the background, then check to see if this process
2686 // is bad. If so, we will just silently fail.
2687 if (mBadProcesses.get(info.processName, info.uid) != null) {
2688 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2689 + "/" + info.processName);
2690 return null;
2691 }
2692 } else {
2693 // When the user is explicitly starting a process, then clear its
2694 // crash count so that we won't make it bad until they see at
2695 // least one crash dialog again, and make the process good again
2696 // if it had been bad.
2697 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002698 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002699 mProcessCrashTimes.remove(info.processName, info.uid);
2700 if (mBadProcesses.get(info.processName, info.uid) != null) {
2701 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
2702 info.processName);
2703 mBadProcesses.remove(info.processName, info.uid);
2704 if (app != null) {
2705 app.bad = false;
2706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 }
2708 }
2709 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002712 app = newProcessRecordLocked(null, info, processName, isolated);
2713 if (app == null) {
2714 Slog.w(TAG, "Failed making new process record for "
2715 + processName + "/" + info.uid + " isolated=" + isolated);
2716 return null;
2717 }
2718 mProcessNames.put(processName, app.uid, app);
2719 if (isolated) {
2720 mIsolatedProcesses.put(app.uid, app);
2721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 } else {
2723 // If this is a new package in the process, add the package to the list
2724 app.addPackage(info.packageName);
2725 }
2726
2727 // If the system is not ready yet, then hold off on starting this
2728 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002729 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002730 && !isAllowedWhileBooting(info)
2731 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 if (!mProcessesOnHold.contains(app)) {
2733 mProcessesOnHold.add(app);
2734 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002735 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 return app;
2737 }
2738
2739 startProcessLocked(app, hostingType, hostingNameStr);
2740 return (app.pid != 0) ? app : null;
2741 }
2742
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002743 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2744 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2745 }
2746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 private final void startProcessLocked(ProcessRecord app,
2748 String hostingType, String hostingNameStr) {
2749 if (app.pid > 0 && app.pid != MY_PID) {
2750 synchronized (mPidsSelfLocked) {
2751 mPidsSelfLocked.remove(app.pid);
2752 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2753 }
2754 app.pid = 0;
2755 }
2756
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002757 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2758 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 mProcessesOnHold.remove(app);
2760
2761 updateCpuStats();
2762
2763 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2764 mProcDeaths[0] = 0;
2765
2766 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002767 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002770 if (!app.isolated) {
2771 try {
2772 gids = mContext.getPackageManager().getPackageGids(
2773 app.info.packageName);
2774 } catch (PackageManager.NameNotFoundException e) {
2775 Slog.w(TAG, "Unable to retrieve gids", e);
2776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 }
2778 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2779 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2780 && mTopComponent != null
2781 && app.processName.equals(mTopComponent.getPackageName())) {
2782 uid = 0;
2783 }
2784 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2785 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2786 uid = 0;
2787 }
2788 }
2789 int debugFlags = 0;
2790 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2791 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002792 // Also turn on CheckJNI for debuggable apps. It's quite
2793 // awkward to turn on otherwise.
2794 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002796 // Run the app in safe mode if its manifest requests so or the
2797 // system is booted in safe mode.
2798 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2799 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002800 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2803 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2804 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002805 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2806 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 if ("1".equals(SystemProperties.get("debug.assert"))) {
2809 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2810 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002811
2812 // Start the process. It will either succeed and return a result containing
2813 // the PID of the new process, or else throw a RuntimeException.
2814 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002815 app.processName, uid, uid, gids, debugFlags,
2816 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2819 synchronized (bs) {
2820 if (bs.isOnBattery()) {
2821 app.batteryStats.incStartsLocked();
2822 }
2823 }
2824
Jeff Brown3f9dd282011-07-08 20:02:19 -07002825 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 app.processName, hostingType,
2827 hostingNameStr != null ? hostingNameStr : "");
2828
2829 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002830 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 }
2832
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002833 StringBuilder buf = mStringBuilder;
2834 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 buf.append("Start proc ");
2836 buf.append(app.processName);
2837 buf.append(" for ");
2838 buf.append(hostingType);
2839 if (hostingNameStr != null) {
2840 buf.append(" ");
2841 buf.append(hostingNameStr);
2842 }
2843 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002844 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 buf.append(" uid=");
2846 buf.append(uid);
2847 buf.append(" gids={");
2848 if (gids != null) {
2849 for (int gi=0; gi<gids.length; gi++) {
2850 if (gi != 0) buf.append(", ");
2851 buf.append(gids[gi]);
2852
2853 }
2854 }
2855 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002856 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002857 app.pid = startResult.pid;
2858 app.usingWrapper = startResult.usingWrapper;
2859 app.removed = false;
2860 synchronized (mPidsSelfLocked) {
2861 this.mPidsSelfLocked.put(startResult.pid, app);
2862 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2863 msg.obj = app;
2864 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2865 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 }
2867 } catch (RuntimeException e) {
2868 // XXX do better error recovery.
2869 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002870 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 }
2872 }
2873
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002874 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 if (resumed) {
2876 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2877 } else {
2878 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2879 }
2880 }
2881
Amith Yamasani742a6712011-05-04 14:49:28 -07002882 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002883 if (mHeadless) {
2884 // Added because none of the other calls to ensureBootCompleted seem to fire
2885 // when running headless.
2886 ensureBootCompleted();
2887 return false;
2888 }
2889
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002890 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2891 && mTopAction == null) {
2892 // We are running in factory test mode, but unable to find
2893 // the factory test app, so just sit around displaying the
2894 // error message and don't try to start anything.
2895 return false;
2896 }
2897 Intent intent = new Intent(
2898 mTopAction,
2899 mTopData != null ? Uri.parse(mTopData) : null);
2900 intent.setComponent(mTopComponent);
2901 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2902 intent.addCategory(Intent.CATEGORY_HOME);
2903 }
2904 ActivityInfo aInfo =
2905 intent.resolveActivityInfo(mContext.getPackageManager(),
2906 STOCK_PM_FLAGS);
2907 if (aInfo != null) {
2908 intent.setComponent(new ComponentName(
2909 aInfo.applicationInfo.packageName, aInfo.name));
2910 // Don't do this if the home app is currently being
2911 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002912 aInfo = new ActivityInfo(aInfo);
2913 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002914 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2915 aInfo.applicationInfo.uid);
2916 if (app == null || app.instrumentationClass == null) {
2917 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002918 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002919 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002920 }
2921 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002922
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002923 return true;
2924 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002925
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002926 /**
2927 * Starts the "new version setup screen" if appropriate.
2928 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002929 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002930 // Only do this once per boot.
2931 if (mCheckedForSetup) {
2932 return;
2933 }
2934
2935 // We will show this screen if the current one is a different
2936 // version than the last one shown, and we are not running in
2937 // low-level factory test mode.
2938 final ContentResolver resolver = mContext.getContentResolver();
2939 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2940 Settings.Secure.getInt(resolver,
2941 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2942 mCheckedForSetup = true;
2943
2944 // See if we should be showing the platform update setup UI.
2945 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2946 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2947 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2948
2949 // We don't allow third party apps to replace this.
2950 ResolveInfo ri = null;
2951 for (int i=0; ris != null && i<ris.size(); i++) {
2952 if ((ris.get(i).activityInfo.applicationInfo.flags
2953 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2954 ri = ris.get(i);
2955 break;
2956 }
2957 }
2958
2959 if (ri != null) {
2960 String vers = ri.activityInfo.metaData != null
2961 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2962 : null;
2963 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2964 vers = ri.activityInfo.applicationInfo.metaData.getString(
2965 Intent.METADATA_SETUP_VERSION);
2966 }
2967 String lastVers = Settings.Secure.getString(
2968 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2969 if (vers != null && !vers.equals(lastVers)) {
2970 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2971 intent.setComponent(new ComponentName(
2972 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002973 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002974 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002975 }
2976 }
2977 }
2978 }
2979
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002980 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002981 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002982 }
2983
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002984 void enforceNotIsolatedCaller(String caller) {
2985 if (UserId.isIsolated(Binder.getCallingUid())) {
2986 throw new SecurityException("Isolated process not allowed to call " + caller);
2987 }
2988 }
2989
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002990 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002991 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002992 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002993 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2994 }
2995 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002996
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002997 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002998 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2999 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07003000 synchronized (this) {
3001 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
3002 }
3003 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003004
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07003005 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003006 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07003007 synchronized (this) {
3008 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
3009 }
3010 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003011
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07003012 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003013 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3014 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07003015 synchronized (this) {
3016 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003017 }
3018 }
3019
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07003020 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003021 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07003022 synchronized (this) {
3023 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
3024 }
3025 }
3026
3027 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003028 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3029 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07003030 synchronized (this) {
3031 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
3032 }
3033 }
3034
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003035 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003036 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003037
3038 final int identHash = System.identityHashCode(r);
3039 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041
Jeff Sharkeya4620792011-05-20 15:29:23 -07003042 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
3043 int i = mProcessObservers.beginBroadcast();
3044 while (i > 0) {
3045 i--;
3046 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3047 if (observer != null) {
3048 try {
3049 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
3050 } catch (RemoteException e) {
3051 }
3052 }
3053 }
3054 mProcessObservers.finishBroadcast();
3055 }
3056
3057 private void dispatchProcessDied(int pid, int uid) {
3058 int i = mProcessObservers.beginBroadcast();
3059 while (i > 0) {
3060 i--;
3061 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3062 if (observer != null) {
3063 try {
3064 observer.onProcessDied(pid, uid);
3065 } catch (RemoteException e) {
3066 }
3067 }
3068 }
3069 mProcessObservers.finishBroadcast();
3070 }
3071
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003072 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003073 final int N = mPendingActivityLaunches.size();
3074 if (N <= 0) {
3075 return;
3076 }
3077 for (int i=0; i<N; i++) {
3078 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003079 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003080 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
3081 doResume && i == (N-1));
3082 }
3083 mPendingActivityLaunches.clear();
3084 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003085
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003086 public final int startActivity(IApplicationThread caller,
3087 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3088 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003089 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
3090 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003091 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07003092 int userId = 0;
3093 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
3094 // Requesting home, set the identity to the current user
3095 // HACK!
3096 userId = mCurrentUserId;
3097 } else {
3098 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
3099 // the current user's userId
3100 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
3101 userId = 0;
3102 } else {
3103 userId = Binder.getOrigCallingUser();
3104 }
3105 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003106 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -07003107 grantedUriPermissions, grantedMode, resultTo, resultWho, requestCode, onlyIfNeeded,
3108 debug, profileFile, profileFd, autoStopProfiler, null, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003109 }
3110
3111 public final WaitResult startActivityAndWait(IApplicationThread caller,
3112 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3113 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003114 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
3115 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003116 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003117 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07003118 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003119 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003120 grantedUriPermissions, grantedMode, resultTo, resultWho,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003121 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
Amith Yamasani742a6712011-05-04 14:49:28 -07003122 res, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003123 return res;
3124 }
3125
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003126 public final int startActivityWithConfig(IApplicationThread caller,
3127 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3128 int grantedMode, IBinder resultTo,
3129 String resultWho, int requestCode, boolean onlyIfNeeded,
3130 boolean debug, Configuration config) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003131 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07003132 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003133 grantedUriPermissions, grantedMode, resultTo, resultWho,
Amith Yamasani742a6712011-05-04 14:49:28 -07003134 requestCode, onlyIfNeeded,
3135 debug, null, null, false, null, config, Binder.getOrigCallingUser());
3136 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003137 }
3138
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003139 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003140 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003141 IBinder resultTo, String resultWho, int requestCode,
3142 int flagsMask, int flagsValues) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003143 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003144 // Refuse possible leaked file descriptors
3145 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
3146 throw new IllegalArgumentException("File descriptors passed in Intent");
3147 }
3148
3149 IIntentSender sender = intent.getTarget();
3150 if (!(sender instanceof PendingIntentRecord)) {
3151 throw new IllegalArgumentException("Bad PendingIntent object");
3152 }
3153
3154 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003155
3156 synchronized (this) {
3157 // If this is coming from the currently resumed activity, it is
3158 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003159 if (mMainStack.mResumedActivity != null
3160 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003161 Binder.getCallingUid()) {
3162 mAppSwitchesAllowedTime = 0;
3163 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003164 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003165 int ret = pir.sendInner(0, fillInIntent, resolvedType, null,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003166 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
Amith Yamasani742a6712011-05-04 14:49:28 -07003167 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003168 }
3169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 public boolean startNextMatchingActivity(IBinder callingActivity,
3171 Intent intent) {
3172 // Refuse possible leaked file descriptors
3173 if (intent != null && intent.hasFileDescriptors() == true) {
3174 throw new IllegalArgumentException("File descriptors passed in Intent");
3175 }
3176
3177 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003178 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
3179 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 return false;
3181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 if (r.app == null || r.app.thread == null) {
3183 // The caller is not running... d'oh!
3184 return false;
3185 }
3186 intent = new Intent(intent);
3187 // The caller is not allowed to change the data.
3188 intent.setDataAndType(r.intent.getData(), r.intent.getType());
3189 // And we are resetting to find the next component...
3190 intent.setComponent(null);
3191
3192 ActivityInfo aInfo = null;
3193 try {
3194 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003195 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07003197 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198
3199 // Look for the original activity in the list...
3200 final int N = resolves != null ? resolves.size() : 0;
3201 for (int i=0; i<N; i++) {
3202 ResolveInfo rInfo = resolves.get(i);
3203 if (rInfo.activityInfo.packageName.equals(r.packageName)
3204 && rInfo.activityInfo.name.equals(r.info.name)) {
3205 // We found the current one... the next matching is
3206 // after it.
3207 i++;
3208 if (i<N) {
3209 aInfo = resolves.get(i).activityInfo;
3210 }
3211 break;
3212 }
3213 }
3214 } catch (RemoteException e) {
3215 }
3216
3217 if (aInfo == null) {
3218 // Nobody who is next!
3219 return false;
3220 }
3221
3222 intent.setComponent(new ComponentName(
3223 aInfo.applicationInfo.packageName, aInfo.name));
3224 intent.setFlags(intent.getFlags()&~(
3225 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
3226 Intent.FLAG_ACTIVITY_CLEAR_TOP|
3227 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
3228 Intent.FLAG_ACTIVITY_NEW_TASK));
3229
3230 // Okay now we need to start the new activity, replacing the
3231 // currently running activity. This is a little tricky because
3232 // we want to start the new one as if the current one is finished,
3233 // but not finish the current one first so that there is no flicker.
3234 // And thus...
3235 final boolean wasFinishing = r.finishing;
3236 r.finishing = true;
3237
3238 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003239 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 final String resultWho = r.resultWho;
3241 final int requestCode = r.requestCode;
3242 r.resultTo = null;
3243 if (resultTo != null) {
3244 resultTo.removeResultsLocked(r, resultWho, requestCode);
3245 }
3246
3247 final long origId = Binder.clearCallingIdentity();
3248 // XXX we are not dealing with propagating grantedUriPermissions...
3249 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003250 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackbornbe707852011-11-11 14:32:10 -08003251 r.resolvedType, null, 0, aInfo,
3252 resultTo != null ? resultTo.appToken : null, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003253 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 Binder.restoreCallingIdentity(origId);
3255
3256 r.finishing = wasFinishing;
3257 if (res != START_SUCCESS) {
3258 return false;
3259 }
3260 return true;
3261 }
3262 }
3263
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003264 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 Intent intent, String resolvedType, IBinder resultTo,
3266 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003267
3268 // This is so super not safe, that only the system (or okay root)
3269 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07003270 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003271 final int callingUid = Binder.getCallingUid();
3272 if (callingUid != 0 && callingUid != Process.myUid()) {
3273 throw new SecurityException(
3274 "startActivityInPackage only available to the system");
3275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276
Amith Yamasani742a6712011-05-04 14:49:28 -07003277 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003278 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false,
Amith Yamasani742a6712011-05-04 14:49:28 -07003279 null, null, false, null, null, userId);
3280 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003281 }
3282
3283 public final int startActivities(IApplicationThread caller,
3284 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003285 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07003286 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
3287 Binder.getOrigCallingUser());
3288 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003289 }
3290
3291 public final int startActivitiesInPackage(int uid,
3292 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
3293
3294 // This is so super not safe, that only the system (or okay root)
3295 // can do it.
3296 final int callingUid = Binder.getCallingUid();
3297 if (callingUid != 0 && callingUid != Process.myUid()) {
3298 throw new SecurityException(
3299 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003301 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
3302 UserId.getUserId(uid));
3303 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 }
3305
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003306 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08003308 // Quick case: check if the top-most recent task is the same.
3309 if (N > 0 && mRecentTasks.get(0) == task) {
3310 return;
3311 }
3312 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 for (int i=0; i<N; i++) {
3314 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07003315 if (task.userId == tr.userId
3316 && ((task.affinity != null && task.affinity.equals(tr.affinity))
3317 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 mRecentTasks.remove(i);
3319 i--;
3320 N--;
3321 if (task.intent == null) {
3322 // If the new recent task we are adding is not fully
3323 // specified, then replace it with the existing recent task.
3324 task = tr;
3325 }
3326 }
3327 }
3328 if (N >= MAX_RECENT_TASKS) {
3329 mRecentTasks.remove(N-1);
3330 }
3331 mRecentTasks.add(0, task);
3332 }
3333
3334 public void setRequestedOrientation(IBinder token,
3335 int requestedOrientation) {
3336 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003337 ActivityRecord r = mMainStack.isInStackLocked(token);
3338 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 return;
3340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08003342 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07003344 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08003345 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 if (config != null) {
3347 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08003348 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003349 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 }
3351 }
3352 Binder.restoreCallingIdentity(origId);
3353 }
3354 }
3355
3356 public int getRequestedOrientation(IBinder token) {
3357 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003358 ActivityRecord r = mMainStack.isInStackLocked(token);
3359 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3361 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003362 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 }
3364 }
3365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 /**
3367 * This is the internal entry point for handling Activity.finish().
3368 *
3369 * @param token The Binder token referencing the Activity we want to finish.
3370 * @param resultCode Result code, if any, from this Activity.
3371 * @param resultData Result data (Intent), if any, from this Activity.
3372 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11003373 * @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 -08003374 */
3375 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
3376 // Refuse possible leaked file descriptors
3377 if (resultData != null && resultData.hasFileDescriptors() == true) {
3378 throw new IllegalArgumentException("File descriptors passed in Intent");
3379 }
3380
3381 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003382 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003384 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 if (next != null) {
3386 // ask watcher if this is allowed
3387 boolean resumeOK = true;
3388 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003389 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003391 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 }
3393
3394 if (!resumeOK) {
3395 return false;
3396 }
3397 }
3398 }
3399 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003400 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 resultData, "app-request");
3402 Binder.restoreCallingIdentity(origId);
3403 return res;
3404 }
3405 }
3406
Dianne Hackborn860755f2010-06-03 18:47:52 -07003407 public final void finishHeavyWeightApp() {
3408 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3409 != PackageManager.PERMISSION_GRANTED) {
3410 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
3411 + Binder.getCallingPid()
3412 + ", uid=" + Binder.getCallingUid()
3413 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3414 Slog.w(TAG, msg);
3415 throw new SecurityException(msg);
3416 }
3417
3418 synchronized(this) {
3419 if (mHeavyWeightProcess == null) {
3420 return;
3421 }
3422
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003423 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07003424 mHeavyWeightProcess.activities);
3425 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003426 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003427 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003428 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003429 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003430 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07003431 null, "finish-heavy");
3432 }
3433 }
3434 }
3435
3436 mHeavyWeightProcess = null;
3437 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3438 }
3439 }
3440
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003441 public void crashApplication(int uid, int initialPid, String packageName,
3442 String message) {
3443 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3444 != PackageManager.PERMISSION_GRANTED) {
3445 String msg = "Permission Denial: crashApplication() from pid="
3446 + Binder.getCallingPid()
3447 + ", uid=" + Binder.getCallingUid()
3448 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3449 Slog.w(TAG, msg);
3450 throw new SecurityException(msg);
3451 }
3452
3453 synchronized(this) {
3454 ProcessRecord proc = null;
3455
3456 // Figure out which process to kill. We don't trust that initialPid
3457 // still has any relation to current pids, so must scan through the
3458 // list.
3459 synchronized (mPidsSelfLocked) {
3460 for (int i=0; i<mPidsSelfLocked.size(); i++) {
3461 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003462 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003463 continue;
3464 }
3465 if (p.pid == initialPid) {
3466 proc = p;
3467 break;
3468 }
3469 for (String str : p.pkgList) {
3470 if (str.equals(packageName)) {
3471 proc = p;
3472 }
3473 }
3474 }
3475 }
3476
3477 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07003478 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003479 + " initialPid=" + initialPid
3480 + " packageName=" + packageName);
3481 return;
3482 }
3483
3484 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07003485 if (proc.pid == Process.myPid()) {
3486 Log.w(TAG, "crashApplication: trying to crash self!");
3487 return;
3488 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003489 long ident = Binder.clearCallingIdentity();
3490 try {
3491 proc.thread.scheduleCrash(message);
3492 } catch (RemoteException e) {
3493 }
3494 Binder.restoreCallingIdentity(ident);
3495 }
3496 }
3497 }
3498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 public final void finishSubActivity(IBinder token, String resultWho,
3500 int requestCode) {
3501 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003502 ActivityRecord self = mMainStack.isInStackLocked(token);
3503 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 return;
3505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506
3507 final long origId = Binder.clearCallingIdentity();
3508
3509 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003510 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3511 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 if (r.resultTo == self && r.requestCode == requestCode) {
3513 if ((r.resultWho == null && resultWho == null) ||
3514 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003515 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 Activity.RESULT_CANCELED, null, "request-sub");
3517 }
3518 }
3519 }
3520
3521 Binder.restoreCallingIdentity(origId);
3522 }
3523 }
3524
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003525 public boolean willActivityBeVisible(IBinder token) {
3526 synchronized(this) {
3527 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003528 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3529 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003530 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003531 return true;
3532 }
3533 if (r.fullscreen && !r.finishing) {
3534 return false;
3535 }
3536 }
3537 return true;
3538 }
3539 }
3540
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003541 public void overridePendingTransition(IBinder token, String packageName,
3542 int enterAnim, int exitAnim) {
3543 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003544 ActivityRecord self = mMainStack.isInStackLocked(token);
3545 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003546 return;
3547 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003548
3549 final long origId = Binder.clearCallingIdentity();
3550
3551 if (self.state == ActivityState.RESUMED
3552 || self.state == ActivityState.PAUSING) {
3553 mWindowManager.overridePendingAppTransition(packageName,
3554 enterAnim, exitAnim);
3555 }
3556
3557 Binder.restoreCallingIdentity(origId);
3558 }
3559 }
3560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 * Main function for removing an existing process from the activity manager
3563 * as a result of that process going away. Clears out all connections
3564 * to the process.
3565 */
3566 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003567 boolean restarting, boolean allowRestart) {
3568 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003570 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 }
3572
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003573 if (mProfileProc == app) {
3574 clearProfilerLocked();
3575 }
3576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 // Just in case...
Dianne Hackborncbb722e2012-02-07 18:33:49 -08003578 mMainStack.appDiedLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579
3580 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003581 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582
3583 boolean atTop = true;
3584 boolean hasVisibleActivities = false;
3585
3586 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003587 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003588 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003589 TAG, "Removing app " + app + " from history with " + i + " entries");
3590 while (i > 0) {
3591 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003592 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003593 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3595 if (r.app == app) {
3596 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003597 if (ActivityStack.DEBUG_ADD_REMOVE) {
3598 RuntimeException here = new RuntimeException("here");
3599 here.fillInStackTrace();
3600 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
3601 + ": haveState=" + r.haveState
3602 + " stateNotNeeded=" + r.stateNotNeeded
3603 + " finishing=" + r.finishing
3604 + " state=" + r.state, here);
3605 }
3606 if (!r.finishing) {
3607 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08003608 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3609 System.identityHashCode(r),
3610 r.task.taskId, r.shortComponentName,
3611 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003612 }
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003613 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003614 mMainStack.mHistory.remove(i);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003615 r.takeFromHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08003616 mWindowManager.removeAppToken(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003618 mMainStack.validateAppTokensLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003619 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003620 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621
3622 } else {
3623 // We have the current state for this activity, so
3624 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003625 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 TAG, "Keeping entry, setting app to null");
3627 if (r.visible) {
3628 hasVisibleActivities = true;
3629 }
3630 r.app = null;
3631 r.nowVisible = false;
3632 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003633 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
3634 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 r.icicle = null;
3636 }
3637 }
3638
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003639 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 }
3641 atTop = false;
3642 }
3643
3644 app.activities.clear();
3645
3646 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003647 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 + " running instrumentation " + app.instrumentationClass);
3649 Bundle info = new Bundle();
3650 info.putString("shortMsg", "Process crashed.");
3651 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3652 }
3653
3654 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003655 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 // If there was nothing to resume, and we are not already
3657 // restarting this process, but there is a visible activity that
3658 // is hosted by the process... then make sure all visible
3659 // activities are running, taking care of restarting this
3660 // process.
3661 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003662 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 }
3664 }
3665 }
3666 }
3667
3668 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3669 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003671 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3672 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3674 return i;
3675 }
3676 }
3677 return -1;
3678 }
3679
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003680 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 IApplicationThread thread) {
3682 if (thread == null) {
3683 return null;
3684 }
3685
3686 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003687 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 }
3689
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003690 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003691 IApplicationThread thread) {
3692
3693 mProcDeaths[0]++;
3694
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003695 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3696 synchronized (stats) {
3697 stats.noteProcessDiedLocked(app.info.uid, pid);
3698 }
3699
Magnus Edlund7bb25812010-02-24 15:45:06 +01003700 // Clean up already done if the process has been re-started.
3701 if (app.pid == pid && app.thread != null &&
3702 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003703 if (!app.killedBackground) {
3704 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3705 + ") has died.");
3706 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08003707 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003708 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 TAG, "Dying app: " + app + ", pid: " + pid
3710 + ", thread: " + thread.asBinder());
3711 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003712 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003713
3714 if (doLowMem) {
3715 // If there are no longer any background processes running,
3716 // and the app that died was not running instrumentation,
3717 // then tell everyone we are now low on memory.
3718 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003719 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3720 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003721 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 haveBg = true;
3723 break;
3724 }
3725 }
3726
3727 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003728 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003729 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003730 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3731 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003732 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003733 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3734 // The low memory report is overriding any current
3735 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003736 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003737 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003738 rec.lastRequestedGc = 0;
3739 } else {
3740 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003742 rec.reportLowMemory = true;
3743 rec.lastLowMemory = now;
3744 mProcessesToGc.remove(rec);
3745 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 }
3747 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003748 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003749 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 }
3751 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003752 } else if (app.pid != pid) {
3753 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003754 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003755 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003756 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003757 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003758 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 + thread.asBinder());
3760 }
3761 }
3762
Dan Egnor42471dd2010-01-07 17:25:22 -08003763 /**
3764 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003765 * @param clearTraces causes the dump file to be erased prior to the new
3766 * traces being written, if true; when false, the new traces will be
3767 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003768 * @param firstPids of dalvik VM processes to dump stack traces for first
3769 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08003770 * @return file containing stack traces, or null if no dump file is configured
3771 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003772 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
3773 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003774 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3775 if (tracesPath == null || tracesPath.length() == 0) {
3776 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003778
3779 File tracesFile = new File(tracesPath);
3780 try {
3781 File tracesDir = tracesFile.getParentFile();
3782 if (!tracesDir.exists()) tracesFile.mkdirs();
3783 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3784
Christopher Tate6ee412d2010-05-28 12:01:56 -07003785 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003786 tracesFile.createNewFile();
3787 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3788 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003789 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003790 return null;
3791 }
3792
3793 // Use a FileObserver to detect when traces finish writing.
3794 // The order of traces is considered important to maintain for legibility.
3795 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3796 public synchronized void onEvent(int event, String path) { notify(); }
3797 };
3798
3799 try {
3800 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003801
3802 // First collect all of the stacks of the most important pids.
3803 try {
3804 int num = firstPids.size();
3805 for (int i = 0; i < num; i++) {
3806 synchronized (observer) {
3807 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3808 observer.wait(200); // Wait for write-close, give up after 200msec
3809 }
3810 }
3811 } catch (InterruptedException e) {
3812 Log.wtf(TAG, e);
3813 }
3814
3815 // Next measure CPU usage.
3816 if (processStats != null) {
3817 processStats.init();
3818 System.gc();
3819 processStats.update();
3820 try {
3821 synchronized (processStats) {
3822 processStats.wait(500); // measure over 1/2 second.
3823 }
3824 } catch (InterruptedException e) {
3825 }
3826 processStats.update();
3827
3828 // We'll take the stack crawls of just the top apps using CPU.
3829 final int N = processStats.countWorkingStats();
3830 int numProcs = 0;
3831 for (int i=0; i<N && numProcs<5; i++) {
3832 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3833 if (lastPids.indexOfKey(stats.pid) >= 0) {
3834 numProcs++;
3835 try {
3836 synchronized (observer) {
3837 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3838 observer.wait(200); // Wait for write-close, give up after 200msec
3839 }
3840 } catch (InterruptedException e) {
3841 Log.wtf(TAG, e);
3842 }
3843
3844 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003845 }
3846 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003847
3848 return tracesFile;
3849
Dan Egnor42471dd2010-01-07 17:25:22 -08003850 } finally {
3851 observer.stopWatching();
3852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 }
3854
Jeff Brown4d94a762010-09-23 11:33:28 -07003855 private final class AppNotResponding implements Runnable {
3856 private final ProcessRecord mApp;
3857 private final String mAnnotation;
3858
3859 public AppNotResponding(ProcessRecord app, String annotation) {
3860 mApp = app;
3861 mAnnotation = annotation;
3862 }
3863
3864 @Override
3865 public void run() {
3866 appNotResponding(mApp, null, null, mAnnotation);
3867 }
3868 }
3869
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003870 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3871 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003872 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3873 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3874
Dianne Hackborn287952c2010-09-22 22:34:31 -07003875 if (mController != null) {
3876 try {
3877 // 0 == continue, -1 = kill process immediately
3878 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3879 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3880 } catch (RemoteException e) {
3881 mController = null;
3882 }
3883 }
3884
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003885 long anrTime = SystemClock.uptimeMillis();
3886 if (MONITOR_CPU_USAGE) {
3887 updateCpuStatsNow();
3888 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003889
3890 synchronized (this) {
3891 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3892 if (mShuttingDown) {
3893 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3894 return;
3895 } else if (app.notResponding) {
3896 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3897 return;
3898 } else if (app.crashing) {
3899 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3900 return;
3901 }
3902
3903 // In case we come through here for the same app before completing
3904 // this one, mark as anring now so we will bail out.
3905 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003906
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003907 // Log the ANR to the event log.
3908 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3909 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003910
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003911 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003912 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003913
3914 int parentPid = app.pid;
3915 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003916 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003917
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003918 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003919
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003920 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3921 ProcessRecord r = mLruProcesses.get(i);
3922 if (r != null && r.thread != null) {
3923 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003924 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3925 if (r.persistent) {
3926 firstPids.add(pid);
3927 } else {
3928 lastPids.put(pid, Boolean.TRUE);
3929 }
3930 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 }
3933 }
3934
Dan Egnor42471dd2010-01-07 17:25:22 -08003935 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003936 StringBuilder info = mStringBuilder;
3937 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003938 info.append("ANR in ").append(app.processName);
3939 if (activity != null && activity.shortComponentName != null) {
3940 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003941 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003942 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003944 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003946 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003947 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949
Dianne Hackborn287952c2010-09-22 22:34:31 -07003950 final ProcessStats processStats = new ProcessStats(true);
3951
3952 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3953
Dan Egnor42471dd2010-01-07 17:25:22 -08003954 String cpuInfo = null;
3955 if (MONITOR_CPU_USAGE) {
3956 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003957 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003958 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003959 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003960 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003961 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 }
3963
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003964 info.append(processStats.printCurrentState(anrTime));
3965
Joe Onorato8a9b2202010-02-26 18:56:32 -08003966 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003967 if (tracesFile == null) {
3968 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3969 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3970 }
3971
Jeff Sharkeya353d262011-10-28 11:12:06 -07003972 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3973 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003974
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003975 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003977 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3978 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003980 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3981 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 }
3983 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003984 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 }
3986 }
3987
Dan Egnor42471dd2010-01-07 17:25:22 -08003988 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3989 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3990 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003991
3992 synchronized (this) {
3993 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003994 Slog.w(TAG, "Killing " + app + ": background ANR");
3995 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3996 app.processName, app.setAdj, "background ANR");
3997 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003998 return;
3999 }
4000
4001 // Set the app's notResponding state, and look up the errorReportReceiver
4002 makeAppNotRespondingLocked(app,
4003 activity != null ? activity.shortComponentName : null,
4004 annotation != null ? "ANR " + annotation : "ANR",
4005 info.toString());
4006
4007 // Bring up the infamous App Not Responding dialog
4008 Message msg = Message.obtain();
4009 HashMap map = new HashMap();
4010 msg.what = SHOW_NOT_RESPONDING_MSG;
4011 msg.obj = map;
4012 map.put("app", app);
4013 if (activity != null) {
4014 map.put("activity", activity);
4015 }
4016
4017 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08004018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 }
4020
Dianne Hackborn0dad3642010-09-09 21:25:35 -07004021 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
4022 if (!mLaunchWarningShown) {
4023 mLaunchWarningShown = true;
4024 mHandler.post(new Runnable() {
4025 @Override
4026 public void run() {
4027 synchronized (ActivityManagerService.this) {
4028 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
4029 d.show();
4030 mHandler.postDelayed(new Runnable() {
4031 @Override
4032 public void run() {
4033 synchronized (ActivityManagerService.this) {
4034 d.dismiss();
4035 mLaunchWarningShown = false;
4036 }
4037 }
4038 }, 4000);
4039 }
4040 }
4041 });
4042 }
4043 }
4044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07004046 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004047 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 int uid = Binder.getCallingUid();
4049 int pid = Binder.getCallingPid();
4050 long callingId = Binder.clearCallingIdentity();
4051 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004052 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 int pkgUid = -1;
4054 synchronized(this) {
4055 try {
4056 pkgUid = pm.getPackageUid(packageName);
4057 } catch (RemoteException e) {
4058 }
4059 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004060 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 return false;
4062 }
4063 if (uid == pkgUid || checkComponentPermission(
4064 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004065 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08004067 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 } else {
4069 throw new SecurityException(pid+" does not have permission:"+
4070 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
4071 "for process:"+packageName);
4072 }
4073 }
4074
4075 try {
4076 //clear application user data
4077 pm.clearApplicationUserData(packageName, observer);
4078 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
4079 Uri.fromParts("package", packageName, null));
4080 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004081 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07004082 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 } catch (RemoteException e) {
4084 }
4085 } finally {
4086 Binder.restoreCallingIdentity(callingId);
4087 }
4088 return true;
4089 }
4090
Dianne Hackborn03abb812010-01-04 18:43:19 -08004091 public void killBackgroundProcesses(final String packageName) {
4092 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4093 != PackageManager.PERMISSION_GRANTED &&
4094 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
4095 != PackageManager.PERMISSION_GRANTED) {
4096 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 + Binder.getCallingPid()
4098 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08004099 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004100 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 throw new SecurityException(msg);
4102 }
4103
4104 long callingId = Binder.clearCallingIdentity();
4105 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004106 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 int pkgUid = -1;
4108 synchronized(this) {
4109 try {
4110 pkgUid = pm.getPackageUid(packageName);
4111 } catch (RemoteException e) {
4112 }
4113 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004114 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 return;
4116 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004117 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004118 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
4119 }
4120 } finally {
4121 Binder.restoreCallingIdentity(callingId);
4122 }
4123 }
4124
4125 public void killAllBackgroundProcesses() {
4126 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4127 != PackageManager.PERMISSION_GRANTED) {
4128 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
4129 + Binder.getCallingPid()
4130 + ", uid=" + Binder.getCallingUid()
4131 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4132 Slog.w(TAG, msg);
4133 throw new SecurityException(msg);
4134 }
4135
4136 long callingId = Binder.clearCallingIdentity();
4137 try {
4138 synchronized(this) {
4139 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
4140 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
4141 final int NA = apps.size();
4142 for (int ia=0; ia<NA; ia++) {
4143 ProcessRecord app = apps.valueAt(ia);
4144 if (app.persistent) {
4145 // we don't kill persistent processes
4146 continue;
4147 }
4148 if (app.removed) {
4149 procs.add(app);
4150 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
4151 app.removed = true;
4152 procs.add(app);
4153 }
4154 }
4155 }
4156
4157 int N = procs.size();
4158 for (int i=0; i<N; i++) {
4159 removeProcessLocked(procs.get(i), false, true, "kill all background");
4160 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004161 }
4162 } finally {
4163 Binder.restoreCallingIdentity(callingId);
4164 }
4165 }
4166
4167 public void forceStopPackage(final String packageName) {
4168 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4169 != PackageManager.PERMISSION_GRANTED) {
4170 String msg = "Permission Denial: forceStopPackage() from pid="
4171 + Binder.getCallingPid()
4172 + ", uid=" + Binder.getCallingUid()
4173 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004174 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004175 throw new SecurityException(msg);
4176 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004177 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08004178 long callingId = Binder.clearCallingIdentity();
4179 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004180 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08004181 int pkgUid = -1;
4182 synchronized(this) {
4183 try {
4184 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004185 // Convert the uid to the one for the calling user
4186 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004187 } catch (RemoteException e) {
4188 }
4189 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004190 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004191 return;
4192 }
4193 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08004194 try {
4195 pm.setPackageStoppedState(packageName, true);
4196 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08004197 } catch (IllegalArgumentException e) {
4198 Slog.w(TAG, "Failed trying to unstop package "
4199 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08004200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 }
4202 } finally {
4203 Binder.restoreCallingIdentity(callingId);
4204 }
4205 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004206
4207 /*
4208 * The pkg name and uid have to be specified.
4209 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
4210 */
4211 public void killApplicationWithUid(String pkg, int uid) {
4212 if (pkg == null) {
4213 return;
4214 }
4215 // Make sure the uid is valid.
4216 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004217 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004218 return;
4219 }
4220 int callerUid = Binder.getCallingUid();
4221 // Only the system server can kill an application
4222 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07004223 // Post an aysnc message to kill the application
4224 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
4225 msg.arg1 = uid;
4226 msg.arg2 = 0;
4227 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07004228 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004229 } else {
4230 throw new SecurityException(callerUid + " cannot kill pkg: " +
4231 pkg);
4232 }
4233 }
4234
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004235 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004236 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004237 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004238 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004239 if (reason != null) {
4240 intent.putExtra("reason", reason);
4241 }
4242
4243 final int uid = Binder.getCallingUid();
4244 final long origId = Binder.clearCallingIdentity();
4245 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07004246 mWindowManager.closeSystemDialogs(reason);
4247
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08004248 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004249 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07004250 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004251 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07004252 Activity.RESULT_CANCELED, null, "close-sys");
4253 }
4254 }
4255
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004256 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07004257 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004258 }
4259 Binder.restoreCallingIdentity(origId);
4260 }
4261
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004262 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004263 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004264 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004265 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
4266 for (int i=pids.length-1; i>=0; i--) {
4267 infos[i] = new Debug.MemoryInfo();
4268 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004269 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004270 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004271 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07004272
Dianne Hackbornb437e092011-08-05 17:50:29 -07004273 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004274 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07004275 long[] pss = new long[pids.length];
4276 for (int i=pids.length-1; i>=0; i--) {
4277 pss[i] = Debug.getPss(pids[i]);
4278 }
4279 return pss;
4280 }
4281
Christopher Tate5e1ab332009-09-01 20:32:49 -07004282 public void killApplicationProcess(String processName, int uid) {
4283 if (processName == null) {
4284 return;
4285 }
4286
4287 int callerUid = Binder.getCallingUid();
4288 // Only the system server can kill an application
4289 if (callerUid == Process.SYSTEM_UID) {
4290 synchronized (this) {
4291 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07004292 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07004293 try {
4294 app.thread.scheduleSuicide();
4295 } catch (RemoteException e) {
4296 // If the other end already died, then our work here is done.
4297 }
4298 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004299 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07004300 + processName + " / " + uid);
4301 }
4302 }
4303 } else {
4304 throw new SecurityException(callerUid + " cannot kill app process: " +
4305 processName);
4306 }
4307 }
4308
Dianne Hackborn03abb812010-01-04 18:43:19 -08004309 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004310 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
4312 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004313 if (!mProcessesReady) {
4314 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 intent.putExtra(Intent.EXTRA_UID, uid);
4317 broadcastIntentLocked(null, null, intent,
4318 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07004319 false, false,
4320 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 }
4322
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004323 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07004324 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004325 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08004326 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327
Dianne Hackborn03abb812010-01-04 18:43:19 -08004328 // Remove all processes this package may have touched: all with the
4329 // same UID (except for the system or root user), and all whose name
4330 // matches the package name.
4331 final String procNamePrefix = packageName + ":";
4332 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
4333 final int NA = apps.size();
4334 for (int ia=0; ia<NA; ia++) {
4335 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07004336 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07004337 // we don't kill persistent processes
4338 continue;
4339 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004340 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004341 if (doit) {
4342 procs.add(app);
4343 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004344 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
4345 || app.processName.equals(packageName)
4346 || app.processName.startsWith(procNamePrefix)) {
4347 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004348 if (!doit) {
4349 return true;
4350 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004351 app.removed = true;
4352 procs.add(app);
4353 }
4354 }
4355 }
4356 }
4357
4358 int N = procs.size();
4359 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004360 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004361 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004362 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08004363 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004364
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004365 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07004366 boolean callerWillRestart, boolean purgeCache, boolean doit,
4367 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004368 int i;
4369 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 if (uid < 0) {
4372 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004373 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 } catch (RemoteException e) {
4375 }
4376 }
4377
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004378 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004379 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004380
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004381 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
4382 while (badApps.hasNext()) {
4383 SparseArray<Long> ba = badApps.next();
4384 if (ba.get(uid) != null) {
4385 badApps.remove();
4386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 }
4388 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004389
4390 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004391 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004393 TaskRecord lastTask = null;
4394 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004395 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004396 final boolean samePackage = r.packageName.equals(name);
4397 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07004398 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004399 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07004400 if (r.finishing) {
4401 // If this activity is just finishing, then it is not
4402 // interesting as far as something to stop.
4403 continue;
4404 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004405 return true;
4406 }
4407 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004408 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004409 if (samePackage) {
4410 if (r.app != null) {
4411 r.app.removed = true;
4412 }
4413 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004415 lastTask = r.task;
4416 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
4417 null, "force-stop")) {
4418 i--;
4419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420 }
4421 }
4422
4423 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07004424 int userId = UserId.getUserId(uid);
4425 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07004426 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07004427 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004428 if (!doit) {
4429 return true;
4430 }
4431 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004432 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004433 if (service.app != null) {
4434 service.app.removed = true;
4435 }
4436 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004437 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004438 services.add(service);
4439 }
4440 }
4441
4442 N = services.size();
4443 for (i=0; i<N; i++) {
4444 bringDownServiceLocked(services.get(i), true);
4445 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004446
4447 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
4448 for (ContentProviderRecord provider : mProvidersByClass.values()) {
4449 if (provider.info.packageName.equals(name)
4450 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
4451 if (!doit) {
4452 return true;
4453 }
4454 didSomething = true;
4455 providers.add(provider);
4456 }
4457 }
4458
4459 N = providers.size();
4460 for (i=0; i<N; i++) {
4461 removeDyingProviderLocked(null, providers.get(i));
4462 }
4463
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004464 if (doit) {
4465 if (purgeCache) {
4466 AttributeCache ac = AttributeCache.instance();
4467 if (ac != null) {
4468 ac.removePackage(name);
4469 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004470 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004471 if (mBooted) {
4472 mMainStack.resumeTopActivityLocked(null);
4473 mMainStack.scheduleIdleLocked();
4474 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004475 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004476
4477 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478 }
4479
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004480 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004481 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004483 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004484 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004485 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004486 + "/" + uid + ")");
4487
4488 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004489 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004490 if (mHeavyWeightProcess == app) {
4491 mHeavyWeightProcess = null;
4492 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
4493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 boolean needRestart = false;
4495 if (app.pid > 0 && app.pid != MY_PID) {
4496 int pid = app.pid;
4497 synchronized (mPidsSelfLocked) {
4498 mPidsSelfLocked.remove(pid);
4499 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4500 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004501 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004502 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004503 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004504 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004506 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004508 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509 } else {
4510 needRestart = true;
4511 }
4512 }
4513 } else {
4514 mRemovedProcesses.add(app);
4515 }
4516
4517 return needRestart;
4518 }
4519
4520 private final void processStartTimedOutLocked(ProcessRecord app) {
4521 final int pid = app.pid;
4522 boolean gone = false;
4523 synchronized (mPidsSelfLocked) {
4524 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4525 if (knownApp != null && knownApp.thread == null) {
4526 mPidsSelfLocked.remove(pid);
4527 gone = true;
4528 }
4529 }
4530
4531 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004532 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004533 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004534 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004535 mProcessNames.remove(app.processName, app.uid);
4536 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004537 if (mHeavyWeightProcess == app) {
4538 mHeavyWeightProcess = null;
4539 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
4540 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004541 // Take care of any launching providers waiting for this process.
4542 checkAppInLaunchingProvidersLocked(app, true);
4543 // Take care of any services that are waiting for the process.
4544 for (int i=0; i<mPendingServices.size(); i++) {
4545 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004546 if ((app.uid == sr.appInfo.uid
4547 && app.processName.equals(sr.processName))
4548 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004549 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004550 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004551 mPendingServices.remove(i);
4552 i--;
4553 bringDownServiceLocked(sr, true);
4554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004555 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004556 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
4557 app.processName, app.setAdj, "start timeout");
4558 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004559 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004560 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004561 try {
4562 IBackupManager bm = IBackupManager.Stub.asInterface(
4563 ServiceManager.getService(Context.BACKUP_SERVICE));
4564 bm.agentDisconnected(app.info.packageName);
4565 } catch (RemoteException e) {
4566 // Can't happen; the backup manager is local
4567 }
4568 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004569 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004570 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004571 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004573 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004574 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 }
4576 }
4577
4578 private final boolean attachApplicationLocked(IApplicationThread thread,
4579 int pid) {
4580
4581 // Find the application record that is being attached... either via
4582 // the pid if we are running in multiple processes, or just pull the
4583 // next app record if we are emulating process with anonymous threads.
4584 ProcessRecord app;
4585 if (pid != MY_PID && pid >= 0) {
4586 synchronized (mPidsSelfLocked) {
4587 app = mPidsSelfLocked.get(pid);
4588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004589 } else {
4590 app = null;
4591 }
4592
4593 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004594 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004596 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004597 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004598 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 } else {
4600 try {
4601 thread.scheduleExit();
4602 } catch (Exception e) {
4603 // Ignore exceptions.
4604 }
4605 }
4606 return false;
4607 }
4608
4609 // If this application record is still attached to a previous
4610 // process, clean it up now.
4611 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004612 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 }
4614
4615 // Tell the process all about itself.
4616
Joe Onorato8a9b2202010-02-26 18:56:32 -08004617 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004618 TAG, "Binding process pid " + pid + " to record " + app);
4619
4620 String processName = app.processName;
4621 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004622 AppDeathRecipient adr = new AppDeathRecipient(
4623 app, pid, thread);
4624 thread.asBinder().linkToDeath(adr, 0);
4625 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 } catch (RemoteException e) {
4627 app.resetPackageList();
4628 startProcessLocked(app, "link fail", processName);
4629 return false;
4630 }
4631
Doug Zongker2bec3d42009-12-04 12:52:44 -08004632 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004633
4634 app.thread = thread;
4635 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004636 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4637 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004638 app.forcingToForeground = null;
4639 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004640 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 app.debugging = false;
4642
4643 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4644
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004645 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004646 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004648 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004649 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004650 }
4651
Joe Onorato8a9b2202010-02-26 18:56:32 -08004652 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004653 TAG, "New app record " + app
4654 + " thread=" + thread.asBinder() + " pid=" + pid);
4655 try {
4656 int testMode = IApplicationThread.DEBUG_OFF;
4657 if (mDebugApp != null && mDebugApp.equals(processName)) {
4658 testMode = mWaitForDebugger
4659 ? IApplicationThread.DEBUG_WAIT
4660 : IApplicationThread.DEBUG_ON;
4661 app.debugging = true;
4662 if (mDebugTransient) {
4663 mDebugApp = mOrigDebugApp;
4664 mWaitForDebugger = mOrigWaitForDebugger;
4665 }
4666 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004667 String profileFile = app.instrumentationProfileFile;
4668 ParcelFileDescriptor profileFd = null;
4669 boolean profileAutoStop = false;
4670 if (mProfileApp != null && mProfileApp.equals(processName)) {
4671 mProfileProc = app;
4672 profileFile = mProfileFile;
4673 profileFd = mProfileFd;
4674 profileAutoStop = mAutoStopProfiler;
4675 }
4676
Christopher Tate181fafa2009-05-14 11:12:14 -07004677 // If the app is being launched for restore or full backup, set it up specially
4678 boolean isRestrictedBackupMode = false;
4679 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4680 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004681 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004682 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4683 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004684
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004685 ensurePackageDexOpt(app.instrumentationInfo != null
4686 ? app.instrumentationInfo.packageName
4687 : app.info.packageName);
4688 if (app.instrumentationClass != null) {
4689 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004690 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004691 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004692 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004693 ApplicationInfo appInfo = app.instrumentationInfo != null
4694 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004695 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004696 if (profileFd != null) {
4697 profileFd = profileFd.dup();
4698 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004699 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004700 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004701 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn5d927c22011-09-02 12:22:18 -07004702 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004703 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004704 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004705 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004706 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 } catch (Exception e) {
4708 // todo: Yikes! What should we do? For now we will try to
4709 // start another process, but that could easily get us in
4710 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004711 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004712
4713 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004714 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 startProcessLocked(app, "bind fail", processName);
4716 return false;
4717 }
4718
4719 // Remove this record from the list of starting applications.
4720 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004721 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4722 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004723 mProcessesOnHold.remove(app);
4724
4725 boolean badApp = false;
4726 boolean didSomething = false;
4727
4728 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004729 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004730 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004731 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004732 && processName.equals(hr.processName)) {
4733 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004734 if (mHeadless) {
4735 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4736 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004737 didSomething = true;
4738 }
4739 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004740 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004741 + hr.intent.getComponent().flattenToShortString(), e);
4742 badApp = true;
4743 }
4744 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004745 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004746 }
4747 }
4748
4749 // Find any services that should be running in this process...
4750 if (!badApp && mPendingServices.size() > 0) {
4751 ServiceRecord sr = null;
4752 try {
4753 for (int i=0; i<mPendingServices.size(); i++) {
4754 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004755 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4756 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004757 continue;
4758 }
4759
4760 mPendingServices.remove(i);
4761 i--;
4762 realStartServiceLocked(sr, app);
4763 didSomething = true;
4764 }
4765 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004766 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004767 + sr.shortName, e);
4768 badApp = true;
4769 }
4770 }
4771
Christopher Tatef46723b2012-01-26 14:19:24 -08004772 // Check if a next-broadcast receiver is in this process...
4773 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004774 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004775 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004777 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004778 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004779 }
4780 }
4781
Christopher Tate181fafa2009-05-14 11:12:14 -07004782 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004783 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004784 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004785 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004786 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004787 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4788 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4789 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004790 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004791 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004792 e.printStackTrace();
4793 }
4794 }
4795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004796 if (badApp) {
4797 // todo: Also need to kill application to deal with all
4798 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004799 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004800 return false;
4801 }
4802
4803 if (!didSomething) {
4804 updateOomAdjLocked();
4805 }
4806
4807 return true;
4808 }
4809
4810 public final void attachApplication(IApplicationThread thread) {
4811 synchronized (this) {
4812 int callingPid = Binder.getCallingPid();
4813 final long origId = Binder.clearCallingIdentity();
4814 attachApplicationLocked(thread, callingPid);
4815 Binder.restoreCallingIdentity(origId);
4816 }
4817 }
4818
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004819 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004820 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004821 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4822 if (stopProfiling) {
4823 synchronized (this) {
4824 if (mProfileProc == r.app) {
4825 if (mProfileFd != null) {
4826 try {
4827 mProfileFd.close();
4828 } catch (IOException e) {
4829 }
4830 clearProfilerLocked();
4831 }
4832 }
4833 }
4834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004835 Binder.restoreCallingIdentity(origId);
4836 }
4837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004838 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004839 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004840 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004841 mWindowManager.enableScreenAfterBoot();
4842 }
4843
Dianne Hackborn661cd522011-08-22 00:26:20 -07004844 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004845 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004846 mWindowManager.showBootMessage(msg, always);
4847 }
4848
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004849 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004850 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004851 synchronized (this) {
4852 mMainStack.dismissKeyguardOnNextActivityLocked();
4853 }
4854 }
4855
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004856 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004857 IntentFilter pkgFilter = new IntentFilter();
4858 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4859 pkgFilter.addDataScheme("package");
4860 mContext.registerReceiver(new BroadcastReceiver() {
4861 @Override
4862 public void onReceive(Context context, Intent intent) {
4863 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4864 if (pkgs != null) {
4865 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004866 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004867 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004868 setResultCode(Activity.RESULT_OK);
4869 return;
4870 }
4871 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004872 }
4873 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004874 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004875 }, pkgFilter);
4876
4877 synchronized (this) {
4878 // Ensure that any processes we had put on hold are now started
4879 // up.
4880 final int NP = mProcessesOnHold.size();
4881 if (NP > 0) {
4882 ArrayList<ProcessRecord> procs =
4883 new ArrayList<ProcessRecord>(mProcessesOnHold);
4884 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004885 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4886 + procs.get(ip));
4887 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004888 }
4889 }
4890
4891 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004892 // Start looking for apps that are abusing wake locks.
4893 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004894 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004895 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004896 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004897 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004898 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004899 broadcastIntentLocked(null, null,
4900 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4901 null, null, 0, null, null,
4902 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004903 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004904 }
4905 }
4906 }
4907
4908 final void ensureBootCompleted() {
4909 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004910 boolean enableScreen;
4911 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004912 booting = mBooting;
4913 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004914 enableScreen = !mBooted;
4915 mBooted = true;
4916 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004917
4918 if (booting) {
4919 finishBooting();
4920 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004921
4922 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004923 enableScreenAfterBoot();
4924 }
4925 }
4926
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004927 public final void activityPaused(IBinder token) {
4928 final long origId = Binder.clearCallingIdentity();
4929 mMainStack.activityPaused(token, false);
4930 Binder.restoreCallingIdentity(origId);
4931 }
4932
4933 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4934 CharSequence description) {
4935 if (localLOGV) Slog.v(
4936 TAG, "Activity stopped: token=" + token);
4937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004938 // Refuse possible leaked file descriptors
4939 if (icicle != null && icicle.hasFileDescriptors()) {
4940 throw new IllegalArgumentException("File descriptors passed in Bundle");
4941 }
4942
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004943 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944
4945 final long origId = Binder.clearCallingIdentity();
4946
4947 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004948 r = mMainStack.isInStackLocked(token);
4949 if (r != null) {
4950 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004951 }
4952 }
4953
4954 if (r != null) {
4955 sendPendingThumbnail(r, null, null, null, false);
4956 }
4957
4958 trimApplications();
4959
4960 Binder.restoreCallingIdentity(origId);
4961 }
4962
4963 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004964 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004965 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004966 }
4967
4968 public String getCallingPackage(IBinder token) {
4969 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004970 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004971 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004972 }
4973 }
4974
4975 public ComponentName getCallingActivity(IBinder token) {
4976 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004977 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004978 return r != null ? r.intent.getComponent() : null;
4979 }
4980 }
4981
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004982 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004983 ActivityRecord r = mMainStack.isInStackLocked(token);
4984 if (r == null) {
4985 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004986 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004987 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004988 }
4989
4990 public ComponentName getActivityClassForToken(IBinder token) {
4991 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004992 ActivityRecord r = mMainStack.isInStackLocked(token);
4993 if (r == null) {
4994 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004995 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004996 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004997 }
4998 }
4999
5000 public String getPackageForToken(IBinder token) {
5001 synchronized(this) {
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.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005007 }
5008 }
5009
5010 public IIntentSender getIntentSender(int type,
5011 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005012 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005013 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005014 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005015 if (intents != null) {
5016 if (intents.length < 1) {
5017 throw new IllegalArgumentException("Intents array length must be >= 1");
5018 }
5019 for (int i=0; i<intents.length; i++) {
5020 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07005021 if (intent != null) {
5022 if (intent.hasFileDescriptors()) {
5023 throw new IllegalArgumentException("File descriptors passed in Intent");
5024 }
5025 if (type == INTENT_SENDER_BROADCAST &&
5026 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
5027 throw new IllegalArgumentException(
5028 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
5029 }
5030 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005031 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005032 }
5033 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005034 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005035 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005036 }
5037 }
5038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005039 synchronized(this) {
5040 int callingUid = Binder.getCallingUid();
5041 try {
Jeff Brown10e89712011-07-08 18:52:57 -07005042 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005043 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005044 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07005045 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005046 String msg = "Permission Denial: getIntentSender() from pid="
5047 + Binder.getCallingPid()
5048 + ", uid=" + Binder.getCallingUid()
5049 + ", (need uid=" + uid + ")"
5050 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005051 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005052 throw new SecurityException(msg);
5053 }
5054 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005055
Amith Yamasani742a6712011-05-04 14:49:28 -07005056 if (DEBUG_MU)
5057 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
5058 + Binder.getOrigCallingUid());
5059 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005060 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07005061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 } catch (RemoteException e) {
5063 throw new SecurityException(e);
5064 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005065 }
5066 }
5067
5068 IIntentSender getIntentSenderLocked(int type,
5069 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005070 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005071 if (DEBUG_MU)
5072 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005073 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07005074 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005075 activity = mMainStack.isInStackLocked(token);
5076 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005077 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005078 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005079 if (activity.finishing) {
5080 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005081 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005082 }
5083
5084 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
5085 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
5086 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
5087 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
5088 |PendingIntent.FLAG_UPDATE_CURRENT);
5089
5090 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
5091 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005092 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07005093 WeakReference<PendingIntentRecord> ref;
5094 ref = mIntentSenderRecords.get(key);
5095 PendingIntentRecord rec = ref != null ? ref.get() : null;
5096 if (rec != null) {
5097 if (!cancelCurrent) {
5098 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005099 if (rec.key.requestIntent != null) {
5100 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
5101 }
5102 if (intents != null) {
5103 intents[intents.length-1] = rec.key.requestIntent;
5104 rec.key.allIntents = intents;
5105 rec.key.allResolvedTypes = resolvedTypes;
5106 } else {
5107 rec.key.allIntents = null;
5108 rec.key.allResolvedTypes = null;
5109 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 return rec;
5112 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005113 rec.canceled = true;
5114 mIntentSenderRecords.remove(key);
5115 }
5116 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005117 return rec;
5118 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005119 rec = new PendingIntentRecord(this, key, callingUid);
5120 mIntentSenderRecords.put(key, rec.ref);
5121 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
5122 if (activity.pendingResults == null) {
5123 activity.pendingResults
5124 = new HashSet<WeakReference<PendingIntentRecord>>();
5125 }
5126 activity.pendingResults.add(rec.ref);
5127 }
5128 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 }
5130
5131 public void cancelIntentSender(IIntentSender sender) {
5132 if (!(sender instanceof PendingIntentRecord)) {
5133 return;
5134 }
5135 synchronized(this) {
5136 PendingIntentRecord rec = (PendingIntentRecord)sender;
5137 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005138 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 .getPackageUid(rec.key.packageName);
5140 if (uid != Binder.getCallingUid()) {
5141 String msg = "Permission Denial: cancelIntentSender() from pid="
5142 + Binder.getCallingPid()
5143 + ", uid=" + Binder.getCallingUid()
5144 + " is not allowed to cancel packges "
5145 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005146 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005147 throw new SecurityException(msg);
5148 }
5149 } catch (RemoteException e) {
5150 throw new SecurityException(e);
5151 }
5152 cancelIntentSenderLocked(rec, true);
5153 }
5154 }
5155
5156 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
5157 rec.canceled = true;
5158 mIntentSenderRecords.remove(rec.key);
5159 if (cleanActivity && rec.key.activity != null) {
5160 rec.key.activity.pendingResults.remove(rec.ref);
5161 }
5162 }
5163
5164 public String getPackageForIntentSender(IIntentSender pendingResult) {
5165 if (!(pendingResult instanceof PendingIntentRecord)) {
5166 return null;
5167 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07005168 try {
5169 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5170 return res.key.packageName;
5171 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005172 }
5173 return null;
5174 }
5175
Dianne Hackborn6c418d52011-06-29 14:05:33 -07005176 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
5177 if (!(pendingResult instanceof PendingIntentRecord)) {
5178 return false;
5179 }
5180 try {
5181 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5182 if (res.key.allIntents == null) {
5183 return false;
5184 }
5185 for (int i=0; i<res.key.allIntents.length; i++) {
5186 Intent intent = res.key.allIntents[i];
5187 if (intent.getPackage() != null && intent.getComponent() != null) {
5188 return false;
5189 }
5190 }
5191 return true;
5192 } catch (ClassCastException e) {
5193 }
5194 return false;
5195 }
5196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005197 public void setProcessLimit(int max) {
5198 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5199 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005200 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005201 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005202 mProcessLimitOverride = max;
5203 }
5204 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 }
5206
5207 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005208 synchronized (this) {
5209 return mProcessLimitOverride;
5210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005211 }
5212
5213 void foregroundTokenDied(ForegroundToken token) {
5214 synchronized (ActivityManagerService.this) {
5215 synchronized (mPidsSelfLocked) {
5216 ForegroundToken cur
5217 = mForegroundProcesses.get(token.pid);
5218 if (cur != token) {
5219 return;
5220 }
5221 mForegroundProcesses.remove(token.pid);
5222 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
5223 if (pr == null) {
5224 return;
5225 }
5226 pr.forcingToForeground = null;
5227 pr.foregroundServices = false;
5228 }
5229 updateOomAdjLocked();
5230 }
5231 }
5232
5233 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
5234 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5235 "setProcessForeground()");
5236 synchronized(this) {
5237 boolean changed = false;
5238
5239 synchronized (mPidsSelfLocked) {
5240 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005241 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005242 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005243 return;
5244 }
5245 ForegroundToken oldToken = mForegroundProcesses.get(pid);
5246 if (oldToken != null) {
5247 oldToken.token.unlinkToDeath(oldToken, 0);
5248 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005249 if (pr != null) {
5250 pr.forcingToForeground = null;
5251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005252 changed = true;
5253 }
5254 if (isForeground && token != null) {
5255 ForegroundToken newToken = new ForegroundToken() {
5256 public void binderDied() {
5257 foregroundTokenDied(this);
5258 }
5259 };
5260 newToken.pid = pid;
5261 newToken.token = token;
5262 try {
5263 token.linkToDeath(newToken, 0);
5264 mForegroundProcesses.put(pid, newToken);
5265 pr.forcingToForeground = token;
5266 changed = true;
5267 } catch (RemoteException e) {
5268 // If the process died while doing this, we will later
5269 // do the cleanup with the process death link.
5270 }
5271 }
5272 }
5273
5274 if (changed) {
5275 updateOomAdjLocked();
5276 }
5277 }
5278 }
5279
5280 // =========================================================
5281 // PERMISSIONS
5282 // =========================================================
5283
5284 static class PermissionController extends IPermissionController.Stub {
5285 ActivityManagerService mActivityManagerService;
5286 PermissionController(ActivityManagerService activityManagerService) {
5287 mActivityManagerService = activityManagerService;
5288 }
5289
5290 public boolean checkPermission(String permission, int pid, int uid) {
5291 return mActivityManagerService.checkPermission(permission, pid,
5292 uid) == PackageManager.PERMISSION_GRANTED;
5293 }
5294 }
5295
5296 /**
5297 * This can be called with or without the global lock held.
5298 */
5299 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005300 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005301 // We might be performing an operation on behalf of an indirect binder
5302 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
5303 // client identity accordingly before proceeding.
5304 Identity tlsIdentity = sCallerIdentity.get();
5305 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005306 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005307 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
5308 uid = tlsIdentity.uid;
5309 pid = tlsIdentity.pid;
5310 }
5311
5312 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005313 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 return PackageManager.PERMISSION_GRANTED;
5315 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005316 // Isolated processes don't get any permissions.
5317 if (UserId.isIsolated(uid)) {
5318 return PackageManager.PERMISSION_DENIED;
5319 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005320 // If there is a uid that owns whatever is being accessed, it has
5321 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07005322 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005323 return PackageManager.PERMISSION_GRANTED;
5324 }
5325 // If the target is not exported, then nobody else can get to it.
5326 if (!exported) {
5327 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005328 return PackageManager.PERMISSION_DENIED;
5329 }
5330 if (permission == null) {
5331 return PackageManager.PERMISSION_GRANTED;
5332 }
5333 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005334 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005335 .checkUidPermission(permission, uid);
5336 } catch (RemoteException e) {
5337 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08005338 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005339 }
5340 return PackageManager.PERMISSION_DENIED;
5341 }
5342
5343 /**
5344 * As the only public entry point for permissions checking, this method
5345 * can enforce the semantic that requesting a check on a null global
5346 * permission is automatically denied. (Internally a null permission
5347 * string is used when calling {@link #checkComponentPermission} in cases
5348 * when only uid-based security is needed.)
5349 *
5350 * This can be called with or without the global lock held.
5351 */
5352 public int checkPermission(String permission, int pid, int uid) {
5353 if (permission == null) {
5354 return PackageManager.PERMISSION_DENIED;
5355 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005356 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 }
5358
5359 /**
5360 * Binder IPC calls go through the public entry point.
5361 * This can be called with or without the global lock held.
5362 */
5363 int checkCallingPermission(String permission) {
5364 return checkPermission(permission,
5365 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07005366 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367 }
5368
5369 /**
5370 * This can be called with or without the global lock held.
5371 */
5372 void enforceCallingPermission(String permission, String func) {
5373 if (checkCallingPermission(permission)
5374 == PackageManager.PERMISSION_GRANTED) {
5375 return;
5376 }
5377
5378 String msg = "Permission Denial: " + func + " from pid="
5379 + Binder.getCallingPid()
5380 + ", uid=" + Binder.getCallingUid()
5381 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005382 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005383 throw new SecurityException(msg);
5384 }
5385
5386 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07005387 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
5388 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
5389 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
5390 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5391 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005393 // Is the component private from the target uid?
5394 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
5395
5396 // Acceptable if the there is no read permission needed from the
5397 // target or the target is holding the read permission.
5398 if (!readPerm) {
5399 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005400 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07005401 == PackageManager.PERMISSION_GRANTED)) {
5402 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005403 }
5404 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005405
5406 // Acceptable if the there is no write permission needed from the
5407 // target or the target is holding the read permission.
5408 if (!writePerm) {
5409 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005410 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07005411 == PackageManager.PERMISSION_GRANTED)) {
5412 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005413 }
5414 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005415
5416 // Acceptable if there is a path permission matching the URI that
5417 // the target holds the permission on.
5418 PathPermission[] pps = pi.pathPermissions;
5419 if (pps != null && (!readPerm || !writePerm)) {
5420 final String path = uri.getPath();
5421 int i = pps.length;
5422 while (i > 0 && (!readPerm || !writePerm)) {
5423 i--;
5424 PathPermission pp = pps[i];
5425 if (!readPerm) {
5426 final String pprperm = pp.getReadPermission();
5427 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5428 + pprperm + " for " + pp.getPath()
5429 + ": match=" + pp.match(path)
5430 + " check=" + pm.checkUidPermission(pprperm, uid));
5431 if (pprperm != null && pp.match(path) &&
5432 (pm.checkUidPermission(pprperm, uid)
5433 == PackageManager.PERMISSION_GRANTED)) {
5434 readPerm = true;
5435 }
5436 }
5437 if (!writePerm) {
5438 final String ppwperm = pp.getWritePermission();
5439 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5440 + ppwperm + " for " + pp.getPath()
5441 + ": match=" + pp.match(path)
5442 + " check=" + pm.checkUidPermission(ppwperm, uid));
5443 if (ppwperm != null && pp.match(path) &&
5444 (pm.checkUidPermission(ppwperm, uid)
5445 == PackageManager.PERMISSION_GRANTED)) {
5446 writePerm = true;
5447 }
5448 }
5449 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 } catch (RemoteException e) {
5452 return false;
5453 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005454
5455 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456 }
5457
5458 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5459 int modeFlags) {
5460 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005461 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005462 return true;
5463 }
5464 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5465 if (perms == null) return false;
5466 UriPermission perm = perms.get(uri);
5467 if (perm == null) return false;
5468 return (modeFlags&perm.modeFlags) == modeFlags;
5469 }
5470
5471 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005472 enforceNotIsolatedCaller("checkUriPermission");
5473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 // Another redirected-binder-call permissions check as in
5475 // {@link checkComponentPermission}.
5476 Identity tlsIdentity = sCallerIdentity.get();
5477 if (tlsIdentity != null) {
5478 uid = tlsIdentity.uid;
5479 pid = tlsIdentity.pid;
5480 }
5481
Amith Yamasani742a6712011-05-04 14:49:28 -07005482 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 // Our own process gets to do everything.
5484 if (pid == MY_PID) {
5485 return PackageManager.PERMISSION_GRANTED;
5486 }
5487 synchronized(this) {
5488 return checkUriPermissionLocked(uri, uid, modeFlags)
5489 ? PackageManager.PERMISSION_GRANTED
5490 : PackageManager.PERMISSION_DENIED;
5491 }
5492 }
5493
Dianne Hackborn39792d22010-08-19 18:01:52 -07005494 /**
5495 * Check if the targetPkg can be granted permission to access uri by
5496 * the callingUid using the given modeFlags. Throws a security exception
5497 * if callingUid is not allowed to do this. Returns the uid of the target
5498 * if the URI permission grant should be performed; returns -1 if it is not
5499 * needed (for example targetPkg already has permission to access the URI).
5500 */
5501 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
5502 Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005503 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5504 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5505 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005506 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 }
5508
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005509 if (targetPkg != null) {
5510 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5511 "Checking grant " + targetPkg + " permission to " + uri);
5512 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005513
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005514 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515
5516 // If this is not a content: uri, we can't do anything with it.
5517 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005518 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005519 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005520 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 }
5522
5523 String name = uri.getAuthority();
5524 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005525 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
5526 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527 if (cpr != null) {
5528 pi = cpr.info;
5529 } else {
5530 try {
5531 pi = pm.resolveContentProvider(name,
5532 PackageManager.GET_URI_PERMISSION_PATTERNS);
5533 } catch (RemoteException ex) {
5534 }
5535 }
5536 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005537 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005538 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 }
5540
5541 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005542 if (targetPkg != null) {
5543 try {
5544 targetUid = pm.getPackageUid(targetPkg);
5545 if (targetUid < 0) {
5546 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5547 "Can't grant URI permission no uid for: " + targetPkg);
5548 return -1;
5549 }
5550 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005551 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005552 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005553 } else {
5554 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005555 }
5556
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005557 if (targetUid >= 0) {
5558 // First... does the target actually need this permission?
5559 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5560 // No need to grant the target this permission.
5561 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5562 "Target " + targetPkg + " already has full permission to " + uri);
5563 return -1;
5564 }
5565 } else {
5566 // First... there is no target package, so can anyone access it?
5567 boolean allowed = pi.exported;
5568 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5569 if (pi.readPermission != null) {
5570 allowed = false;
5571 }
5572 }
5573 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5574 if (pi.writePermission != null) {
5575 allowed = false;
5576 }
5577 }
5578 if (allowed) {
5579 return -1;
5580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 }
5582
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005583 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005584 if (!pi.grantUriPermissions) {
5585 throw new SecurityException("Provider " + pi.packageName
5586 + "/" + pi.name
5587 + " does not allow granting of Uri permissions (uri "
5588 + uri + ")");
5589 }
5590 if (pi.uriPermissionPatterns != null) {
5591 final int N = pi.uriPermissionPatterns.length;
5592 boolean allowed = false;
5593 for (int i=0; i<N; i++) {
5594 if (pi.uriPermissionPatterns[i] != null
5595 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5596 allowed = true;
5597 break;
5598 }
5599 }
5600 if (!allowed) {
5601 throw new SecurityException("Provider " + pi.packageName
5602 + "/" + pi.name
5603 + " does not allow granting of permission to path of Uri "
5604 + uri);
5605 }
5606 }
5607
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005608 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005610 if (callingUid != Process.myUid()) {
5611 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5612 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5613 throw new SecurityException("Uid " + callingUid
5614 + " does not have permission to uri " + uri);
5615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 }
5617 }
5618
Dianne Hackborn39792d22010-08-19 18:01:52 -07005619 return targetUid;
5620 }
5621
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005622 public int checkGrantUriPermission(int callingUid, String targetPkg,
5623 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005624 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005625 synchronized(this) {
5626 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
5627 }
5628 }
5629
Dianne Hackborn39792d22010-08-19 18:01:52 -07005630 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5631 Uri uri, int modeFlags, UriPermissionOwner owner) {
5632 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5633 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5634 if (modeFlags == 0) {
5635 return;
5636 }
5637
5638 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 // to the uri, and the target doesn't. Let's now give this to
5640 // the target.
5641
Joe Onorato8a9b2202010-02-26 18:56:32 -08005642 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005643 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005645 HashMap<Uri, UriPermission> targetUris
5646 = mGrantedUriPermissions.get(targetUid);
5647 if (targetUris == null) {
5648 targetUris = new HashMap<Uri, UriPermission>();
5649 mGrantedUriPermissions.put(targetUid, targetUris);
5650 }
5651
5652 UriPermission perm = targetUris.get(uri);
5653 if (perm == null) {
5654 perm = new UriPermission(targetUid, uri);
5655 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005659 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005661 } else {
5662 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5663 perm.readOwners.add(owner);
5664 owner.addReadPermission(perm);
5665 }
5666 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5667 perm.writeOwners.add(owner);
5668 owner.addWritePermission(perm);
5669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 }
5671 }
5672
Dianne Hackborn39792d22010-08-19 18:01:52 -07005673 void grantUriPermissionLocked(int callingUid,
5674 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005675 if (targetPkg == null) {
5676 throw new NullPointerException("targetPkg");
5677 }
5678
Dianne Hackborn39792d22010-08-19 18:01:52 -07005679 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
5680 if (targetUid < 0) {
5681 return;
5682 }
5683
5684 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5685 }
5686
5687 /**
5688 * Like checkGrantUriPermissionLocked, but takes an Intent.
5689 */
5690 int checkGrantUriPermissionFromIntentLocked(int callingUid,
5691 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005692 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005693 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005694 + " from " + intent + "; flags=0x"
5695 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5696
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005697 if (targetPkg == null) {
5698 throw new NullPointerException("targetPkg");
5699 }
5700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005702 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 }
5704 Uri data = intent.getData();
5705 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005706 return -1;
5707 }
5708 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5709 intent.getFlags());
5710 }
5711
5712 /**
5713 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5714 */
5715 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
5716 String targetPkg, Intent intent, UriPermissionOwner owner) {
5717 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
5718 intent.getFlags(), owner);
5719 }
5720
5721 void grantUriPermissionFromIntentLocked(int callingUid,
5722 String targetPkg, Intent intent, UriPermissionOwner owner) {
5723 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
5724 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 return;
5726 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005727
5728 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 }
5730
5731 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5732 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005733 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 synchronized(this) {
5735 final ProcessRecord r = getRecordForAppLocked(caller);
5736 if (r == null) {
5737 throw new SecurityException("Unable to find app for caller "
5738 + caller
5739 + " when granting permission to uri " + uri);
5740 }
5741 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005742 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 }
5744 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005745 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005746 }
5747
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005748 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 null);
5750 }
5751 }
5752
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005753 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5755 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5756 HashMap<Uri, UriPermission> perms
5757 = mGrantedUriPermissions.get(perm.uid);
5758 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005759 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005760 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 perms.remove(perm.uri);
5762 if (perms.size() == 0) {
5763 mGrantedUriPermissions.remove(perm.uid);
5764 }
5765 }
5766 }
5767 }
5768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5770 int modeFlags) {
5771 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5772 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5773 if (modeFlags == 0) {
5774 return;
5775 }
5776
Joe Onorato8a9b2202010-02-26 18:56:32 -08005777 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005778 "Revoking all granted permissions to " + uri);
5779
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005780 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781
5782 final String authority = uri.getAuthority();
5783 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005784 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
5785 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 if (cpr != null) {
5787 pi = cpr.info;
5788 } else {
5789 try {
5790 pi = pm.resolveContentProvider(authority,
5791 PackageManager.GET_URI_PERMISSION_PATTERNS);
5792 } catch (RemoteException ex) {
5793 }
5794 }
5795 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005796 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 return;
5798 }
5799
5800 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005801 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802 // Right now, if you are not the original owner of the permission,
5803 // you are not allowed to revoke it.
5804 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5805 throw new SecurityException("Uid " + callingUid
5806 + " does not have permission to uri " + uri);
5807 //}
5808 }
5809
5810 // Go through all of the permissions and remove any that match.
5811 final List<String> SEGMENTS = uri.getPathSegments();
5812 if (SEGMENTS != null) {
5813 final int NS = SEGMENTS.size();
5814 int N = mGrantedUriPermissions.size();
5815 for (int i=0; i<N; i++) {
5816 HashMap<Uri, UriPermission> perms
5817 = mGrantedUriPermissions.valueAt(i);
5818 Iterator<UriPermission> it = perms.values().iterator();
5819 toploop:
5820 while (it.hasNext()) {
5821 UriPermission perm = it.next();
5822 Uri targetUri = perm.uri;
5823 if (!authority.equals(targetUri.getAuthority())) {
5824 continue;
5825 }
5826 List<String> targetSegments = targetUri.getPathSegments();
5827 if (targetSegments == null) {
5828 continue;
5829 }
5830 if (targetSegments.size() < NS) {
5831 continue;
5832 }
5833 for (int j=0; j<NS; j++) {
5834 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5835 continue toploop;
5836 }
5837 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005838 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005839 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 perm.clearModes(modeFlags);
5841 if (perm.modeFlags == 0) {
5842 it.remove();
5843 }
5844 }
5845 if (perms.size() == 0) {
5846 mGrantedUriPermissions.remove(
5847 mGrantedUriPermissions.keyAt(i));
5848 N--;
5849 i--;
5850 }
5851 }
5852 }
5853 }
5854
5855 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5856 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005857 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858 synchronized(this) {
5859 final ProcessRecord r = getRecordForAppLocked(caller);
5860 if (r == null) {
5861 throw new SecurityException("Unable to find app for caller "
5862 + caller
5863 + " when revoking permission to uri " + uri);
5864 }
5865 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005866 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 return;
5868 }
5869
5870 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5871 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5872 if (modeFlags == 0) {
5873 return;
5874 }
5875
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005876 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877
5878 final String authority = uri.getAuthority();
5879 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005880 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 if (cpr != null) {
5882 pi = cpr.info;
5883 } else {
5884 try {
5885 pi = pm.resolveContentProvider(authority,
5886 PackageManager.GET_URI_PERMISSION_PATTERNS);
5887 } catch (RemoteException ex) {
5888 }
5889 }
5890 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005891 Slog.w(TAG, "No content provider found for permission revoke: "
5892 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 return;
5894 }
5895
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005896 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 }
5898 }
5899
Dianne Hackborn7e269642010-08-25 19:50:20 -07005900 @Override
5901 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005902 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005903 synchronized(this) {
5904 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5905 return owner.getExternalTokenLocked();
5906 }
5907 }
5908
5909 @Override
5910 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5911 Uri uri, int modeFlags) {
5912 synchronized(this) {
5913 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5914 if (owner == null) {
5915 throw new IllegalArgumentException("Unknown owner: " + token);
5916 }
5917 if (fromUid != Binder.getCallingUid()) {
5918 if (Binder.getCallingUid() != Process.myUid()) {
5919 // Only system code can grant URI permissions on behalf
5920 // of other users.
5921 throw new SecurityException("nice try");
5922 }
5923 }
5924 if (targetPkg == null) {
5925 throw new IllegalArgumentException("null target");
5926 }
5927 if (uri == null) {
5928 throw new IllegalArgumentException("null uri");
5929 }
5930
5931 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5932 }
5933 }
5934
5935 @Override
5936 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5937 synchronized(this) {
5938 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5939 if (owner == null) {
5940 throw new IllegalArgumentException("Unknown owner: " + token);
5941 }
5942
5943 if (uri == null) {
5944 owner.removeUriPermissionsLocked(mode);
5945 } else {
5946 owner.removeUriPermissionLocked(uri, mode);
5947 }
5948 }
5949 }
5950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5952 synchronized (this) {
5953 ProcessRecord app =
5954 who != null ? getRecordForAppLocked(who) : null;
5955 if (app == null) return;
5956
5957 Message msg = Message.obtain();
5958 msg.what = WAIT_FOR_DEBUGGER_MSG;
5959 msg.obj = app;
5960 msg.arg1 = waiting ? 1 : 0;
5961 mHandler.sendMessage(msg);
5962 }
5963 }
5964
5965 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005966 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5967 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005969 outInfo.threshold = homeAppMem;
5970 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5971 outInfo.hiddenAppThreshold = hiddenAppMem;
5972 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005973 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005974 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5975 ProcessList.VISIBLE_APP_ADJ);
5976 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5977 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 }
5979
5980 // =========================================================
5981 // TASK MANAGEMENT
5982 // =========================================================
5983
5984 public List getTasks(int maxNum, int flags,
5985 IThumbnailReceiver receiver) {
5986 ArrayList list = new ArrayList();
5987
5988 PendingThumbnailsRecord pending = null;
5989 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005990 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991
5992 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005993 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5995 + ", receiver=" + receiver);
5996
5997 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5998 != PackageManager.PERMISSION_GRANTED) {
5999 if (receiver != null) {
6000 // If the caller wants to wait for pending thumbnails,
6001 // it ain't gonna get them.
6002 try {
6003 receiver.finished();
6004 } catch (RemoteException ex) {
6005 }
6006 }
6007 String msg = "Permission Denial: getTasks() from pid="
6008 + Binder.getCallingPid()
6009 + ", uid=" + Binder.getCallingUid()
6010 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006011 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 throw new SecurityException(msg);
6013 }
6014
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006015 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006016 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006017 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006018 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 TaskRecord curTask = null;
6020 int numActivities = 0;
6021 int numRunning = 0;
6022 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006023 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006025 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026
6027 // Initialize state for next task if needed.
6028 if (top == null ||
6029 (top.state == ActivityState.INITIALIZING
6030 && top.task == r.task)) {
6031 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 curTask = r.task;
6033 numActivities = numRunning = 0;
6034 }
6035
6036 // Add 'r' into the current task.
6037 numActivities++;
6038 if (r.app != null && r.app.thread != null) {
6039 numRunning++;
6040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041
Joe Onorato8a9b2202010-02-26 18:56:32 -08006042 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 TAG, r.intent.getComponent().flattenToShortString()
6044 + ": task=" + r.task);
6045
6046 // If the next one is a different task, generate a new
6047 // TaskInfo entry for what we have.
6048 if (next == null || next.task != curTask) {
6049 ActivityManager.RunningTaskInfo ci
6050 = new ActivityManager.RunningTaskInfo();
6051 ci.id = curTask.taskId;
6052 ci.baseActivity = r.intent.getComponent();
6053 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006054 if (top.thumbHolder != null) {
6055 ci.description = top.thumbHolder.lastDescription;
6056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006057 ci.numActivities = numActivities;
6058 ci.numRunning = numRunning;
6059 //System.out.println(
6060 // "#" + maxNum + ": " + " descr=" + ci.description);
6061 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006062 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006063 TAG, "State=" + top.state + "Idle=" + top.idle
6064 + " app=" + top.app
6065 + " thr=" + (top.app != null ? top.app.thread : null));
6066 if (top.state == ActivityState.RESUMED
6067 || top.state == ActivityState.PAUSING) {
6068 if (top.idle && top.app != null
6069 && top.app.thread != null) {
6070 topRecord = top;
6071 topThumbnail = top.app.thread;
6072 } else {
6073 top.thumbnailNeeded = true;
6074 }
6075 }
6076 if (pending == null) {
6077 pending = new PendingThumbnailsRecord(receiver);
6078 }
6079 pending.pendingRecords.add(top);
6080 }
6081 list.add(ci);
6082 maxNum--;
6083 top = null;
6084 }
6085 }
6086
6087 if (pending != null) {
6088 mPendingThumbnails.add(pending);
6089 }
6090 }
6091
Joe Onorato8a9b2202010-02-26 18:56:32 -08006092 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093
6094 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006095 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006096 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08006097 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006098 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006099 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006100 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006101 }
6102 }
6103
6104 if (pending == null && receiver != null) {
6105 // In this case all thumbnails were available and the client
6106 // is being asked to be told when the remaining ones come in...
6107 // which is unusually, since the top-most currently running
6108 // activity should never have a canned thumbnail! Oh well.
6109 try {
6110 receiver.finished();
6111 } catch (RemoteException ex) {
6112 }
6113 }
6114
6115 return list;
6116 }
6117
6118 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
6119 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006120 final int callingUid = Binder.getCallingUid();
6121 // If it's the system uid asking, then use the current user id.
6122 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
6123 // require the entire list.
6124 final int callingUserId = callingUid == Process.SYSTEM_UID
6125 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 synchronized (this) {
6127 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
6128 "getRecentTasks()");
6129
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006130 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07006131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132 final int N = mRecentTasks.size();
6133 ArrayList<ActivityManager.RecentTaskInfo> res
6134 = new ArrayList<ActivityManager.RecentTaskInfo>(
6135 maxNum < N ? maxNum : N);
6136 for (int i=0; i<N && maxNum > 0; i++) {
6137 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07006138 // Only add calling user's recent tasks
6139 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07006140 // Return the entry if desired by the caller. We always return
6141 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07006142 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07006143 // not supplied RECENT_WITH_EXCLUDED and there is some reason
6144 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07006145
Dianne Hackborn905577f2011-09-07 18:31:28 -07006146 if (i == 0
6147 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 || (tr.intent == null)
6149 || ((tr.intent.getFlags()
6150 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
6151 ActivityManager.RecentTaskInfo rti
6152 = new ActivityManager.RecentTaskInfo();
6153 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08006154 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 rti.baseIntent = new Intent(
6156 tr.intent != null ? tr.intent : tr.affinityIntent);
6157 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08006158 rti.description = tr.lastDescription;
6159
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07006160 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
6161 // Check whether this activity is currently available.
6162 try {
6163 if (rti.origActivity != null) {
6164 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
6165 continue;
6166 }
6167 } else if (rti.baseIntent != null) {
6168 if (pm.queryIntentActivities(rti.baseIntent,
6169 null, 0) == null) {
6170 continue;
6171 }
6172 }
6173 } catch (RemoteException e) {
6174 // Will never happen.
6175 }
6176 }
6177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 res.add(rti);
6179 maxNum--;
6180 }
6181 }
6182 return res;
6183 }
6184 }
6185
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006186 private TaskRecord taskForIdLocked(int id) {
6187 final int N = mRecentTasks.size();
6188 for (int i=0; i<N; i++) {
6189 TaskRecord tr = mRecentTasks.get(i);
6190 if (tr.taskId == id) {
6191 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08006192 }
6193 }
6194 return null;
6195 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006196
6197 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
6198 synchronized (this) {
6199 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
6200 "getTaskThumbnails()");
6201 TaskRecord tr = taskForIdLocked(id);
6202 if (tr != null) {
6203 return mMainStack.getTaskThumbnailsLocked(tr);
6204 }
6205 }
6206 return null;
6207 }
6208
6209 public boolean removeSubTask(int taskId, int subTaskIndex) {
6210 synchronized (this) {
6211 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
6212 "removeSubTask()");
6213 long ident = Binder.clearCallingIdentity();
6214 try {
6215 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
6216 } finally {
6217 Binder.restoreCallingIdentity(ident);
6218 }
6219 }
6220 }
6221
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006222 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006223 TaskRecord tr = root.task;
6224 Intent baseIntent = new Intent(
6225 tr.intent != null ? tr.intent : tr.affinityIntent);
6226 ComponentName component = baseIntent.getComponent();
6227 if (component == null) {
6228 Slog.w(TAG, "Now component for base intent of task: " + tr);
6229 return;
6230 }
6231
6232 // Find any running services associated with this app.
6233 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07006234 for (ServiceRecord sr : mServiceMap.getAllServices(root.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006235 if (sr.packageName.equals(component.getPackageName())) {
6236 services.add(sr);
6237 }
6238 }
6239
6240 // Take care of any running services associated with the app.
6241 for (int i=0; i<services.size(); i++) {
6242 ServiceRecord sr = services.get(i);
6243 if (sr.startRequested) {
6244 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006245 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006246 stopServiceLocked(sr);
6247 } else {
6248 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
6249 sr.makeNextStartId(), baseIntent, -1));
6250 if (sr.app != null && sr.app.thread != null) {
6251 sendServiceArgsLocked(sr, false);
6252 }
6253 }
6254 }
6255 }
6256
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006257 if (killProcesses) {
6258 // Find any running processes associated with this app.
6259 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
6260 SparseArray<ProcessRecord> appProcs
6261 = mProcessNames.getMap().get(component.getPackageName());
6262 if (appProcs != null) {
6263 for (int i=0; i<appProcs.size(); i++) {
6264 procs.add(appProcs.valueAt(i));
6265 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006266 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006267
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006268 // Kill the running processes.
6269 for (int i=0; i<procs.size(); i++) {
6270 ProcessRecord pr = procs.get(i);
6271 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
6272 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
6273 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
6274 pr.processName, pr.setAdj, "remove task");
6275 Process.killProcessQuiet(pr.pid);
6276 } else {
6277 pr.waitingToKill = "remove task";
6278 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006279 }
6280 }
6281 }
6282
6283 public boolean removeTask(int taskId, int flags) {
6284 synchronized (this) {
6285 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
6286 "removeTask()");
6287 long ident = Binder.clearCallingIdentity();
6288 try {
6289 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
6290 if (r != null) {
6291 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006292 cleanUpRemovedTaskLocked(r,
6293 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006294 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07006295 } else {
6296 TaskRecord tr = null;
6297 int i=0;
6298 while (i < mRecentTasks.size()) {
6299 TaskRecord t = mRecentTasks.get(i);
6300 if (t.taskId == taskId) {
6301 tr = t;
6302 break;
6303 }
6304 i++;
6305 }
6306 if (tr != null) {
6307 if (tr.numActivities <= 0) {
6308 // Caller is just removing a recent task that is
6309 // not actively running. That is easy!
6310 mRecentTasks.remove(i);
6311 } else {
6312 Slog.w(TAG, "removeTask: task " + taskId
6313 + " does not have activities to remove, "
6314 + " but numActivities=" + tr.numActivities
6315 + ": " + tr);
6316 }
6317 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006318 }
6319 } finally {
6320 Binder.restoreCallingIdentity(ident);
6321 }
6322 }
6323 return false;
6324 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08006325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006326 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
6327 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006328 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 TaskRecord jt = startTask;
6330
6331 // First look backwards
6332 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006333 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 if (r.task != jt) {
6335 jt = r.task;
6336 if (affinity.equals(jt.affinity)) {
6337 return j;
6338 }
6339 }
6340 }
6341
6342 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006343 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 jt = startTask;
6345 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006346 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 if (r.task != jt) {
6348 if (affinity.equals(jt.affinity)) {
6349 return j;
6350 }
6351 jt = r.task;
6352 }
6353 }
6354
6355 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006356 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 return N-1;
6358 }
6359
6360 return -1;
6361 }
6362
6363 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006364 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006366 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6368 "moveTaskToFront()");
6369
6370 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006371 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6372 Binder.getCallingUid(), "Task to front")) {
6373 return;
6374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 final long origId = Binder.clearCallingIdentity();
6376 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006377 TaskRecord tr = taskForIdLocked(task);
6378 if (tr != null) {
6379 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6380 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006382 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6383 // Caller wants the home activity moved with it. To accomplish this,
6384 // we'll just move the home task to the top first.
6385 mMainStack.moveHomeToFrontLocked();
6386 }
6387 mMainStack.moveTaskToFrontLocked(tr, null);
6388 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006390 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6391 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006393 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6394 mMainStack.mUserLeaving = true;
6395 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006396 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6397 // Caller wants the home activity moved with it. To accomplish this,
6398 // we'll just move the home task to the top first.
6399 mMainStack.moveHomeToFrontLocked();
6400 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006401 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 return;
6403 }
6404 }
6405 } finally {
6406 Binder.restoreCallingIdentity(origId);
6407 }
6408 }
6409 }
6410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 public void moveTaskToBack(int task) {
6412 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6413 "moveTaskToBack()");
6414
6415 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006416 if (mMainStack.mResumedActivity != null
6417 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006418 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6419 Binder.getCallingUid(), "Task to back")) {
6420 return;
6421 }
6422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006424 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 Binder.restoreCallingIdentity(origId);
6426 }
6427 }
6428
6429 /**
6430 * Moves an activity, and all of the other activities within the same task, to the bottom
6431 * of the history stack. The activity's order within the task is unchanged.
6432 *
6433 * @param token A reference to the activity we wish to move
6434 * @param nonRoot If false then this only works if the activity is the root
6435 * of a task; if true it will work for any activity in a task.
6436 * @return Returns true if the move completed, false if not.
6437 */
6438 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006439 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 synchronized(this) {
6441 final long origId = Binder.clearCallingIdentity();
6442 int taskId = getTaskForActivityLocked(token, !nonRoot);
6443 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006444 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 }
6446 Binder.restoreCallingIdentity(origId);
6447 }
6448 return false;
6449 }
6450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 public void moveTaskBackwards(int task) {
6452 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6453 "moveTaskBackwards()");
6454
6455 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006456 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6457 Binder.getCallingUid(), "Task backwards")) {
6458 return;
6459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006460 final long origId = Binder.clearCallingIdentity();
6461 moveTaskBackwardsLocked(task);
6462 Binder.restoreCallingIdentity(origId);
6463 }
6464 }
6465
6466 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006467 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 }
6469
6470 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6471 synchronized(this) {
6472 return getTaskForActivityLocked(token, onlyRoot);
6473 }
6474 }
6475
6476 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006477 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 TaskRecord lastTask = null;
6479 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006480 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006481 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 if (!onlyRoot || lastTask != r.task) {
6483 return r.task.taskId;
6484 }
6485 return -1;
6486 }
6487 lastTask = r.task;
6488 }
6489
6490 return -1;
6491 }
6492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 // =========================================================
6494 // THUMBNAILS
6495 // =========================================================
6496
6497 public void reportThumbnail(IBinder token,
6498 Bitmap thumbnail, CharSequence description) {
6499 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6500 final long origId = Binder.clearCallingIdentity();
6501 sendPendingThumbnail(null, token, thumbnail, description, true);
6502 Binder.restoreCallingIdentity(origId);
6503 }
6504
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006505 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 Bitmap thumbnail, CharSequence description, boolean always) {
6507 TaskRecord task = null;
6508 ArrayList receivers = null;
6509
6510 //System.out.println("Send pending thumbnail: " + r);
6511
6512 synchronized(this) {
6513 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006514 r = mMainStack.isInStackLocked(token);
6515 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 return;
6517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006519 if (thumbnail == null && r.thumbHolder != null) {
6520 thumbnail = r.thumbHolder.lastThumbnail;
6521 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 }
6523 if (thumbnail == null && !always) {
6524 // If there is no thumbnail, and this entry is not actually
6525 // going away, then abort for now and pick up the next
6526 // thumbnail we get.
6527 return;
6528 }
6529 task = r.task;
6530
6531 int N = mPendingThumbnails.size();
6532 int i=0;
6533 while (i<N) {
6534 PendingThumbnailsRecord pr =
6535 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6536 //System.out.println("Looking in " + pr.pendingRecords);
6537 if (pr.pendingRecords.remove(r)) {
6538 if (receivers == null) {
6539 receivers = new ArrayList();
6540 }
6541 receivers.add(pr);
6542 if (pr.pendingRecords.size() == 0) {
6543 pr.finished = true;
6544 mPendingThumbnails.remove(i);
6545 N--;
6546 continue;
6547 }
6548 }
6549 i++;
6550 }
6551 }
6552
6553 if (receivers != null) {
6554 final int N = receivers.size();
6555 for (int i=0; i<N; i++) {
6556 try {
6557 PendingThumbnailsRecord pr =
6558 (PendingThumbnailsRecord)receivers.get(i);
6559 pr.receiver.newThumbnail(
6560 task != null ? task.taskId : -1, thumbnail, description);
6561 if (pr.finished) {
6562 pr.receiver.finished();
6563 }
6564 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006565 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 }
6567 }
6568 }
6569 }
6570
6571 // =========================================================
6572 // CONTENT PROVIDERS
6573 // =========================================================
6574
Jeff Brown10e89712011-07-08 18:52:57 -07006575 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6576 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006578 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006579 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006580 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 } catch (RemoteException ex) {
6582 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006583 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006584 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6585 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 if (providers != null) {
6587 final int N = providers.size();
6588 for (int i=0; i<N; i++) {
6589 ProviderInfo cpi =
6590 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07006591
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006592 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006593 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 if (cpr == null) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006595 cpr = new ContentProviderRecord(cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07006596 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006597 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006598 if (DEBUG_MU)
6599 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006600 app.pubProviders.put(cpi.name, cpr);
6601 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006602 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006603 }
6604 }
6605 return providers;
6606 }
6607
6608 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006609 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006611 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006613 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006614 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 return null;
6616 }
6617 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006618 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006619 == PackageManager.PERMISSION_GRANTED) {
6620 return null;
6621 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006622
6623 PathPermission[] pps = cpi.pathPermissions;
6624 if (pps != null) {
6625 int i = pps.length;
6626 while (i > 0) {
6627 i--;
6628 PathPermission pp = pps[i];
6629 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006630 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006631 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006632 return null;
6633 }
6634 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006635 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006636 == PackageManager.PERMISSION_GRANTED) {
6637 return null;
6638 }
6639 }
6640 }
6641
Dianne Hackbornb424b632010-08-18 15:59:05 -07006642 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6643 if (perms != null) {
6644 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6645 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6646 return null;
6647 }
6648 }
6649 }
6650
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006651 String msg;
6652 if (!cpi.exported) {
6653 msg = "Permission Denial: opening provider " + cpi.name
6654 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6655 + ", uid=" + callingUid + ") that is not exported from uid "
6656 + cpi.applicationInfo.uid;
6657 } else {
6658 msg = "Permission Denial: opening provider " + cpi.name
6659 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6660 + ", uid=" + callingUid + ") requires "
6661 + cpi.readPermission + " or " + cpi.writePermission;
6662 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006663 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006664 return msg;
6665 }
6666
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006667 boolean incProviderCount(ProcessRecord r, ContentProviderRecord cpr) {
6668 if (r != null) {
6669 Integer cnt = r.conProviders.get(cpr);
6670 if (DEBUG_PROVIDER) Slog.v(TAG,
6671 "Adding provider requested by "
6672 + r.processName + " from process "
6673 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6674 + " cnt=" + (cnt == null ? 1 : cnt));
6675 if (cnt == null) {
6676 cpr.clients.add(r);
6677 r.conProviders.put(cpr, new Integer(1));
6678 return true;
6679 } else {
6680 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6681 }
6682 } else {
6683 cpr.externals++;
6684 }
6685 return false;
6686 }
6687
6688 boolean decProviderCount(ProcessRecord r, ContentProviderRecord cpr) {
6689 if (r != null) {
6690 Integer cnt = r.conProviders.get(cpr);
6691 if (DEBUG_PROVIDER) Slog.v(TAG,
6692 "Removing provider requested by "
6693 + r.processName + " from process "
6694 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6695 + " cnt=" + cnt);
6696 if (cnt == null || cnt.intValue() <= 1) {
6697 cpr.clients.remove(r);
6698 r.conProviders.remove(cpr);
6699 return true;
6700 } else {
6701 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6702 }
6703 } else {
6704 cpr.externals++;
6705 }
6706 return false;
6707 }
6708
Amith Yamasani742a6712011-05-04 14:49:28 -07006709 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
6710 String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 ContentProviderRecord cpr;
6712 ProviderInfo cpi = null;
6713
6714 synchronized(this) {
6715 ProcessRecord r = null;
6716 if (caller != null) {
6717 r = getRecordForAppLocked(caller);
6718 if (r == null) {
6719 throw new SecurityException(
6720 "Unable to find app for caller " + caller
6721 + " (pid=" + Binder.getCallingPid()
6722 + ") when getting content provider " + name);
6723 }
6724 }
6725
6726 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006727 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006728 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006729 boolean providerRunning = cpr != null;
6730 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006732 String msg;
6733 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6734 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 }
6736
6737 if (r != null && cpr.canRunHere(r)) {
6738 // This provider has been published or is in the process
6739 // of being published... but it is also allowed to run
6740 // in the caller's process, so don't make a connection
6741 // and just let the caller instantiate its own instance.
6742 if (cpr.provider != null) {
6743 // don't give caller the provider object, it needs
6744 // to make its own.
6745 cpr = new ContentProviderRecord(cpr);
6746 }
6747 return cpr;
6748 }
6749
6750 final long origId = Binder.clearCallingIdentity();
6751
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006752 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006753 // return it right away.
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006754 final boolean countChanged = incProviderCount(r, cpr);
6755 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006756 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006757 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006758 // make sure to count it as being accessed and thus
6759 // back up on the LRU list. This is good because
6760 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006761 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006762 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006763 }
6764
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006765 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006766 if (false) {
6767 if (cpr.name.flattenToShortString().equals(
6768 "com.android.providers.calendar/.CalendarProvider2")) {
6769 Slog.v(TAG, "****************** KILLING "
6770 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006771 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006772 }
6773 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006774 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006775 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6776 // NOTE: there is still a race here where a signal could be
6777 // pending on the process even though we managed to update its
6778 // adj level. Not sure what to do about this, but at least
6779 // the race is now smaller.
6780 if (!success) {
6781 // Uh oh... it looks like the provider's process
6782 // has been killed on us. We need to wait for a new
6783 // process to be started, and make sure its death
6784 // doesn't kill our process.
6785 Slog.i(TAG,
6786 "Existing provider " + cpr.name.flattenToShortString()
6787 + " is crashing; detaching " + r);
6788 boolean lastRef = decProviderCount(r, cpr);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006789 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006790 if (!lastRef) {
6791 // This wasn't the last ref our process had on
6792 // the provider... we have now been killed, bail.
6793 return null;
6794 }
6795 providerRunning = false;
6796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 }
6798
6799 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006802 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006803 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006804 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006805 resolveContentProvider(name,
6806 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006807 } catch (RemoteException ex) {
6808 }
6809 if (cpi == null) {
6810 return null;
6811 }
6812
Amith Yamasani742a6712011-05-04 14:49:28 -07006813 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
6814 Binder.getOrigCallingUser());
6815
Dianne Hackbornb424b632010-08-18 15:59:05 -07006816 String msg;
6817 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6818 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006819 }
6820
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006821 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006822 && !cpi.processName.equals("system")) {
6823 // If this content provider does not run in the system
6824 // process, and the system is not yet ready to run other
6825 // processes, then fail fast instead of hanging.
6826 throw new IllegalArgumentException(
6827 "Attempt to launch content provider before system ready");
6828 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006829
6830 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006831 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006832 final boolean firstClass = cpr == null;
6833 if (firstClass) {
6834 try {
6835 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006836 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837 getApplicationInfo(
6838 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006839 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006841 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006842 + cpi.name);
6843 return null;
6844 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006845 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006846 cpr = new ContentProviderRecord(cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 } catch (RemoteException ex) {
6848 // pm is in same process, this will never happen.
6849 }
6850 }
6851
6852 if (r != null && cpr.canRunHere(r)) {
6853 // If this is a multiprocess provider, then just return its
6854 // info and allow the caller to instantiate it. Only do
6855 // this if the provider is the same user as the caller's
6856 // process, or can run as root (so can be in any process).
6857 return cpr;
6858 }
6859
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006860 if (DEBUG_PROVIDER) {
6861 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006862 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006863 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006864 }
6865
6866 // This is single process, and our app is now connecting to it.
6867 // See if we are already in the process of launching this
6868 // provider.
6869 final int N = mLaunchingProviders.size();
6870 int i;
6871 for (i=0; i<N; i++) {
6872 if (mLaunchingProviders.get(i) == cpr) {
6873 break;
6874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006875 }
6876
6877 // If the provider is not already being launched, then get it
6878 // started.
6879 if (i >= N) {
6880 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006881
6882 try {
6883 // Content provider is now in use, its package can't be stopped.
6884 try {
6885 AppGlobals.getPackageManager().setPackageStoppedState(
6886 cpr.appInfo.packageName, false);
6887 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006888 } catch (IllegalArgumentException e) {
6889 Slog.w(TAG, "Failed trying to unstop package "
6890 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006891 }
6892
6893 ProcessRecord proc = startProcessLocked(cpi.processName,
6894 cpr.appInfo, false, 0, "content provider",
6895 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006896 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006897 if (proc == null) {
6898 Slog.w(TAG, "Unable to launch app "
6899 + cpi.applicationInfo.packageName + "/"
6900 + cpi.applicationInfo.uid + " for provider "
6901 + name + ": process is bad");
6902 return null;
6903 }
6904 cpr.launchingApp = proc;
6905 mLaunchingProviders.add(cpr);
6906 } finally {
6907 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 }
6910
6911 // Make sure the provider is published (the same provider class
6912 // may be published under multiple names).
6913 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006914 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006915 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006916 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006917 incProviderCount(r, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918 }
6919 }
6920
6921 // Wait for the provider to be published...
6922 synchronized (cpr) {
6923 while (cpr.provider == null) {
6924 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006925 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 + cpi.applicationInfo.packageName + "/"
6927 + cpi.applicationInfo.uid + " for provider "
6928 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006929 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006930 cpi.applicationInfo.packageName,
6931 cpi.applicationInfo.uid, name);
6932 return null;
6933 }
6934 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006935 if (DEBUG_MU) {
6936 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6937 + cpr.launchingApp);
6938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006939 cpr.wait();
6940 } catch (InterruptedException ex) {
6941 }
6942 }
6943 }
6944 return cpr;
6945 }
6946
6947 public final ContentProviderHolder getContentProvider(
6948 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006949 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 if (caller == null) {
6951 String msg = "null IApplicationThread when getting content provider "
6952 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006953 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006954 throw new SecurityException(msg);
6955 }
6956
Amith Yamasani742a6712011-05-04 14:49:28 -07006957 ContentProviderHolder contentProvider = getContentProviderImpl(caller, name);
6958 return contentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006959 }
6960
6961 private ContentProviderHolder getContentProviderExternal(String name) {
6962 return getContentProviderImpl(null, name);
6963 }
6964
6965 /**
6966 * Drop a content provider from a ProcessRecord's bookkeeping
6967 * @param cpr
6968 */
6969 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006970 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006971 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006972 int userId = UserId.getUserId(Binder.getCallingUid());
6973 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006974 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006975 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006976 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006977 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 return;
6979 }
6980 final ProcessRecord r = getRecordForAppLocked(caller);
6981 if (r == null) {
6982 throw new SecurityException(
6983 "Unable to find app for caller " + caller +
6984 " when removing content provider " + name);
6985 }
6986 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006987 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006988 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6989 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6990 + r.info.processName + " from process "
6991 + localCpr.appInfo.processName);
6992 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006993 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006994 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006995 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006996 return;
6997 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006998 if (decProviderCount(r, localCpr)) {
6999 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07007000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007002 }
7003 }
7004
7005 private void removeContentProviderExternal(String name) {
7006 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07007007 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
7008 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007009 if(cpr == null) {
7010 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08007011 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007012 return;
7013 }
7014
7015 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07007016 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07007017 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
7018 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007019 localCpr.externals--;
7020 if (localCpr.externals < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007021 Slog.e(TAG, "Externals < 0 for content provider " + localCpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 }
7023 updateOomAdjLocked();
7024 }
7025 }
7026
7027 public final void publishContentProviders(IApplicationThread caller,
7028 List<ContentProviderHolder> providers) {
7029 if (providers == null) {
7030 return;
7031 }
7032
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007033 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007034 synchronized(this) {
7035 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07007036 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007037 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007038 if (r == null) {
7039 throw new SecurityException(
7040 "Unable to find app for caller " + caller
7041 + " (pid=" + Binder.getCallingPid()
7042 + ") when publishing content providers");
7043 }
7044
7045 final long origId = Binder.clearCallingIdentity();
7046
7047 final int N = providers.size();
7048 for (int i=0; i<N; i++) {
7049 ContentProviderHolder src = providers.get(i);
7050 if (src == null || src.info == null || src.provider == null) {
7051 continue;
7052 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07007053 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07007054 if (DEBUG_MU)
7055 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07007057 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07007058 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007059 String names[] = dst.info.authority.split(";");
7060 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07007061 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007062 }
7063
7064 int NL = mLaunchingProviders.size();
7065 int j;
7066 for (j=0; j<NL; j++) {
7067 if (mLaunchingProviders.get(j) == dst) {
7068 mLaunchingProviders.remove(j);
7069 j--;
7070 NL--;
7071 }
7072 }
7073 synchronized (dst) {
7074 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07007075 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007076 dst.notifyAll();
7077 }
7078 updateOomAdjLocked(r);
7079 }
7080 }
7081
7082 Binder.restoreCallingIdentity(origId);
7083 }
7084 }
7085
7086 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07007087 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06007088 synchronized (mSelf) {
7089 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
7090 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08007091 if (providers != null) {
7092 for (int i=providers.size()-1; i>=0; i--) {
7093 ProviderInfo pi = (ProviderInfo)providers.get(i);
7094 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7095 Slog.w(TAG, "Not installing system proc provider " + pi.name
7096 + ": not system .apk");
7097 providers.remove(i);
7098 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08007099 }
7100 }
7101 }
Josh Bartel2ecce342010-02-25 10:55:48 -06007102 if (providers != null) {
7103 mSystemThread.installSystemProviders(providers);
7104 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007105
7106 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01007107
7108 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007109 }
7110
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007111 /**
7112 * Allows app to retrieve the MIME type of a URI without having permission
7113 * to access its content provider.
7114 *
7115 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
7116 *
7117 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
7118 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
7119 */
7120 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007121 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007122 final String name = uri.getAuthority();
7123 final long ident = Binder.clearCallingIdentity();
7124 ContentProviderHolder holder = null;
7125
7126 try {
7127 holder = getContentProviderExternal(name);
7128 if (holder != null) {
7129 return holder.provider.getType(uri);
7130 }
7131 } catch (RemoteException e) {
7132 Log.w(TAG, "Content provider dead retrieving " + uri, e);
7133 return null;
7134 } finally {
7135 if (holder != null) {
7136 removeContentProviderExternal(name);
7137 }
7138 Binder.restoreCallingIdentity(ident);
7139 }
7140
7141 return null;
7142 }
7143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007144 // =========================================================
7145 // GLOBAL MANAGEMENT
7146 // =========================================================
7147
7148 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007149 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007150 String proc = customProcess != null ? customProcess : info.processName;
7151 BatteryStatsImpl.Uid.Proc ps = null;
7152 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007153 int uid = info.uid;
7154 if (isolated) {
7155 int userId = UserId.getUserId(uid);
7156 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
7157 uid = 0;
7158 while (true) {
7159 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
7160 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
7161 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
7162 }
7163 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
7164 mNextIsolatedProcessUid++;
7165 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
7166 // No process for this uid, use it.
7167 break;
7168 }
7169 stepsLeft--;
7170 if (stepsLeft <= 0) {
7171 return null;
7172 }
7173 }
7174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007175 synchronized (stats) {
7176 ps = stats.getProcessStatsLocked(info.uid, proc);
7177 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007178 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007179 }
7180
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007181 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
7182 ProcessRecord app;
7183 if (!isolated) {
7184 app = getProcessRecordLocked(info.processName, info.uid);
7185 } else {
7186 app = null;
7187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007188
7189 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007190 app = newProcessRecordLocked(null, info, null, isolated);
7191 mProcessNames.put(info.processName, app.uid, app);
7192 if (isolated) {
7193 mIsolatedProcesses.put(app.uid, app);
7194 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007195 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 }
7197
Dianne Hackborne7f97212011-02-24 14:40:20 -08007198 // This package really, really can not be stopped.
7199 try {
7200 AppGlobals.getPackageManager().setPackageStoppedState(
7201 info.packageName, false);
7202 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007203 } catch (IllegalArgumentException e) {
7204 Slog.w(TAG, "Failed trying to unstop package "
7205 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007206 }
7207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7209 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7210 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007211 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212 }
7213 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7214 mPersistentStartingProcesses.add(app);
7215 startProcessLocked(app, "added application", app.processName);
7216 }
7217
7218 return app;
7219 }
7220
7221 public void unhandledBack() {
7222 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7223 "unhandledBack()");
7224
7225 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007226 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007227 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007228 TAG, "Performing unhandledBack(): stack size = " + count);
7229 if (count > 1) {
7230 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007231 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007232 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
7233 Binder.restoreCallingIdentity(origId);
7234 }
7235 }
7236 }
7237
7238 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007239 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007240 String name = uri.getAuthority();
7241 ContentProviderHolder cph = getContentProviderExternal(name);
7242 ParcelFileDescriptor pfd = null;
7243 if (cph != null) {
7244 // We record the binder invoker's uid in thread-local storage before
7245 // going to the content provider to open the file. Later, in the code
7246 // that handles all permissions checks, we look for this uid and use
7247 // that rather than the Activity Manager's own uid. The effect is that
7248 // we do the check against the caller's permissions even though it looks
7249 // to the content provider like the Activity Manager itself is making
7250 // the request.
7251 sCallerIdentity.set(new Identity(
7252 Binder.getCallingPid(), Binder.getCallingUid()));
7253 try {
7254 pfd = cph.provider.openFile(uri, "r");
7255 } catch (FileNotFoundException e) {
7256 // do nothing; pfd will be returned null
7257 } finally {
7258 // Ensure that whatever happens, we clean up the identity state
7259 sCallerIdentity.remove();
7260 }
7261
7262 // We've got the fd now, so we're done with the provider.
7263 removeContentProviderExternal(name);
7264 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007265 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007266 }
7267 return pfd;
7268 }
7269
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007270 // Actually is sleeping or shutting down or whatever else in the future
7271 // is an inactive state.
7272 public boolean isSleeping() {
7273 return mSleeping || mShuttingDown;
7274 }
7275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007276 public void goingToSleep() {
7277 synchronized(this) {
7278 mSleeping = true;
7279 mWindowManager.setEventDispatching(false);
7280
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007281 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007282
7283 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07007284 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007285 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7286 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07007287 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288 }
7289 }
7290
Dianne Hackborn55280a92009-05-07 15:53:46 -07007291 public boolean shutdown(int timeout) {
7292 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7293 != PackageManager.PERMISSION_GRANTED) {
7294 throw new SecurityException("Requires permission "
7295 + android.Manifest.permission.SHUTDOWN);
7296 }
7297
7298 boolean timedout = false;
7299
7300 synchronized(this) {
7301 mShuttingDown = true;
7302 mWindowManager.setEventDispatching(false);
7303
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007304 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007305 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007306 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007307 while (mMainStack.mResumedActivity != null
Dianne Hackborncbb722e2012-02-07 18:33:49 -08007308 || mMainStack.mPausingActivities.size() > 0) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007309 long delay = endTime - System.currentTimeMillis();
7310 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007311 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007312 timedout = true;
7313 break;
7314 }
7315 try {
7316 this.wait();
7317 } catch (InterruptedException e) {
7318 }
7319 }
7320 }
7321 }
7322
7323 mUsageStatsService.shutdown();
7324 mBatteryStatsService.shutdown();
7325
7326 return timedout;
7327 }
7328
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007329 public final void activitySlept(IBinder token) {
7330 if (localLOGV) Slog.v(
7331 TAG, "Activity slept: token=" + token);
7332
7333 ActivityRecord r = null;
7334
7335 final long origId = Binder.clearCallingIdentity();
7336
7337 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007338 r = mMainStack.isInStackLocked(token);
7339 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007340 mMainStack.activitySleptLocked(r);
7341 }
7342 }
7343
7344 Binder.restoreCallingIdentity(origId);
7345 }
7346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007347 public void wakingUp() {
7348 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007349 mWindowManager.setEventDispatching(true);
7350 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007351 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007352 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007353 }
7354 }
7355
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007356 public void stopAppSwitches() {
7357 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7358 != PackageManager.PERMISSION_GRANTED) {
7359 throw new SecurityException("Requires permission "
7360 + android.Manifest.permission.STOP_APP_SWITCHES);
7361 }
7362
7363 synchronized(this) {
7364 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7365 + APP_SWITCH_DELAY_TIME;
7366 mDidAppSwitch = false;
7367 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7368 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7369 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7370 }
7371 }
7372
7373 public void resumeAppSwitches() {
7374 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7375 != PackageManager.PERMISSION_GRANTED) {
7376 throw new SecurityException("Requires permission "
7377 + android.Manifest.permission.STOP_APP_SWITCHES);
7378 }
7379
7380 synchronized(this) {
7381 // Note that we don't execute any pending app switches... we will
7382 // let those wait until either the timeout, or the next start
7383 // activity request.
7384 mAppSwitchesAllowedTime = 0;
7385 }
7386 }
7387
7388 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7389 String name) {
7390 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7391 return true;
7392 }
7393
7394 final int perm = checkComponentPermission(
7395 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007396 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007397 if (perm == PackageManager.PERMISSION_GRANTED) {
7398 return true;
7399 }
7400
Joe Onorato8a9b2202010-02-26 18:56:32 -08007401 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007402 return false;
7403 }
7404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007405 public void setDebugApp(String packageName, boolean waitForDebugger,
7406 boolean persistent) {
7407 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7408 "setDebugApp()");
7409
7410 // Note that this is not really thread safe if there are multiple
7411 // callers into it at the same time, but that's not a situation we
7412 // care about.
7413 if (persistent) {
7414 final ContentResolver resolver = mContext.getContentResolver();
7415 Settings.System.putString(
7416 resolver, Settings.System.DEBUG_APP,
7417 packageName);
7418 Settings.System.putInt(
7419 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7420 waitForDebugger ? 1 : 0);
7421 }
7422
7423 synchronized (this) {
7424 if (!persistent) {
7425 mOrigDebugApp = mDebugApp;
7426 mOrigWaitForDebugger = mWaitForDebugger;
7427 }
7428 mDebugApp = packageName;
7429 mWaitForDebugger = waitForDebugger;
7430 mDebugTransient = !persistent;
7431 if (packageName != null) {
7432 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07007433 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007434 Binder.restoreCallingIdentity(origId);
7435 }
7436 }
7437 }
7438
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007439 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7440 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7441 synchronized (this) {
7442 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7443 if (!isDebuggable) {
7444 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7445 throw new SecurityException("Process not debuggable: " + app.packageName);
7446 }
7447 }
7448 mProfileApp = processName;
7449 mProfileFile = profileFile;
7450 if (mProfileFd != null) {
7451 try {
7452 mProfileFd.close();
7453 } catch (IOException e) {
7454 }
7455 mProfileFd = null;
7456 }
7457 mProfileFd = profileFd;
7458 mProfileType = 0;
7459 mAutoStopProfiler = autoStopProfiler;
7460 }
7461 }
7462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007463 public void setAlwaysFinish(boolean enabled) {
7464 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7465 "setAlwaysFinish()");
7466
7467 Settings.System.putInt(
7468 mContext.getContentResolver(),
7469 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7470
7471 synchronized (this) {
7472 mAlwaysFinishActivities = enabled;
7473 }
7474 }
7475
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007476 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007477 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007478 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007479 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007480 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007481 }
7482 }
7483
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007484 public boolean isUserAMonkey() {
7485 // For now the fact that there is a controller implies
7486 // we have a monkey.
7487 synchronized (this) {
7488 return mController != null;
7489 }
7490 }
7491
Jeff Sharkeya4620792011-05-20 15:29:23 -07007492 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007493 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7494 "registerProcessObserver()");
7495 synchronized (this) {
7496 mProcessObservers.register(observer);
7497 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007498 }
7499
7500 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007501 synchronized (this) {
7502 mProcessObservers.unregister(observer);
7503 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007504 }
7505
Daniel Sandler69a48172010-06-23 16:29:36 -04007506 public void setImmersive(IBinder token, boolean immersive) {
7507 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007508 ActivityRecord r = mMainStack.isInStackLocked(token);
7509 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007510 throw new IllegalArgumentException();
7511 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007512 r.immersive = immersive;
7513 }
7514 }
7515
7516 public boolean isImmersive(IBinder token) {
7517 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007518 ActivityRecord r = mMainStack.isInStackLocked(token);
7519 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007520 throw new IllegalArgumentException();
7521 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007522 return r.immersive;
7523 }
7524 }
7525
7526 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007527 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007528 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007529 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007530 return (r != null) ? r.immersive : false;
7531 }
7532 }
7533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007534 public final void enterSafeMode() {
7535 synchronized(this) {
7536 // It only makes sense to do this before the system is ready
7537 // and started launching other packages.
7538 if (!mSystemReady) {
7539 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007540 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007541 } catch (RemoteException e) {
7542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007543 }
7544 }
7545 }
7546
Jeff Brownb09abc12011-01-13 21:08:27 -08007547 public final void showSafeModeOverlay() {
7548 View v = LayoutInflater.from(mContext).inflate(
7549 com.android.internal.R.layout.safe_mode, null);
7550 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7551 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7552 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7553 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7554 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7555 lp.format = v.getBackground().getOpacity();
7556 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7557 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7558 ((WindowManager)mContext.getSystemService(
7559 Context.WINDOW_SERVICE)).addView(v, lp);
7560 }
7561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 public void noteWakeupAlarm(IIntentSender sender) {
7563 if (!(sender instanceof PendingIntentRecord)) {
7564 return;
7565 }
7566 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7567 synchronized (stats) {
7568 if (mBatteryStatsService.isOnBattery()) {
7569 mBatteryStatsService.enforceCallingPermission();
7570 PendingIntentRecord rec = (PendingIntentRecord)sender;
7571 int MY_UID = Binder.getCallingUid();
7572 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7573 BatteryStatsImpl.Uid.Pkg pkg =
7574 stats.getPackageStatsLocked(uid, rec.key.packageName);
7575 pkg.incWakeupsLocked();
7576 }
7577 }
7578 }
7579
Dianne Hackborn64825172011-03-02 21:32:58 -08007580 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007582 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007584 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 // XXX Note: don't acquire main activity lock here, because the window
7586 // manager calls in with its locks held.
7587
7588 boolean killed = false;
7589 synchronized (mPidsSelfLocked) {
7590 int[] types = new int[pids.length];
7591 int worstType = 0;
7592 for (int i=0; i<pids.length; i++) {
7593 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7594 if (proc != null) {
7595 int type = proc.setAdj;
7596 types[i] = type;
7597 if (type > worstType) {
7598 worstType = type;
7599 }
7600 }
7601 }
7602
Dianne Hackborn64825172011-03-02 21:32:58 -08007603 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007604 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007605 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7606 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007607 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007609
7610 // If this is not a secure call, don't let it kill processes that
7611 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007612 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7613 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007614 }
7615
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007616 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007617 for (int i=0; i<pids.length; i++) {
7618 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7619 if (proc == null) {
7620 continue;
7621 }
7622 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007623 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007624 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007625 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7626 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007628 proc.killedBackground = true;
7629 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007630 }
7631 }
7632 }
7633 return killed;
7634 }
7635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 public final void startRunning(String pkg, String cls, String action,
7637 String data) {
7638 synchronized(this) {
7639 if (mStartRunning) {
7640 return;
7641 }
7642 mStartRunning = true;
7643 mTopComponent = pkg != null && cls != null
7644 ? new ComponentName(pkg, cls) : null;
7645 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7646 mTopData = data;
7647 if (!mSystemReady) {
7648 return;
7649 }
7650 }
7651
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007652 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653 }
7654
7655 private void retrieveSettings() {
7656 final ContentResolver resolver = mContext.getContentResolver();
7657 String debugApp = Settings.System.getString(
7658 resolver, Settings.System.DEBUG_APP);
7659 boolean waitForDebugger = Settings.System.getInt(
7660 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7661 boolean alwaysFinishActivities = Settings.System.getInt(
7662 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7663
7664 Configuration configuration = new Configuration();
7665 Settings.System.getConfiguration(resolver, configuration);
7666
7667 synchronized (this) {
7668 mDebugApp = mOrigDebugApp = debugApp;
7669 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7670 mAlwaysFinishActivities = alwaysFinishActivities;
7671 // This happens before any activities are started, so we can
7672 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007673 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007674 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 }
7676 }
7677
7678 public boolean testIsSystemReady() {
7679 // no need to synchronize(this) just to read & return the value
7680 return mSystemReady;
7681 }
7682
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007683 private static File getCalledPreBootReceiversFile() {
7684 File dataDir = Environment.getDataDirectory();
7685 File systemDir = new File(dataDir, "system");
7686 File fname = new File(systemDir, "called_pre_boots.dat");
7687 return fname;
7688 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007689
7690 static final int LAST_DONE_VERSION = 10000;
7691
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007692 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7693 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7694 File file = getCalledPreBootReceiversFile();
7695 FileInputStream fis = null;
7696 try {
7697 fis = new FileInputStream(file);
7698 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007699 int fvers = dis.readInt();
7700 if (fvers == LAST_DONE_VERSION) {
7701 String vers = dis.readUTF();
7702 String codename = dis.readUTF();
7703 String build = dis.readUTF();
7704 if (android.os.Build.VERSION.RELEASE.equals(vers)
7705 && android.os.Build.VERSION.CODENAME.equals(codename)
7706 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7707 int num = dis.readInt();
7708 while (num > 0) {
7709 num--;
7710 String pkg = dis.readUTF();
7711 String cls = dis.readUTF();
7712 lastDoneReceivers.add(new ComponentName(pkg, cls));
7713 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007714 }
7715 }
7716 } catch (FileNotFoundException e) {
7717 } catch (IOException e) {
7718 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7719 } finally {
7720 if (fis != null) {
7721 try {
7722 fis.close();
7723 } catch (IOException e) {
7724 }
7725 }
7726 }
7727 return lastDoneReceivers;
7728 }
7729
7730 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7731 File file = getCalledPreBootReceiversFile();
7732 FileOutputStream fos = null;
7733 DataOutputStream dos = null;
7734 try {
7735 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7736 fos = new FileOutputStream(file);
7737 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007738 dos.writeInt(LAST_DONE_VERSION);
7739 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007740 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007741 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007742 dos.writeInt(list.size());
7743 for (int i=0; i<list.size(); i++) {
7744 dos.writeUTF(list.get(i).getPackageName());
7745 dos.writeUTF(list.get(i).getClassName());
7746 }
7747 } catch (IOException e) {
7748 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7749 file.delete();
7750 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007751 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007752 if (dos != null) {
7753 try {
7754 dos.close();
7755 } catch (IOException e) {
7756 // TODO Auto-generated catch block
7757 e.printStackTrace();
7758 }
7759 }
7760 }
7761 }
7762
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007763 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 synchronized(this) {
7765 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007766 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007767 return;
7768 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007769
7770 // Check to see if there are any update receivers to run.
7771 if (!mDidUpdate) {
7772 if (mWaitingUpdate) {
7773 return;
7774 }
7775 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7776 List<ResolveInfo> ris = null;
7777 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007778 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007779 intent, null, 0);
7780 } catch (RemoteException e) {
7781 }
7782 if (ris != null) {
7783 for (int i=ris.size()-1; i>=0; i--) {
7784 if ((ris.get(i).activityInfo.applicationInfo.flags
7785 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7786 ris.remove(i);
7787 }
7788 }
7789 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007790
7791 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7792
7793 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007794 for (int i=0; i<ris.size(); i++) {
7795 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007796 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7797 if (lastDoneReceivers.contains(comp)) {
7798 ris.remove(i);
7799 i--;
7800 }
7801 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007802
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007803 for (int i=0; i<ris.size(); i++) {
7804 ActivityInfo ai = ris.get(i).activityInfo;
7805 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7806 doneReceivers.add(comp);
7807 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007808 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007809 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007810 finisher = new IIntentReceiver.Stub() {
7811 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007812 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007813 boolean sticky) {
7814 // The raw IIntentReceiver interface is called
7815 // with the AM lock held, so redispatch to
7816 // execute our code without the lock.
7817 mHandler.post(new Runnable() {
7818 public void run() {
7819 synchronized (ActivityManagerService.this) {
7820 mDidUpdate = true;
7821 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007822 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007823 showBootMessage(mContext.getText(
7824 R.string.android_upgrading_complete),
7825 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007826 systemReady(goingCallback);
7827 }
7828 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007829 }
7830 };
7831 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007832 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007833 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007834 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007835 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7836 Process.SYSTEM_UID);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007837 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007838 mWaitingUpdate = true;
7839 }
7840 }
7841 }
7842 if (mWaitingUpdate) {
7843 return;
7844 }
7845 mDidUpdate = true;
7846 }
7847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 mSystemReady = true;
7849 if (!mStartRunning) {
7850 return;
7851 }
7852 }
7853
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007854 ArrayList<ProcessRecord> procsToKill = null;
7855 synchronized(mPidsSelfLocked) {
7856 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7857 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7858 if (!isAllowedWhileBooting(proc.info)){
7859 if (procsToKill == null) {
7860 procsToKill = new ArrayList<ProcessRecord>();
7861 }
7862 procsToKill.add(proc);
7863 }
7864 }
7865 }
7866
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007867 synchronized(this) {
7868 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007869 for (int i=procsToKill.size()-1; i>=0; i--) {
7870 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007871 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007872 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007873 }
7874 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007875
7876 // Now that we have cleaned up any update processes, we
7877 // are ready to start launching real processes and know that
7878 // we won't trample on them any more.
7879 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007880 }
7881
Joe Onorato8a9b2202010-02-26 18:56:32 -08007882 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007883 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 SystemClock.uptimeMillis());
7885
7886 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007887 // Make sure we have no pre-ready processes sitting around.
7888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7890 ResolveInfo ri = mContext.getPackageManager()
7891 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007892 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007893 CharSequence errorMsg = null;
7894 if (ri != null) {
7895 ActivityInfo ai = ri.activityInfo;
7896 ApplicationInfo app = ai.applicationInfo;
7897 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7898 mTopAction = Intent.ACTION_FACTORY_TEST;
7899 mTopData = null;
7900 mTopComponent = new ComponentName(app.packageName,
7901 ai.name);
7902 } else {
7903 errorMsg = mContext.getResources().getText(
7904 com.android.internal.R.string.factorytest_not_system);
7905 }
7906 } else {
7907 errorMsg = mContext.getResources().getText(
7908 com.android.internal.R.string.factorytest_no_action);
7909 }
7910 if (errorMsg != null) {
7911 mTopAction = null;
7912 mTopData = null;
7913 mTopComponent = null;
7914 Message msg = Message.obtain();
7915 msg.what = SHOW_FACTORY_ERROR_MSG;
7916 msg.getData().putCharSequence("msg", errorMsg);
7917 mHandler.sendMessage(msg);
7918 }
7919 }
7920 }
7921
7922 retrieveSettings();
7923
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007924 if (goingCallback != null) goingCallback.run();
7925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007926 synchronized (this) {
7927 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7928 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007929 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007930 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007931 if (apps != null) {
7932 int N = apps.size();
7933 int i;
7934 for (i=0; i<N; i++) {
7935 ApplicationInfo info
7936 = (ApplicationInfo)apps.get(i);
7937 if (info != null &&
7938 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007939 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007940 }
7941 }
7942 }
7943 } catch (RemoteException ex) {
7944 // pm is in same process, this will never happen.
7945 }
7946 }
7947
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007948 // Start up initial activity.
7949 mBooting = true;
7950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007951 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007952 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 Message msg = Message.obtain();
7954 msg.what = SHOW_UID_ERROR_MSG;
7955 mHandler.sendMessage(msg);
7956 }
7957 } catch (RemoteException e) {
7958 }
7959
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007960 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007961 }
7962 }
7963
Dan Egnorb7f03672009-12-09 16:22:32 -08007964 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007965 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007967 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007968 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007969 startAppProblemLocked(app);
7970 app.stopFreezingAllLocked();
7971 return handleAppCrashLocked(app);
7972 }
7973
Dan Egnorb7f03672009-12-09 16:22:32 -08007974 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007975 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007976 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007977 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007978 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7979 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 startAppProblemLocked(app);
7981 app.stopFreezingAllLocked();
7982 }
7983
7984 /**
7985 * Generate a process error record, suitable for attachment to a ProcessRecord.
7986 *
7987 * @param app The ProcessRecord in which the error occurred.
7988 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7989 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007990 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 * @param shortMsg Short message describing the crash.
7992 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007993 * @param stackTrace Full crash stack trace, may be null.
7994 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007995 * @return Returns a fully-formed AppErrorStateInfo record.
7996 */
7997 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007998 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007999 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08008000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008001 report.condition = condition;
8002 report.processName = app.processName;
8003 report.pid = app.pid;
8004 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08008005 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008006 report.shortMsg = shortMsg;
8007 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08008008 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009
8010 return report;
8011 }
8012
Dan Egnor42471dd2010-01-07 17:25:22 -08008013 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 synchronized (this) {
8015 app.crashing = false;
8016 app.crashingReport = null;
8017 app.notResponding = false;
8018 app.notRespondingReport = null;
8019 if (app.anrDialog == fromDialog) {
8020 app.anrDialog = null;
8021 }
8022 if (app.waitDialog == fromDialog) {
8023 app.waitDialog = null;
8024 }
8025 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008026 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008027 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07008028 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
8029 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008030 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008032 }
8033 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008034
Dan Egnorb7f03672009-12-09 16:22:32 -08008035 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008036 long now = SystemClock.uptimeMillis();
8037
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008038 Long crashTime;
8039 if (!app.isolated) {
8040 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
8041 } else {
8042 crashTime = null;
8043 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07008044 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008045 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008046 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008047 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008048 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008049 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008050 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
8051 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008052 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008053 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008054 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008055 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008056 }
8057 }
8058 if (!app.persistent) {
8059 // We don't want to start this process again until the user
8060 // explicitly does so... but for persistent process, we really
8061 // need to keep it running. If a persistent process is actually
8062 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008063 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008065 if (!app.isolated) {
8066 // XXX We don't have a way to mark isolated processes
8067 // as bad, since they don't have a peristent identity.
8068 mBadProcesses.put(app.info.processName, app.uid, now);
8069 mProcessCrashTimes.remove(app.info.processName, app.uid);
8070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008071 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008072 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008073 // Don't let services in this process be restarted and potentially
8074 // annoy the user repeatedly. Unless it is persistent, since those
8075 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008076 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008077 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008078 return false;
8079 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008080 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008081 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008082 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008083 if (r.app == app) {
8084 // If the top running activity is from this crashing
8085 // process, then terminate it to avoid getting in a loop.
8086 Slog.w(TAG, " Force finishing activity "
8087 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008088 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008089 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008090 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08008091 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008092 // stopped, to avoid a situation where one will get
8093 // re-start our crashing activity once it gets resumed again.
8094 index--;
8095 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008096 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008097 if (r.state == ActivityState.RESUMED
8098 || r.state == ActivityState.PAUSING
8099 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008100 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008101 Slog.w(TAG, " Force finishing activity "
8102 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008103 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008104 Activity.RESULT_CANCELED, null, "crashed");
8105 }
8106 }
8107 }
8108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109 }
8110
8111 // Bump up the crash count of any services currently running in the proc.
8112 if (app.services.size() != 0) {
8113 // Any services running in the application need to be placed
8114 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008115 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008116 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008117 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118 sr.crashCount++;
8119 }
8120 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008121
8122 // If the crashing process is what we consider to be the "home process" and it has been
8123 // replaced by a third-party app, clear the package preferred activities from packages
8124 // with a home activity running in the process to prevent a repeatedly crashing app
8125 // from blocking the user to manually clear the list.
8126 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8127 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8128 Iterator it = mHomeProcess.activities.iterator();
8129 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008130 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008131 if (r.isHomeActivity) {
8132 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8133 try {
8134 ActivityThread.getPackageManager()
8135 .clearPackagePreferredActivities(r.packageName);
8136 } catch (RemoteException c) {
8137 // pm is in same process, this will never happen.
8138 }
8139 }
8140 }
8141 }
8142
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008143 if (!app.isolated) {
8144 // XXX Can't keep track of crash times for isolated processes,
8145 // because they don't have a perisistent identity.
8146 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8147 }
8148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 return true;
8150 }
8151
8152 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008153 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8154 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008155 skipCurrentReceiverLocked(app);
8156 }
8157
8158 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008159 for (BroadcastQueue queue : mBroadcastQueues) {
8160 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008161 }
8162 }
8163
Dan Egnor60d87622009-12-16 16:32:58 -08008164 /**
8165 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8166 * The application process will exit immediately after this call returns.
8167 * @param app object of the crashing app, null for the system server
8168 * @param crashInfo describing the exception
8169 */
8170 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008171 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008172 final String processName = app == null ? "system_server"
8173 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008174
8175 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008176 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008177 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008178 crashInfo.exceptionClassName,
8179 crashInfo.exceptionMessage,
8180 crashInfo.throwFileName,
8181 crashInfo.throwLineNumber);
8182
Jeff Sharkeya353d262011-10-28 11:12:06 -07008183 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008184
8185 crashApplication(r, crashInfo);
8186 }
8187
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008188 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008189 IBinder app,
8190 int violationMask,
8191 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008192 ProcessRecord r = findAppProcess(app, "StrictMode");
8193 if (r == null) {
8194 return;
8195 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008196
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008197 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008198 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008199 boolean logIt = true;
8200 synchronized (mAlreadyLoggedViolatedStacks) {
8201 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8202 logIt = false;
8203 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008204 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008205 // the relative pain numbers, without logging all
8206 // the stack traces repeatedly. We'd want to do
8207 // likewise in the client code, which also does
8208 // dup suppression, before the Binder call.
8209 } else {
8210 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8211 mAlreadyLoggedViolatedStacks.clear();
8212 }
8213 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8214 }
8215 }
8216 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008217 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008218 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008219 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008220
8221 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8222 AppErrorResult result = new AppErrorResult();
8223 synchronized (this) {
8224 final long origId = Binder.clearCallingIdentity();
8225
8226 Message msg = Message.obtain();
8227 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8228 HashMap<String, Object> data = new HashMap<String, Object>();
8229 data.put("result", result);
8230 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008231 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008232 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008233 msg.obj = data;
8234 mHandler.sendMessage(msg);
8235
8236 Binder.restoreCallingIdentity(origId);
8237 }
8238 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008239 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008240 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008241 }
8242
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008243 // Depending on the policy in effect, there could be a bunch of
8244 // these in quick succession so we try to batch these together to
8245 // minimize disk writes, number of dropbox entries, and maximize
8246 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008247 private void logStrictModeViolationToDropBox(
8248 ProcessRecord process,
8249 StrictMode.ViolationInfo info) {
8250 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008251 return;
8252 }
8253 final boolean isSystemApp = process == null ||
8254 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8255 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008256 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008257 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8258 final DropBoxManager dbox = (DropBoxManager)
8259 mContext.getSystemService(Context.DROPBOX_SERVICE);
8260
8261 // Exit early if the dropbox isn't configured to accept this report type.
8262 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8263
8264 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008265 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008266 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8267 synchronized (sb) {
8268 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008269 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008270 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8271 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008272 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8273 if (info.violationNumThisLoop != 0) {
8274 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8275 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008276 if (info.numAnimationsRunning != 0) {
8277 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8278 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008279 if (info.broadcastIntentAction != null) {
8280 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8281 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008282 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008283 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008284 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008285 if (info.numInstances != -1) {
8286 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8287 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008288 if (info.tags != null) {
8289 for (String tag : info.tags) {
8290 sb.append("Span-Tag: ").append(tag).append("\n");
8291 }
8292 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008293 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008294 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8295 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008296 }
8297 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008298
8299 // Only buffer up to ~64k. Various logging bits truncate
8300 // things at 128k.
8301 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008302 }
8303
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008304 // Flush immediately if the buffer's grown too large, or this
8305 // is a non-system app. Non-system apps are isolated with a
8306 // different tag & policy and not batched.
8307 //
8308 // Batching is useful during internal testing with
8309 // StrictMode settings turned up high. Without batching,
8310 // thousands of separate files could be created on boot.
8311 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008312 new Thread("Error dump: " + dropboxTag) {
8313 @Override
8314 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008315 String report;
8316 synchronized (sb) {
8317 report = sb.toString();
8318 sb.delete(0, sb.length());
8319 sb.trimToSize();
8320 }
8321 if (report.length() != 0) {
8322 dbox.addText(dropboxTag, report);
8323 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008324 }
8325 }.start();
8326 return;
8327 }
8328
8329 // System app batching:
8330 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008331 // An existing dropbox-writing thread is outstanding, so
8332 // we don't need to start it up. The existing thread will
8333 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008334 return;
8335 }
8336
8337 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8338 // (After this point, we shouldn't access AMS internal data structures.)
8339 new Thread("Error dump: " + dropboxTag) {
8340 @Override
8341 public void run() {
8342 // 5 second sleep to let stacks arrive and be batched together
8343 try {
8344 Thread.sleep(5000); // 5 seconds
8345 } catch (InterruptedException e) {}
8346
8347 String errorReport;
8348 synchronized (mStrictModeBuffer) {
8349 errorReport = mStrictModeBuffer.toString();
8350 if (errorReport.length() == 0) {
8351 return;
8352 }
8353 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8354 mStrictModeBuffer.trimToSize();
8355 }
8356 dbox.addText(dropboxTag, errorReport);
8357 }
8358 }.start();
8359 }
8360
Dan Egnor60d87622009-12-16 16:32:58 -08008361 /**
8362 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8363 * @param app object of the crashing app, null for the system server
8364 * @param tag reported by the caller
8365 * @param crashInfo describing the context of the error
8366 * @return true if the process should exit immediately (WTF is fatal)
8367 */
8368 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008369 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008370 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008371 final String processName = app == null ? "system_server"
8372 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008373
8374 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008375 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008376 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008377 tag, crashInfo.exceptionMessage);
8378
Jeff Sharkeya353d262011-10-28 11:12:06 -07008379 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008380
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008381 if (r != null && r.pid != Process.myPid() &&
8382 Settings.Secure.getInt(mContext.getContentResolver(),
8383 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008384 crashApplication(r, crashInfo);
8385 return true;
8386 } else {
8387 return false;
8388 }
8389 }
8390
8391 /**
8392 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8393 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8394 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008395 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008396 if (app == null) {
8397 return null;
8398 }
8399
8400 synchronized (this) {
8401 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8402 final int NA = apps.size();
8403 for (int ia=0; ia<NA; ia++) {
8404 ProcessRecord p = apps.valueAt(ia);
8405 if (p.thread != null && p.thread.asBinder() == app) {
8406 return p;
8407 }
8408 }
8409 }
8410
Dianne Hackborncb44d962011-03-10 17:02:27 -08008411 Slog.w(TAG, "Can't find mystery application for " + reason
8412 + " from pid=" + Binder.getCallingPid()
8413 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008414 return null;
8415 }
8416 }
8417
8418 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008419 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8420 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008421 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008422 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8423 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008424 // Watchdog thread ends up invoking this function (with
8425 // a null ProcessRecord) to add the stack file to dropbox.
8426 // Do not acquire a lock on this (am) in such cases, as it
8427 // could cause a potential deadlock, if and when watchdog
8428 // is invoked due to unavailability of lock on am and it
8429 // would prevent watchdog from killing system_server.
8430 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008431 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008432 return;
8433 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008434 // Note: ProcessRecord 'process' is guarded by the service
8435 // instance. (notably process.pkgList, which could otherwise change
8436 // concurrently during execution of this method)
8437 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008438 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008439 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008440 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008441 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8442 for (String pkg : process.pkgList) {
8443 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008444 try {
Dan Egnora455d192010-03-12 08:52:28 -08008445 PackageInfo pi = pm.getPackageInfo(pkg, 0);
8446 if (pi != null) {
8447 sb.append(" v").append(pi.versionCode);
8448 if (pi.versionName != null) {
8449 sb.append(" (").append(pi.versionName).append(")");
8450 }
8451 }
8452 } catch (RemoteException e) {
8453 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008454 }
Dan Egnora455d192010-03-12 08:52:28 -08008455 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008456 }
Dan Egnora455d192010-03-12 08:52:28 -08008457 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008458 }
8459
8460 private static String processClass(ProcessRecord process) {
8461 if (process == null || process.pid == MY_PID) {
8462 return "system_server";
8463 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8464 return "system_app";
8465 } else {
8466 return "data_app";
8467 }
8468 }
8469
8470 /**
8471 * Write a description of an error (crash, WTF, ANR) to the drop box.
8472 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8473 * @param process which caused the error, null means the system server
8474 * @param activity which triggered the error, null if unknown
8475 * @param parent activity related to the error, null if unknown
8476 * @param subject line related to the error, null if absent
8477 * @param report in long form describing the error, null if absent
8478 * @param logFile to include in the report, null if none
8479 * @param crashInfo giving an application stack trace, null if absent
8480 */
8481 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008482 ProcessRecord process, String processName, ActivityRecord activity,
8483 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008484 final String report, final File logFile,
8485 final ApplicationErrorReport.CrashInfo crashInfo) {
8486 // NOTE -- this must never acquire the ActivityManagerService lock,
8487 // otherwise the watchdog may be prevented from resetting the system.
8488
8489 final String dropboxTag = processClass(process) + "_" + eventType;
8490 final DropBoxManager dbox = (DropBoxManager)
8491 mContext.getSystemService(Context.DROPBOX_SERVICE);
8492
8493 // Exit early if the dropbox isn't configured to accept this report type.
8494 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8495
8496 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008497 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008498 if (activity != null) {
8499 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8500 }
8501 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8502 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8503 }
8504 if (parent != null && parent != activity) {
8505 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8506 }
8507 if (subject != null) {
8508 sb.append("Subject: ").append(subject).append("\n");
8509 }
8510 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008511 if (Debug.isDebuggerConnected()) {
8512 sb.append("Debugger: Connected\n");
8513 }
Dan Egnora455d192010-03-12 08:52:28 -08008514 sb.append("\n");
8515
8516 // Do the rest in a worker thread to avoid blocking the caller on I/O
8517 // (After this point, we shouldn't access AMS internal data structures.)
8518 Thread worker = new Thread("Error dump: " + dropboxTag) {
8519 @Override
8520 public void run() {
8521 if (report != null) {
8522 sb.append(report);
8523 }
8524 if (logFile != null) {
8525 try {
8526 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8527 } catch (IOException e) {
8528 Slog.e(TAG, "Error reading " + logFile, e);
8529 }
8530 }
8531 if (crashInfo != null && crashInfo.stackTrace != null) {
8532 sb.append(crashInfo.stackTrace);
8533 }
8534
8535 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8536 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8537 if (lines > 0) {
8538 sb.append("\n");
8539
8540 // Merge several logcat streams, and take the last N lines
8541 InputStreamReader input = null;
8542 try {
8543 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8544 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8545 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8546
8547 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8548 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8549 input = new InputStreamReader(logcat.getInputStream());
8550
8551 int num;
8552 char[] buf = new char[8192];
8553 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8554 } catch (IOException e) {
8555 Slog.e(TAG, "Error running logcat", e);
8556 } finally {
8557 if (input != null) try { input.close(); } catch (IOException e) {}
8558 }
8559 }
8560
8561 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008562 }
Dan Egnora455d192010-03-12 08:52:28 -08008563 };
8564
8565 if (process == null || process.pid == MY_PID) {
8566 worker.run(); // We may be about to die -- need to run this synchronously
8567 } else {
8568 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008569 }
8570 }
8571
8572 /**
8573 * Bring up the "unexpected error" dialog box for a crashing app.
8574 * Deal with edge cases (intercepts from instrumented applications,
8575 * ActivityController, error intent receivers, that sort of thing).
8576 * @param r the application crashing
8577 * @param crashInfo describing the failure
8578 */
8579 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008580 long timeMillis = System.currentTimeMillis();
8581 String shortMsg = crashInfo.exceptionClassName;
8582 String longMsg = crashInfo.exceptionMessage;
8583 String stackTrace = crashInfo.stackTrace;
8584 if (shortMsg != null && longMsg != null) {
8585 longMsg = shortMsg + ": " + longMsg;
8586 } else if (shortMsg != null) {
8587 longMsg = shortMsg;
8588 }
8589
Dan Egnor60d87622009-12-16 16:32:58 -08008590 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008592 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 try {
8594 String name = r != null ? r.processName : null;
8595 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008596 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008597 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008598 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008599 + " at watcher's request");
8600 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008601 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008602 }
8603 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008604 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008605 }
8606 }
8607
8608 final long origId = Binder.clearCallingIdentity();
8609
8610 // If this process is running instrumentation, finish it.
8611 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008612 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008614 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8615 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008616 Bundle info = new Bundle();
8617 info.putString("shortMsg", shortMsg);
8618 info.putString("longMsg", longMsg);
8619 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8620 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008621 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 }
8623
Dan Egnor60d87622009-12-16 16:32:58 -08008624 // If we can't identify the process or it's already exceeded its crash quota,
8625 // quit right away without showing a crash dialog.
8626 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008627 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008628 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 }
8630
8631 Message msg = Message.obtain();
8632 msg.what = SHOW_ERROR_MSG;
8633 HashMap data = new HashMap();
8634 data.put("result", result);
8635 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008636 msg.obj = data;
8637 mHandler.sendMessage(msg);
8638
8639 Binder.restoreCallingIdentity(origId);
8640 }
8641
8642 int res = result.get();
8643
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008644 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008645 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008646 if (r != null && !r.isolated) {
8647 // XXX Can't keep track of crash time for isolated processes,
8648 // since they don't have a persistent identity.
8649 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 SystemClock.uptimeMillis());
8651 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008652 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008653 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008654 }
8655 }
8656
8657 if (appErrorIntent != null) {
8658 try {
8659 mContext.startActivity(appErrorIntent);
8660 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008661 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008665
8666 Intent createAppErrorIntentLocked(ProcessRecord r,
8667 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8668 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008669 if (report == null) {
8670 return null;
8671 }
8672 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8673 result.setComponent(r.errorReportReceiver);
8674 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8675 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8676 return result;
8677 }
8678
Dan Egnorb7f03672009-12-09 16:22:32 -08008679 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8680 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008681 if (r.errorReportReceiver == null) {
8682 return null;
8683 }
8684
8685 if (!r.crashing && !r.notResponding) {
8686 return null;
8687 }
8688
Dan Egnorb7f03672009-12-09 16:22:32 -08008689 ApplicationErrorReport report = new ApplicationErrorReport();
8690 report.packageName = r.info.packageName;
8691 report.installerPackageName = r.errorReportReceiver.getPackageName();
8692 report.processName = r.processName;
8693 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008694 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008695
Dan Egnorb7f03672009-12-09 16:22:32 -08008696 if (r.crashing) {
8697 report.type = ApplicationErrorReport.TYPE_CRASH;
8698 report.crashInfo = crashInfo;
8699 } else if (r.notResponding) {
8700 report.type = ApplicationErrorReport.TYPE_ANR;
8701 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008702
Dan Egnorb7f03672009-12-09 16:22:32 -08008703 report.anrInfo.activity = r.notRespondingReport.tag;
8704 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8705 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008706 }
8707
Dan Egnorb7f03672009-12-09 16:22:32 -08008708 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008709 }
8710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008712 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713 // assume our apps are happy - lazy create the list
8714 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8715
8716 synchronized (this) {
8717
8718 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008719 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8720 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008721 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8722 // This one's in trouble, so we'll generate a report for it
8723 // crashes are higher priority (in case there's a crash *and* an anr)
8724 ActivityManager.ProcessErrorStateInfo report = null;
8725 if (app.crashing) {
8726 report = app.crashingReport;
8727 } else if (app.notResponding) {
8728 report = app.notRespondingReport;
8729 }
8730
8731 if (report != null) {
8732 if (errList == null) {
8733 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8734 }
8735 errList.add(report);
8736 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008737 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008738 " crashing = " + app.crashing +
8739 " notResponding = " + app.notResponding);
8740 }
8741 }
8742 }
8743 }
8744
8745 return errList;
8746 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008747
8748 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008749 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008750 if (currApp != null) {
8751 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8752 }
8753 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008754 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8755 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008756 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8757 if (currApp != null) {
8758 currApp.lru = 0;
8759 }
8760 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008761 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008762 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8763 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8764 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8765 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8766 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8767 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8768 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8769 } else {
8770 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8771 }
8772 }
8773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008775 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 // Lazy instantiation of list
8777 List<ActivityManager.RunningAppProcessInfo> runList = null;
8778 synchronized (this) {
8779 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008780 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8781 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8783 // Generate process state info for running application
8784 ActivityManager.RunningAppProcessInfo currApp =
8785 new ActivityManager.RunningAppProcessInfo(app.processName,
8786 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07008787 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07008788 if (mHeavyWeightProcess == app) {
Dianne Hackborn482566e2010-09-03 12:51:28 -07008789 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07008790 }
Dianne Hackborn42499172010-10-15 18:45:07 -07008791 if (app.persistent) {
8792 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008794 int adj = app.curAdj;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008795 currApp.importance = oomAdjToImportance(adj, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008796 currApp.importanceReasonCode = app.adjTypeCode;
8797 if (app.adjSource instanceof ProcessRecord) {
8798 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008799 currApp.importanceReasonImportance = oomAdjToImportance(
8800 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008801 } else if (app.adjSource instanceof ActivityRecord) {
8802 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008803 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8804 }
8805 if (app.adjTarget instanceof ComponentName) {
8806 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8807 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008808 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008809 // + " lru=" + currApp.lru);
8810 if (runList == null) {
8811 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8812 }
8813 runList.add(currApp);
8814 }
8815 }
8816 }
8817 return runList;
8818 }
8819
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008820 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008821 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008822 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8823 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8824 if (runningApps != null && runningApps.size() > 0) {
8825 Set<String> extList = new HashSet<String>();
8826 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8827 if (app.pkgList != null) {
8828 for (String pkg : app.pkgList) {
8829 extList.add(pkg);
8830 }
8831 }
8832 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008833 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008834 for (String pkg : extList) {
8835 try {
8836 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8837 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8838 retList.add(info);
8839 }
8840 } catch (RemoteException e) {
8841 }
8842 }
8843 }
8844 return retList;
8845 }
8846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008847 @Override
8848 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008849 if (checkCallingPermission(android.Manifest.permission.DUMP)
8850 != PackageManager.PERMISSION_GRANTED) {
8851 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8852 + Binder.getCallingPid()
8853 + ", uid=" + Binder.getCallingUid()
8854 + " without permission "
8855 + android.Manifest.permission.DUMP);
8856 return;
8857 }
8858
8859 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008860 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008861 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008862
8863 int opti = 0;
8864 while (opti < args.length) {
8865 String opt = args[opti];
8866 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8867 break;
8868 }
8869 opti++;
8870 if ("-a".equals(opt)) {
8871 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008872 } else if ("-c".equals(opt)) {
8873 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008874 } else if ("-h".equals(opt)) {
8875 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008876 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008877 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008878 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008879 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8880 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8881 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008882 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008883 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008884 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008885 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008886 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008887 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008888 pw.println(" all: dump all activities");
8889 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008890 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008891 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8892 pw.println(" a partial substring in a component name, a");
8893 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008894 pw.println(" -a: include all available server state.");
8895 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008896 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008897 } else {
8898 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008899 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008900 }
8901
8902 // Is the caller requesting to dump a particular piece of data?
8903 if (opti < args.length) {
8904 String cmd = args[opti];
8905 opti++;
8906 if ("activities".equals(cmd) || "a".equals(cmd)) {
8907 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008908 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008909 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008910 return;
8911 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008912 String[] newArgs;
8913 String name;
8914 if (opti >= args.length) {
8915 name = null;
8916 newArgs = EMPTY_STRING_ARRAY;
8917 } else {
8918 name = args[opti];
8919 opti++;
8920 newArgs = new String[args.length - opti];
8921 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8922 args.length - opti);
8923 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008924 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008925 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008926 }
8927 return;
8928 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008929 String[] newArgs;
8930 String name;
8931 if (opti >= args.length) {
8932 name = null;
8933 newArgs = EMPTY_STRING_ARRAY;
8934 } else {
8935 name = args[opti];
8936 opti++;
8937 newArgs = new String[args.length - opti];
8938 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8939 args.length - opti);
8940 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008941 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008942 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008943 }
8944 return;
8945 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008946 String[] newArgs;
8947 String name;
8948 if (opti >= args.length) {
8949 name = null;
8950 newArgs = EMPTY_STRING_ARRAY;
8951 } else {
8952 name = args[opti];
8953 opti++;
8954 newArgs = new String[args.length - opti];
8955 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8956 args.length - opti);
8957 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008958 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008959 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008960 }
8961 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008962 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8963 synchronized (this) {
8964 dumpOomLocked(fd, pw, args, opti, true);
8965 }
8966 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008967 } else if ("provider".equals(cmd)) {
8968 String[] newArgs;
8969 String name;
8970 if (opti >= args.length) {
8971 name = null;
8972 newArgs = EMPTY_STRING_ARRAY;
8973 } else {
8974 name = args[opti];
8975 opti++;
8976 newArgs = new String[args.length - opti];
8977 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8978 }
8979 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8980 pw.println("No providers match: " + name);
8981 pw.println("Use -h for help.");
8982 }
8983 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008984 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8985 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008986 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008987 }
8988 return;
8989 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008990 String[] newArgs;
8991 String name;
8992 if (opti >= args.length) {
8993 name = null;
8994 newArgs = EMPTY_STRING_ARRAY;
8995 } else {
8996 name = args[opti];
8997 opti++;
8998 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008999 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9000 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009001 }
9002 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
9003 pw.println("No services match: " + name);
9004 pw.println("Use -h for help.");
9005 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009006 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009007 } else if ("package".equals(cmd)) {
9008 String[] newArgs;
9009 if (opti >= args.length) {
9010 pw.println("package: no package name specified");
9011 pw.println("Use -h for help.");
9012 return;
9013 } else {
9014 dumpPackage = args[opti];
9015 opti++;
9016 newArgs = new String[args.length - opti];
9017 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9018 args.length - opti);
9019 args = newArgs;
9020 opti = 0;
9021 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009022 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9023 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009024 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009025 }
9026 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07009027 } else {
9028 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009029 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
9030 pw.println("Bad activity command, or no activities match: " + cmd);
9031 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009032 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009033 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009034 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009035 }
9036
9037 // No piece of data specified, dump everything.
9038 synchronized (this) {
9039 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009040 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009041 if (needSep) {
9042 pw.println(" ");
9043 }
9044 if (dumpAll) {
9045 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009046 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009047 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009048 if (needSep) {
9049 pw.println(" ");
9050 }
9051 if (dumpAll) {
9052 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009053 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009054 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009055 if (needSep) {
9056 pw.println(" ");
9057 }
9058 if (dumpAll) {
9059 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009060 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009061 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009062 if (needSep) {
9063 pw.println(" ");
9064 }
9065 if (dumpAll) {
9066 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009067 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009068 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009069 if (needSep) {
9070 pw.println(" ");
9071 }
9072 if (dumpAll) {
9073 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009074 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009075 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009076 }
9077 }
9078
9079 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009080 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009081 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9082 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009083 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9084 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009085 pw.println(" ");
9086 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009087 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9088 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009089 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009090 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009091 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009092 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009093 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009094 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009095 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009097 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009098 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009099 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009100 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009101 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9102 pw.println(" ");
9103 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009104 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009105 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009106 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009107 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009108 pw.println(" ");
9109 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009110 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009111 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009113
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009114 pw.println(" ");
Dianne Hackborncbb722e2012-02-07 18:33:49 -08009115 if (mMainStack.mPausingActivities.size() > 0) {
9116 pw.println(" mPausingActivities: " + Arrays.toString(
9117 mMainStack.mPausingActivities.toArray()));
9118 }
9119 if (mMainStack.mInputPausedActivities.size() > 0) {
9120 pw.println(" mInputPausedActivities: " + Arrays.toString(
9121 mMainStack.mInputPausedActivities.toArray()));
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009122 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009123 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009124 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009125 if (dumpAll) {
9126 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9127 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009128 pw.println(" mDismissKeyguardOnNextActivity: "
9129 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009131
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009132 if (mRecentTasks.size() > 0) {
9133 pw.println();
9134 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009135
9136 final int N = mRecentTasks.size();
9137 for (int i=0; i<N; i++) {
9138 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009139 if (dumpPackage != null) {
9140 if (tr.realActivity == null ||
9141 !dumpPackage.equals(tr.realActivity)) {
9142 continue;
9143 }
9144 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009145 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9146 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009147 if (dumpAll) {
9148 mRecentTasks.get(i).dump(pw, " ");
9149 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009150 }
9151 }
9152
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009153 if (dumpAll) {
9154 pw.println(" ");
9155 pw.println(" mCurTask: " + mCurTask);
9156 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009157
9158 return true;
9159 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009160
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009161 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009162 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009163 boolean needSep = false;
9164 int numPers = 0;
9165
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009166 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9167
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009168 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9170 final int NA = procs.size();
9171 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009172 ProcessRecord r = procs.valueAt(ia);
9173 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9174 continue;
9175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009176 if (!needSep) {
9177 pw.println(" All known processes:");
9178 needSep = true;
9179 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009180 pw.print(r.persistent ? " *PERS*" : " *APP*");
9181 pw.print(" UID "); pw.print(procs.keyAt(ia));
9182 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009183 r.dump(pw, " ");
9184 if (r.persistent) {
9185 numPers++;
9186 }
9187 }
9188 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009189 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009190
9191 if (mIsolatedProcesses.size() > 0) {
9192 if (needSep) pw.println(" ");
9193 needSep = true;
9194 pw.println(" Isolated process list (sorted by uid):");
9195 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9196 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9197 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9198 continue;
9199 }
9200 pw.println(String.format("%sIsolated #%2d: %s",
9201 " ", i, r.toString()));
9202 }
9203 }
9204
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009205 if (mLruProcesses.size() > 0) {
9206 if (needSep) pw.println(" ");
9207 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009208 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009209 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009210 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009211 needSep = true;
9212 }
9213
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009214 if (dumpAll) {
9215 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009216 boolean printed = false;
9217 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9218 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9219 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9220 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009221 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009222 if (!printed) {
9223 if (needSep) pw.println(" ");
9224 needSep = true;
9225 pw.println(" PID mappings:");
9226 printed = true;
9227 }
9228 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9229 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009230 }
9231 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009232 }
9233
9234 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009235 synchronized (mPidsSelfLocked) {
9236 boolean printed = false;
9237 for (int i=0; i<mForegroundProcesses.size(); i++) {
9238 ProcessRecord r = mPidsSelfLocked.get(
9239 mForegroundProcesses.valueAt(i).pid);
9240 if (dumpPackage != null && (r == null
9241 || !dumpPackage.equals(r.info.packageName))) {
9242 continue;
9243 }
9244 if (!printed) {
9245 if (needSep) pw.println(" ");
9246 needSep = true;
9247 pw.println(" Foreground Processes:");
9248 printed = true;
9249 }
9250 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9251 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009253 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009254 }
9255
9256 if (mPersistentStartingProcesses.size() > 0) {
9257 if (needSep) pw.println(" ");
9258 needSep = true;
9259 pw.println(" Persisent processes that are starting:");
9260 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009261 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009263
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009264 if (mRemovedProcesses.size() > 0) {
9265 if (needSep) pw.println(" ");
9266 needSep = true;
9267 pw.println(" Processes that are being removed:");
9268 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009269 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009270 }
9271
9272 if (mProcessesOnHold.size() > 0) {
9273 if (needSep) pw.println(" ");
9274 needSep = true;
9275 pw.println(" Processes that are on old until the system is ready:");
9276 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009277 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009279
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009280 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009281
9282 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009283 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009284 long now = SystemClock.uptimeMillis();
9285 for (Map.Entry<String, SparseArray<Long>> procs
9286 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009287 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009288 SparseArray<Long> uids = procs.getValue();
9289 final int N = uids.size();
9290 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009291 int puid = uids.keyAt(i);
9292 ProcessRecord r = mProcessNames.get(pname, puid);
9293 if (dumpPackage != null && (r == null
9294 || !dumpPackage.equals(r.info.packageName))) {
9295 continue;
9296 }
9297 if (!printed) {
9298 if (needSep) pw.println(" ");
9299 needSep = true;
9300 pw.println(" Time since processes crashed:");
9301 printed = true;
9302 }
9303 pw.print(" Process "); pw.print(pname);
9304 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009305 pw.print(": last crashed ");
9306 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009307 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009308 }
9309 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009311
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009312 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009313 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009314 for (Map.Entry<String, SparseArray<Long>> procs
9315 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009316 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009317 SparseArray<Long> uids = procs.getValue();
9318 final int N = uids.size();
9319 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009320 int puid = uids.keyAt(i);
9321 ProcessRecord r = mProcessNames.get(pname, puid);
9322 if (dumpPackage != null && (r == null
9323 || !dumpPackage.equals(r.info.packageName))) {
9324 continue;
9325 }
9326 if (!printed) {
9327 if (needSep) pw.println(" ");
9328 needSep = true;
9329 pw.println(" Bad processes:");
9330 }
9331 pw.print(" Bad process "); pw.print(pname);
9332 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009333 pw.print(": crashed at time ");
9334 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009335 }
9336 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009338
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009339 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009340 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009341 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009342 if (dumpAll) {
9343 StringBuilder sb = new StringBuilder(128);
9344 sb.append(" mPreviousProcessVisibleTime: ");
9345 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9346 pw.println(sb);
9347 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009348 if (mHeavyWeightProcess != null) {
9349 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9350 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009351 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009352 if (dumpAll) {
9353 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009354 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009355 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009356 for (Map.Entry<String, Integer> entry
9357 : mCompatModePackages.getPackages().entrySet()) {
9358 String pkg = entry.getKey();
9359 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009360 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9361 continue;
9362 }
9363 if (!printed) {
9364 pw.println(" mScreenCompatPackages:");
9365 printed = true;
9366 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009367 pw.print(" "); pw.print(pkg); pw.print(": ");
9368 pw.print(mode); pw.println();
9369 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009370 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009371 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009372 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
9373 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9374 || mOrigWaitForDebugger) {
9375 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9376 + " mDebugTransient=" + mDebugTransient
9377 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9378 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009379 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9380 || mProfileFd != null) {
9381 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9382 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9383 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9384 + mAutoStopProfiler);
9385 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009386 if (mAlwaysFinishActivities || mController != null) {
9387 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9388 + " mController=" + mController);
9389 }
9390 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009391 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009392 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009393 + " mProcessesReady=" + mProcessesReady
9394 + " mSystemReady=" + mSystemReady);
9395 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009396 + " mBooted=" + mBooted
9397 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009398 pw.print(" mLastPowerCheckRealtime=");
9399 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9400 pw.println("");
9401 pw.print(" mLastPowerCheckUptime=");
9402 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9403 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009404 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9405 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009406 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009407 pw.println(" mNumServiceProcs=" + mNumServiceProcs
9408 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009409 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009410
9411 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009412 }
9413
Dianne Hackborn287952c2010-09-22 22:34:31 -07009414 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009415 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009416 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009417 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009418 long now = SystemClock.uptimeMillis();
9419 for (int i=0; i<mProcessesToGc.size(); i++) {
9420 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009421 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9422 continue;
9423 }
9424 if (!printed) {
9425 if (needSep) pw.println(" ");
9426 needSep = true;
9427 pw.println(" Processes that are waiting to GC:");
9428 printed = true;
9429 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009430 pw.print(" Process "); pw.println(proc);
9431 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9432 pw.print(", last gced=");
9433 pw.print(now-proc.lastRequestedGc);
9434 pw.print(" ms ago, last lowMem=");
9435 pw.print(now-proc.lastLowMemory);
9436 pw.println(" ms ago");
9437
9438 }
9439 }
9440 return needSep;
9441 }
9442
9443 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9444 int opti, boolean dumpAll) {
9445 boolean needSep = false;
9446
9447 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009448 if (needSep) pw.println(" ");
9449 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009450 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009451 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009452 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009453 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9454 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9455 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9456 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9457 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009458 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009459 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009460 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009461 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009462 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009463 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009464
9465 if (needSep) pw.println(" ");
9466 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009467 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009468 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009469 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009470 needSep = true;
9471 }
9472
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009473 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009474
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009475 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009476 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009477 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009478 if (mHeavyWeightProcess != null) {
9479 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9480 }
9481
9482 return true;
9483 }
9484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009485 /**
9486 * There are three ways to call this:
9487 * - no service specified: dump all the services
9488 * - a flattened component name that matched an existing service was specified as the
9489 * first arg: dump that one service
9490 * - the first arg isn't the flattened component name of an existing service:
9491 * dump all services whose component contains the first arg as a substring
9492 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009493 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9494 int opti, boolean dumpAll) {
9495 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009496
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009497 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009498 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009499 try {
9500 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9501 for (UserInfo user : users) {
9502 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9503 services.add(r1);
9504 }
9505 }
9506 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009507 }
9508 }
9509 } else {
9510 ComponentName componentName = name != null
9511 ? ComponentName.unflattenFromString(name) : null;
9512 int objectId = 0;
9513 if (componentName == null) {
9514 // Not a '/' separated full component name; maybe an object ID?
9515 try {
9516 objectId = Integer.parseInt(name, 16);
9517 name = null;
9518 componentName = null;
9519 } catch (RuntimeException e) {
9520 }
9521 }
9522
9523 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009524 try {
9525 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9526 for (UserInfo user : users) {
9527 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9528 if (componentName != null) {
9529 if (r1.name.equals(componentName)) {
9530 services.add(r1);
9531 }
9532 } else if (name != null) {
9533 if (r1.name.flattenToString().contains(name)) {
9534 services.add(r1);
9535 }
9536 } else if (System.identityHashCode(r1) == objectId) {
9537 services.add(r1);
9538 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009539 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009540 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009541 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009542 }
9543 }
9544 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009545
9546 if (services.size() <= 0) {
9547 return false;
9548 }
9549
9550 boolean needSep = false;
9551 for (int i=0; i<services.size(); i++) {
9552 if (needSep) {
9553 pw.println();
9554 }
9555 needSep = true;
9556 dumpService("", fd, pw, services.get(i), args, dumpAll);
9557 }
9558 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009559 }
9560
9561 /**
9562 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9563 * there is a thread associated with the service.
9564 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009565 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9566 final ServiceRecord r, String[] args, boolean dumpAll) {
9567 String innerPrefix = prefix + " ";
9568 synchronized (this) {
9569 pw.print(prefix); pw.print("SERVICE ");
9570 pw.print(r.shortName); pw.print(" ");
9571 pw.print(Integer.toHexString(System.identityHashCode(r)));
9572 pw.print(" pid=");
9573 if (r.app != null) pw.println(r.app.pid);
9574 else pw.println("(not running)");
9575 if (dumpAll) {
9576 r.dump(pw, innerPrefix);
9577 }
9578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009579 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009580 pw.print(prefix); pw.println(" Client:");
9581 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009582 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009583 TransferPipe tp = new TransferPipe();
9584 try {
9585 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9586 tp.setBufferPrefix(prefix + " ");
9587 tp.go(fd);
9588 } finally {
9589 tp.kill();
9590 }
9591 } catch (IOException e) {
9592 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009593 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009594 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009595 }
9596 }
9597 }
9598
Marco Nelissen18cb2872011-11-15 11:19:53 -08009599 /**
9600 * There are three ways to call this:
9601 * - no provider specified: dump all the providers
9602 * - a flattened component name that matched an existing provider was specified as the
9603 * first arg: dump that one provider
9604 * - the first arg isn't the flattened component name of an existing provider:
9605 * dump all providers whose component contains the first arg as a substring
9606 */
9607 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9608 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009609 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009610 }
9611
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009612 static class ItemMatcher {
9613 ArrayList<ComponentName> components;
9614 ArrayList<String> strings;
9615 ArrayList<Integer> objects;
9616 boolean all;
9617
9618 ItemMatcher() {
9619 all = true;
9620 }
9621
9622 void build(String name) {
9623 ComponentName componentName = ComponentName.unflattenFromString(name);
9624 if (componentName != null) {
9625 if (components == null) {
9626 components = new ArrayList<ComponentName>();
9627 }
9628 components.add(componentName);
9629 all = false;
9630 } else {
9631 int objectId = 0;
9632 // Not a '/' separated full component name; maybe an object ID?
9633 try {
9634 objectId = Integer.parseInt(name, 16);
9635 if (objects == null) {
9636 objects = new ArrayList<Integer>();
9637 }
9638 objects.add(objectId);
9639 all = false;
9640 } catch (RuntimeException e) {
9641 // Not an integer; just do string match.
9642 if (strings == null) {
9643 strings = new ArrayList<String>();
9644 }
9645 strings.add(name);
9646 all = false;
9647 }
9648 }
9649 }
9650
9651 int build(String[] args, int opti) {
9652 for (; opti<args.length; opti++) {
9653 String name = args[opti];
9654 if ("--".equals(name)) {
9655 return opti+1;
9656 }
9657 build(name);
9658 }
9659 return opti;
9660 }
9661
9662 boolean match(Object object, ComponentName comp) {
9663 if (all) {
9664 return true;
9665 }
9666 if (components != null) {
9667 for (int i=0; i<components.size(); i++) {
9668 if (components.get(i).equals(comp)) {
9669 return true;
9670 }
9671 }
9672 }
9673 if (objects != null) {
9674 for (int i=0; i<objects.size(); i++) {
9675 if (System.identityHashCode(object) == objects.get(i)) {
9676 return true;
9677 }
9678 }
9679 }
9680 if (strings != null) {
9681 String flat = comp.flattenToString();
9682 for (int i=0; i<strings.size(); i++) {
9683 if (flat.contains(strings.get(i))) {
9684 return true;
9685 }
9686 }
9687 }
9688 return false;
9689 }
9690 }
9691
Dianne Hackborn625ac272010-09-17 18:29:22 -07009692 /**
9693 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009694 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009695 * - the cmd arg isn't the flattened component name of an existing activity:
9696 * dump all activity whose component contains the cmd as a substring
9697 * - A hex number of the ActivityRecord object instance.
9698 */
9699 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9700 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009701 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009702
9703 if ("all".equals(name)) {
9704 synchronized (this) {
9705 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009706 activities.add(r1);
9707 }
9708 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009709 } else if ("top".equals(name)) {
9710 synchronized (this) {
9711 final int N = mMainStack.mHistory.size();
9712 if (N > 0) {
9713 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9714 }
9715 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009716 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009717 ItemMatcher matcher = new ItemMatcher();
9718 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009719
9720 synchronized (this) {
9721 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009722 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009723 activities.add(r1);
9724 }
9725 }
9726 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009727 }
9728
9729 if (activities.size() <= 0) {
9730 return false;
9731 }
9732
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009733 String[] newArgs = new String[args.length - opti];
9734 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9735
Dianne Hackborn30d71892010-12-11 10:37:55 -08009736 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009737 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009738 for (int i=activities.size()-1; i>=0; i--) {
9739 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009740 if (needSep) {
9741 pw.println();
9742 }
9743 needSep = true;
9744 synchronized (this) {
9745 if (lastTask != r.task) {
9746 lastTask = r.task;
9747 pw.print("TASK "); pw.print(lastTask.affinity);
9748 pw.print(" id="); pw.println(lastTask.taskId);
9749 if (dumpAll) {
9750 lastTask.dump(pw, " ");
9751 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009752 }
9753 }
9754 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009755 }
9756 return true;
9757 }
9758
9759 /**
9760 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9761 * there is a thread associated with the activity.
9762 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009763 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009764 final ActivityRecord r, String[] args, boolean dumpAll) {
9765 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009766 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009767 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9768 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9769 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009770 if (r.app != null) pw.println(r.app.pid);
9771 else pw.println("(not running)");
9772 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009773 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009774 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009775 }
9776 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009777 // flush anything that is already in the PrintWriter since the thread is going
9778 // to write to the file descriptor directly
9779 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009780 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009781 TransferPipe tp = new TransferPipe();
9782 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009783 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9784 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009785 tp.go(fd);
9786 } finally {
9787 tp.kill();
9788 }
9789 } catch (IOException e) {
9790 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009791 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009792 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009793 }
9794 }
9795 }
9796
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009797 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009798 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009799 boolean needSep = false;
9800
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009801 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009802 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009803 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009804 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009805 Iterator it = mRegisteredReceivers.values().iterator();
9806 while (it.hasNext()) {
9807 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009808 if (dumpPackage != null && (r.app == null ||
9809 !dumpPackage.equals(r.app.info.packageName))) {
9810 continue;
9811 }
9812 if (!printed) {
9813 pw.println(" Registered Receivers:");
9814 needSep = true;
9815 printed = true;
9816 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009817 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009818 r.dump(pw, " ");
9819 }
9820 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009821
9822 if (mReceiverResolver.dump(pw, needSep ?
9823 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9824 " ", dumpPackage, false)) {
9825 needSep = true;
9826 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009827 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009828
9829 for (BroadcastQueue q : mBroadcastQueues) {
9830 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009833 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009834
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009835 if (mStickyBroadcasts != null && dumpPackage == null) {
9836 if (needSep) {
9837 pw.println();
9838 }
9839 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009840 pw.println(" Sticky broadcasts:");
9841 StringBuilder sb = new StringBuilder(128);
9842 for (Map.Entry<String, ArrayList<Intent>> ent
9843 : mStickyBroadcasts.entrySet()) {
9844 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009845 if (dumpAll) {
9846 pw.println(":");
9847 ArrayList<Intent> intents = ent.getValue();
9848 final int N = intents.size();
9849 for (int i=0; i<N; i++) {
9850 sb.setLength(0);
9851 sb.append(" Intent: ");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009852 intents.get(i).toShortString(sb, false, true, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009853 pw.println(sb.toString());
9854 Bundle bundle = intents.get(i).getExtras();
9855 if (bundle != null) {
9856 pw.print(" ");
9857 pw.println(bundle.toString());
9858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009859 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009860 } else {
9861 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009862 }
9863 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009864 needSep = true;
9865 }
9866
9867 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009868 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009869 for (BroadcastQueue queue : mBroadcastQueues) {
9870 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9871 + queue.mBroadcastsScheduled);
9872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009873 pw.println(" mHandler:");
9874 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009875 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009876 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009877
9878 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009879 }
9880
Marco Nelissen18cb2872011-11-15 11:19:53 -08009881 /**
9882 * Prints a list of ServiceRecords (dumpsys activity services)
9883 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009884 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009885 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009886 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009887
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009888 ItemMatcher matcher = new ItemMatcher();
9889 matcher.build(args, opti);
9890
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009891 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009892 try {
9893 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9894 for (UserInfo user : users) {
9895 if (mServiceMap.getAllServices(user.id).size() > 0) {
9896 boolean printed = false;
9897 long nowReal = SystemClock.elapsedRealtime();
9898 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9899 user.id).iterator();
9900 needSep = false;
9901 while (it.hasNext()) {
9902 ServiceRecord r = it.next();
9903 if (!matcher.match(r, r.name)) {
9904 continue;
9905 }
9906 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9907 continue;
9908 }
9909 if (!printed) {
9910 pw.println(" Active services:");
9911 printed = true;
9912 }
9913 if (needSep) {
9914 pw.println();
9915 }
9916 pw.print(" * ");
9917 pw.println(r);
9918 if (dumpAll) {
9919 r.dump(pw, " ");
9920 needSep = true;
9921 } else {
9922 pw.print(" app=");
9923 pw.println(r.app);
9924 pw.print(" created=");
9925 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9926 pw.print(" started=");
9927 pw.print(r.startRequested);
9928 pw.print(" connections=");
9929 pw.println(r.connections.size());
9930 if (r.connections.size() > 0) {
9931 pw.println(" Connections:");
9932 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9933 for (int i = 0; i < clist.size(); i++) {
9934 ConnectionRecord conn = clist.get(i);
9935 pw.print(" ");
9936 pw.print(conn.binding.intent.intent.getIntent()
9937 .toShortString(false, false, false));
9938 pw.print(" -> ");
9939 ProcessRecord proc = conn.binding.client;
9940 pw.println(proc != null ? proc.toShortString() : "null");
9941 }
9942 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009943 }
9944 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009945 if (dumpClient && r.app != null && r.app.thread != null) {
9946 pw.println(" Client:");
9947 pw.flush();
9948 try {
9949 TransferPipe tp = new TransferPipe();
9950 try {
9951 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9952 r, args);
9953 tp.setBufferPrefix(" ");
9954 // Short timeout, since blocking here can
9955 // deadlock with the application.
9956 tp.go(fd, 2000);
9957 } finally {
9958 tp.kill();
9959 }
9960 } catch (IOException e) {
9961 pw.println(" Failure while dumping the service: " + e);
9962 } catch (RemoteException e) {
9963 pw.println(" Got a RemoteException while dumping the service");
9964 }
9965 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009966 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009967 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009968 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009970 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009971 } catch (RemoteException re) {
9972
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009974
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009975 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009976 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009977 for (int i=0; i<mPendingServices.size(); i++) {
9978 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009979 if (!matcher.match(r, r.name)) {
9980 continue;
9981 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009982 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9983 continue;
9984 }
9985 if (!printed) {
9986 if (needSep) pw.println(" ");
9987 needSep = true;
9988 pw.println(" Pending services:");
9989 printed = true;
9990 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009991 pw.print(" * Pending "); pw.println(r);
9992 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009993 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009994 needSep = true;
9995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009996
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009997 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009998 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009999 for (int i=0; i<mRestartingServices.size(); i++) {
10000 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010001 if (!matcher.match(r, r.name)) {
10002 continue;
10003 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010004 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
10005 continue;
10006 }
10007 if (!printed) {
10008 if (needSep) pw.println(" ");
10009 needSep = true;
10010 pw.println(" Restarting services:");
10011 printed = true;
10012 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010013 pw.print(" * Restarting "); pw.println(r);
10014 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010015 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010016 needSep = true;
10017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010018
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010019 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010020 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010021 for (int i=0; i<mStoppingServices.size(); i++) {
10022 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010023 if (!matcher.match(r, r.name)) {
10024 continue;
10025 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010026 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
10027 continue;
10028 }
10029 if (!printed) {
10030 if (needSep) pw.println(" ");
10031 needSep = true;
10032 pw.println(" Stopping services:");
10033 printed = true;
10034 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010035 pw.print(" * Stopping "); pw.println(r);
10036 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010037 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010038 needSep = true;
10039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010040
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010041 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010042 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010043 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010044 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010045 = mServiceConnections.values().iterator();
10046 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010047 ArrayList<ConnectionRecord> r = it.next();
10048 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010049 ConnectionRecord cr = r.get(i);
10050 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
10051 continue;
10052 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010053 if (dumpPackage != null && (cr.binding.client == null
10054 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
10055 continue;
10056 }
10057 if (!printed) {
10058 if (needSep) pw.println(" ");
10059 needSep = true;
10060 pw.println(" Connection bindings to services:");
10061 printed = true;
10062 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010063 pw.print(" * "); pw.println(cr);
10064 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010066 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010067 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010068 }
10069 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010070
10071 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010072 }
10073
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010074 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010075 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010076 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010077
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010078 ItemMatcher matcher = new ItemMatcher();
10079 matcher.build(args, opti);
10080
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010081 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -070010082
10083 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010084
10085 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010086 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010087 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010088 ContentProviderRecord r = mLaunchingProviders.get(i);
10089 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
10090 continue;
10091 }
10092 if (!printed) {
10093 if (needSep) pw.println(" ");
10094 needSep = true;
10095 pw.println(" Launching content providers:");
10096 printed = true;
10097 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010098 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010099 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010100 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010101 }
10102
10103 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010104 if (needSep) pw.println();
10105 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010106 pw.println("Granted Uri Permissions:");
10107 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
10108 int uid = mGrantedUriPermissions.keyAt(i);
10109 HashMap<Uri, UriPermission> perms
10110 = mGrantedUriPermissions.valueAt(i);
10111 pw.print(" * UID "); pw.print(uid);
10112 pw.println(" holds:");
10113 for (UriPermission perm : perms.values()) {
10114 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010115 if (dumpAll) {
10116 perm.dump(pw, " ");
10117 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010118 }
10119 }
10120 needSep = true;
10121 }
10122
10123 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010124 }
10125
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010126 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010127 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010128 boolean needSep = false;
10129
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010130 if (mIntentSenderRecords.size() > 0) {
10131 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010132 Iterator<WeakReference<PendingIntentRecord>> it
10133 = mIntentSenderRecords.values().iterator();
10134 while (it.hasNext()) {
10135 WeakReference<PendingIntentRecord> ref = it.next();
10136 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010137 if (dumpPackage != null && (rec == null
10138 || !dumpPackage.equals(rec.key.packageName))) {
10139 continue;
10140 }
10141 if (!printed) {
10142 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
10143 printed = true;
10144 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010145 needSep = true;
10146 if (rec != null) {
10147 pw.print(" * "); pw.println(rec);
10148 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010149 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010150 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010151 } else {
10152 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010153 }
10154 }
10155 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010156
10157 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010158 }
10159
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010160 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010161 String prefix, String label, boolean complete, boolean brief, boolean client,
10162 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010163 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010164 boolean needNL = false;
10165 final String innerPrefix = prefix + " ";
10166 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010167 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010168 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010169 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
10170 continue;
10171 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -070010172 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010173 if (needNL) {
10174 pw.println(" ");
10175 needNL = false;
10176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010177 if (lastTask != r.task) {
10178 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010179 pw.print(prefix);
10180 pw.print(full ? "* " : " ");
10181 pw.println(lastTask);
10182 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010183 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010184 } else if (complete) {
10185 // Complete + brief == give a summary. Isn't that obvious?!?
10186 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010187 pw.print(prefix); pw.print(" ");
10188 pw.println(lastTask.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010189 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010191 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010192 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
10193 pw.print(" #"); pw.print(i); pw.print(": ");
10194 pw.println(r);
10195 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010196 r.dump(pw, innerPrefix);
10197 } else if (complete) {
10198 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010199 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010200 if (r.app != null) {
10201 pw.print(innerPrefix); pw.println(r.app);
10202 }
10203 }
10204 if (client && r.app != null && r.app.thread != null) {
10205 // flush anything that is already in the PrintWriter since the thread is going
10206 // to write to the file descriptor directly
10207 pw.flush();
10208 try {
10209 TransferPipe tp = new TransferPipe();
10210 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -080010211 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
10212 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010213 // Short timeout, since blocking here can
10214 // deadlock with the application.
10215 tp.go(fd, 2000);
10216 } finally {
10217 tp.kill();
10218 }
10219 } catch (IOException e) {
10220 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
10221 } catch (RemoteException e) {
10222 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
10223 }
10224 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010226 }
10227 }
10228
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010229 private static String buildOomTag(String prefix, String space, int val, int base) {
10230 if (val == base) {
10231 if (space == null) return prefix;
10232 return prefix + " ";
10233 }
10234 return prefix + "+" + Integer.toString(val-base);
10235 }
10236
10237 private static final int dumpProcessList(PrintWriter pw,
10238 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010239 String prefix, String normalLabel, String persistentLabel,
10240 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010241 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010242 final int N = list.size()-1;
10243 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010244 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010245 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10246 continue;
10247 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010248 pw.println(String.format("%s%s #%2d: %s",
10249 prefix, (r.persistent ? persistentLabel : normalLabel),
10250 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010251 if (r.persistent) {
10252 numPers++;
10253 }
10254 }
10255 return numPers;
10256 }
10257
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010258 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010259 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010260 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010261 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010262
Dianne Hackborn905577f2011-09-07 18:31:28 -070010263 ArrayList<Pair<ProcessRecord, Integer>> list
10264 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10265 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010266 ProcessRecord r = origList.get(i);
10267 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10268 continue;
10269 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010270 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10271 }
10272
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010273 if (list.size() <= 0) {
10274 return false;
10275 }
10276
Dianne Hackborn905577f2011-09-07 18:31:28 -070010277 Comparator<Pair<ProcessRecord, Integer>> comparator
10278 = new Comparator<Pair<ProcessRecord, Integer>>() {
10279 @Override
10280 public int compare(Pair<ProcessRecord, Integer> object1,
10281 Pair<ProcessRecord, Integer> object2) {
10282 if (object1.first.setAdj != object2.first.setAdj) {
10283 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10284 }
10285 if (object1.second.intValue() != object2.second.intValue()) {
10286 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10287 }
10288 return 0;
10289 }
10290 };
10291
10292 Collections.sort(list, comparator);
10293
Dianne Hackborn287952c2010-09-22 22:34:31 -070010294 final long curRealtime = SystemClock.elapsedRealtime();
10295 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10296 final long curUptime = SystemClock.uptimeMillis();
10297 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10298
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010299 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010300 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010301 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010302 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010303 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010304 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10305 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010306 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10307 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010308 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10309 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010310 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10311 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010312 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010313 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010314 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10315 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10316 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10317 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10318 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10319 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10320 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10321 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010322 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10323 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010324 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10325 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010326 } else {
10327 oomAdj = Integer.toString(r.setAdj);
10328 }
10329 String schedGroup;
10330 switch (r.setSchedGroup) {
10331 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10332 schedGroup = "B";
10333 break;
10334 case Process.THREAD_GROUP_DEFAULT:
10335 schedGroup = "F";
10336 break;
10337 default:
10338 schedGroup = Integer.toString(r.setSchedGroup);
10339 break;
10340 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010341 String foreground;
10342 if (r.foregroundActivities) {
10343 foreground = "A";
10344 } else if (r.foregroundServices) {
10345 foreground = "S";
10346 } else {
10347 foreground = " ";
10348 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010349 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010350 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010351 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10352 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010353 if (r.adjSource != null || r.adjTarget != null) {
10354 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010355 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010356 if (r.adjTarget instanceof ComponentName) {
10357 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10358 } else if (r.adjTarget != null) {
10359 pw.print(r.adjTarget.toString());
10360 } else {
10361 pw.print("{null}");
10362 }
10363 pw.print("<=");
10364 if (r.adjSource instanceof ProcessRecord) {
10365 pw.print("Proc{");
10366 pw.print(((ProcessRecord)r.adjSource).toShortString());
10367 pw.println("}");
10368 } else if (r.adjSource != null) {
10369 pw.println(r.adjSource.toString());
10370 } else {
10371 pw.println("{null}");
10372 }
10373 }
10374 if (inclDetails) {
10375 pw.print(prefix);
10376 pw.print(" ");
10377 pw.print("oom: max="); pw.print(r.maxAdj);
10378 pw.print(" hidden="); pw.print(r.hiddenAdj);
10379 pw.print(" curRaw="); pw.print(r.curRawAdj);
10380 pw.print(" setRaw="); pw.print(r.setRawAdj);
10381 pw.print(" cur="); pw.print(r.curAdj);
10382 pw.print(" set="); pw.println(r.setAdj);
10383 pw.print(prefix);
10384 pw.print(" ");
10385 pw.print("keeping="); pw.print(r.keeping);
10386 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010387 pw.print(" empty="); pw.print(r.empty);
10388 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010389
10390 if (!r.keeping) {
10391 if (r.lastWakeTime != 0) {
10392 long wtime;
10393 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10394 synchronized (stats) {
10395 wtime = stats.getProcessWakeTime(r.info.uid,
10396 r.pid, curRealtime);
10397 }
10398 long timeUsed = wtime - r.lastWakeTime;
10399 pw.print(prefix);
10400 pw.print(" ");
10401 pw.print("keep awake over ");
10402 TimeUtils.formatDuration(realtimeSince, pw);
10403 pw.print(" used ");
10404 TimeUtils.formatDuration(timeUsed, pw);
10405 pw.print(" (");
10406 pw.print((timeUsed*100)/realtimeSince);
10407 pw.println("%)");
10408 }
10409 if (r.lastCpuTime != 0) {
10410 long timeUsed = r.curCpuTime - r.lastCpuTime;
10411 pw.print(prefix);
10412 pw.print(" ");
10413 pw.print("run cpu over ");
10414 TimeUtils.formatDuration(uptimeSince, pw);
10415 pw.print(" used ");
10416 TimeUtils.formatDuration(timeUsed, pw);
10417 pw.print(" (");
10418 pw.print((timeUsed*100)/uptimeSince);
10419 pw.println("%)");
10420 }
10421 }
10422 }
10423 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010424 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010425 }
10426
Dianne Hackbornb437e092011-08-05 17:50:29 -070010427 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010428 ArrayList<ProcessRecord> procs;
10429 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010430 if (args != null && args.length > start
10431 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010432 procs = new ArrayList<ProcessRecord>();
10433 int pid = -1;
10434 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010435 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010436 } catch (NumberFormatException e) {
10437
10438 }
10439 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10440 ProcessRecord proc = mLruProcesses.get(i);
10441 if (proc.pid == pid) {
10442 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010443 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010444 procs.add(proc);
10445 }
10446 }
10447 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010448 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010449 return null;
10450 }
10451 } else {
10452 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10453 }
10454 }
10455 return procs;
10456 }
10457
10458 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10459 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010460 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010461 if (procs == null) {
10462 return;
10463 }
10464
10465 long uptime = SystemClock.uptimeMillis();
10466 long realtime = SystemClock.elapsedRealtime();
10467 pw.println("Applications Graphics Acceleration Info:");
10468 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10469
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010470 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10471 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010472 if (r.thread != null) {
10473 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10474 pw.flush();
10475 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010476 TransferPipe tp = new TransferPipe();
10477 try {
10478 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10479 tp.go(fd);
10480 } finally {
10481 tp.kill();
10482 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010483 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010484 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010485 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010486 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010487 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010488 pw.flush();
10489 }
10490 }
10491 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010492 }
10493
Jeff Brown6754ba22011-12-14 20:20:01 -080010494 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10495 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10496 if (procs == null) {
10497 return;
10498 }
10499
10500 pw.println("Applications Database Info:");
10501
10502 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10503 ProcessRecord r = procs.get(i);
10504 if (r.thread != null) {
10505 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10506 pw.flush();
10507 try {
10508 TransferPipe tp = new TransferPipe();
10509 try {
10510 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10511 tp.go(fd);
10512 } finally {
10513 tp.kill();
10514 }
10515 } catch (IOException e) {
10516 pw.println("Failure while dumping the app: " + r);
10517 pw.flush();
10518 } catch (RemoteException e) {
10519 pw.println("Got a RemoteException while dumping the app " + r);
10520 pw.flush();
10521 }
10522 }
10523 }
10524 }
10525
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010526 final static class MemItem {
10527 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010528 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010529 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010530 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010531 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010532
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010533 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010534 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010535 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010536 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010537 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010538 }
10539 }
10540
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010541 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010542 boolean sort) {
10543 if (sort) {
10544 Collections.sort(items, new Comparator<MemItem>() {
10545 @Override
10546 public int compare(MemItem lhs, MemItem rhs) {
10547 if (lhs.pss < rhs.pss) {
10548 return 1;
10549 } else if (lhs.pss > rhs.pss) {
10550 return -1;
10551 }
10552 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010553 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010554 });
10555 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010556
10557 for (int i=0; i<items.size(); i++) {
10558 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010559 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010560 if (mi.subitems != null) {
10561 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10562 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010563 }
10564 }
10565
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010566 // These are in KB.
10567 static final long[] DUMP_MEM_BUCKETS = new long[] {
10568 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10569 120*1024, 160*1024, 200*1024,
10570 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10571 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10572 };
10573
Dianne Hackborn672342c2011-11-29 11:29:02 -080010574 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10575 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010576 int start = label.lastIndexOf('.');
10577 if (start >= 0) start++;
10578 else start = 0;
10579 int end = label.length();
10580 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10581 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10582 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10583 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010584 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010585 out.append(label, start, end);
10586 return;
10587 }
10588 }
10589 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010590 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010591 out.append(label, start, end);
10592 }
10593
10594 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10595 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10596 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10597 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10598 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10599 };
10600 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10601 "System", "Persistent", "Foreground",
10602 "Visible", "Perceptible", "Heavy Weight",
10603 "Backup", "A Services", "Home", "Previous",
10604 "B Services", "Background"
10605 };
10606
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010607 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010608 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010609 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010610 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010611 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010612
10613 int opti = 0;
10614 while (opti < args.length) {
10615 String opt = args[opti];
10616 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10617 break;
10618 }
10619 opti++;
10620 if ("-a".equals(opt)) {
10621 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010622 } else if ("--oom".equals(opt)) {
10623 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010624 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010625 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010626 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010627 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010628 pw.println("If [process] is specified it can be the name or ");
10629 pw.println("pid of a specific process to dump.");
10630 return;
10631 } else {
10632 pw.println("Unknown argument: " + opt + "; use -h for help");
10633 }
10634 }
10635
10636 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010637 if (procs == null) {
10638 return;
10639 }
10640
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010641 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010642 long uptime = SystemClock.uptimeMillis();
10643 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010644
10645 if (procs.size() == 1 || isCheckinRequest) {
10646 dumpAll = true;
10647 }
10648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010649 if (isCheckinRequest) {
10650 // short checkin version
10651 pw.println(uptime + "," + realtime);
10652 pw.flush();
10653 } else {
10654 pw.println("Applications Memory Usage (kB):");
10655 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10656 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010657
Dianne Hackbornb437e092011-08-05 17:50:29 -070010658 String[] innerArgs = new String[args.length-opti];
10659 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10660
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010661 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10662 long nativePss=0, dalvikPss=0, otherPss=0;
10663 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10664
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010665 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10666 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10667 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010668
10669 long totalPss = 0;
10670
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010671 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10672 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010673 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010674 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10676 pw.flush();
10677 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010678 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010679 if (dumpAll) {
10680 try {
10681 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10682 } catch (RemoteException e) {
10683 if (!isCheckinRequest) {
10684 pw.println("Got RemoteException!");
10685 pw.flush();
10686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010687 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010688 } else {
10689 mi = new Debug.MemoryInfo();
10690 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010691 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010692
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010693 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010694 long myTotalPss = mi.getTotalPss();
10695 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010696 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010697 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010698 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010699
10700 nativePss += mi.nativePss;
10701 dalvikPss += mi.dalvikPss;
10702 otherPss += mi.otherPss;
10703 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10704 long mem = mi.getOtherPss(j);
10705 miscPss[j] += mem;
10706 otherPss -= mem;
10707 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010708
10709 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010710 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10711 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010712 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010713 if (oomProcs[oomIndex] == null) {
10714 oomProcs[oomIndex] = new ArrayList<MemItem>();
10715 }
10716 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010717 break;
10718 }
10719 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010721 }
10722 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010723
10724 if (!isCheckinRequest && procs.size() > 1) {
10725 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10726
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010727 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10728 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10729 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010730 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010731 String label = Debug.MemoryInfo.getOtherLabel(j);
10732 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010733 }
10734
Dianne Hackbornb437e092011-08-05 17:50:29 -070010735 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10736 for (int j=0; j<oomPss.length; j++) {
10737 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010738 String label = DUMP_MEM_OOM_LABEL[j];
10739 MemItem item = new MemItem(label, label, oomPss[j],
10740 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010741 item.subitems = oomProcs[j];
10742 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010743 }
10744 }
10745
Dianne Hackborn672342c2011-11-29 11:29:02 -080010746 if (outTag != null || outStack != null) {
10747 if (outTag != null) {
10748 appendMemBucket(outTag, totalPss, "total", false);
10749 }
10750 if (outStack != null) {
10751 appendMemBucket(outStack, totalPss, "total", true);
10752 }
10753 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010754 for (int i=0; i<oomMems.size(); i++) {
10755 MemItem miCat = oomMems.get(i);
10756 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10757 continue;
10758 }
10759 if (miCat.id < ProcessList.SERVICE_ADJ
10760 || miCat.id == ProcessList.HOME_APP_ADJ
10761 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010762 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10763 outTag.append(" / ");
10764 }
10765 if (outStack != null) {
10766 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10767 if (firstLine) {
10768 outStack.append(":");
10769 firstLine = false;
10770 }
10771 outStack.append("\n\t at ");
10772 } else {
10773 outStack.append("$");
10774 }
10775 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010776 for (int j=0; j<miCat.subitems.size(); j++) {
10777 MemItem mi = miCat.subitems.get(j);
10778 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010779 if (outTag != null) {
10780 outTag.append(" ");
10781 }
10782 if (outStack != null) {
10783 outStack.append("$");
10784 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010785 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010786 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10787 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10788 }
10789 if (outStack != null) {
10790 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10791 }
10792 }
10793 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10794 outStack.append("(");
10795 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10796 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10797 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10798 outStack.append(":");
10799 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10800 }
10801 }
10802 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010803 }
10804 }
10805 }
10806 }
10807
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010808 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010809 pw.println();
10810 pw.println("Total PSS by process:");
10811 dumpMemItems(pw, " ", procMems, true);
10812 pw.println();
10813 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010814 pw.println("Total PSS by OOM adjustment:");
10815 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010816 if (!oomOnly) {
10817 PrintWriter out = categoryPw != null ? categoryPw : pw;
10818 out.println();
10819 out.println("Total PSS by category:");
10820 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010821 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010822 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010823 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 }
10826
10827 /**
10828 * Searches array of arguments for the specified string
10829 * @param args array of argument strings
10830 * @param value value to search for
10831 * @return true if the value is contained in the array
10832 */
10833 private static boolean scanArgs(String[] args, String value) {
10834 if (args != null) {
10835 for (String arg : args) {
10836 if (value.equals(arg)) {
10837 return true;
10838 }
10839 }
10840 }
10841 return false;
10842 }
10843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010844 private final void killServicesLocked(ProcessRecord app,
10845 boolean allowRestart) {
10846 // Report disconnected services.
10847 if (false) {
10848 // XXX we are letting the client link to the service for
10849 // death notifications.
10850 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010851 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010852 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010853 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010854 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010855 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010856 = r.connections.values().iterator();
10857 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010858 ArrayList<ConnectionRecord> cl = jt.next();
10859 for (int i=0; i<cl.size(); i++) {
10860 ConnectionRecord c = cl.get(i);
10861 if (c.binding.client != app) {
10862 try {
10863 //c.conn.connected(r.className, null);
10864 } catch (Exception e) {
10865 // todo: this should be asynchronous!
10866 Slog.w(TAG, "Exception thrown disconnected servce "
10867 + r.shortName
10868 + " from app " + app.processName, e);
10869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010870 }
10871 }
10872 }
10873 }
10874 }
10875 }
10876 }
10877
10878 // Clean up any connections this application has to other services.
10879 if (app.connections.size() > 0) {
10880 Iterator<ConnectionRecord> it = app.connections.iterator();
10881 while (it.hasNext()) {
10882 ConnectionRecord r = it.next();
10883 removeConnectionLocked(r, app, null);
10884 }
10885 }
10886 app.connections.clear();
10887
10888 if (app.services.size() != 0) {
10889 // Any services running in the application need to be placed
10890 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010891 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010892 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010893 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 synchronized (sr.stats.getBatteryStats()) {
10895 sr.stats.stopLaunchedLocked();
10896 }
10897 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010898 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010899 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010900 if (mStoppingServices.remove(sr)) {
10901 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10902 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010903
10904 boolean hasClients = sr.bindings.size() > 0;
10905 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010906 Iterator<IntentBindRecord> bindings
10907 = sr.bindings.values().iterator();
10908 while (bindings.hasNext()) {
10909 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010910 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010911 + ": shouldUnbind=" + b.hasBound);
10912 b.binder = null;
10913 b.requested = b.received = b.hasBound = false;
10914 }
10915 }
10916
Dianne Hackborn070783f2010-12-29 16:46:28 -080010917 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10918 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010919 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010920 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010921 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 sr.crashCount, sr.shortName, app.pid);
10923 bringDownServiceLocked(sr, true);
10924 } else if (!allowRestart) {
10925 bringDownServiceLocked(sr, true);
10926 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010927 boolean canceled = scheduleServiceRestartLocked(sr, true);
10928
10929 // Should the service remain running? Note that in the
10930 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010931 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010932 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10933 if (sr.pendingStarts.size() == 0) {
10934 sr.startRequested = false;
10935 if (!hasClients) {
10936 // Whoops, no reason to restart!
10937 bringDownServiceLocked(sr, true);
10938 }
10939 }
10940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010941 }
10942 }
10943
10944 if (!allowRestart) {
10945 app.services.clear();
10946 }
10947 }
10948
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010949 // Make sure we have no more records on the stopping list.
10950 int i = mStoppingServices.size();
10951 while (i > 0) {
10952 i--;
10953 ServiceRecord sr = mStoppingServices.get(i);
10954 if (sr.app == app) {
10955 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010956 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010957 }
10958 }
10959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960 app.executingServices.clear();
10961 }
10962
10963 private final void removeDyingProviderLocked(ProcessRecord proc,
10964 ContentProviderRecord cpr) {
10965 synchronized (cpr) {
10966 cpr.launchingApp = null;
10967 cpr.notifyAll();
10968 }
10969
Amith Yamasani742a6712011-05-04 14:49:28 -070010970 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010971 String names[] = cpr.info.authority.split(";");
10972 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010973 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010974 }
10975
10976 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10977 while (cit.hasNext()) {
10978 ProcessRecord capp = cit.next();
10979 if (!capp.persistent && capp.thread != null
10980 && capp.pid != 0
10981 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010982 Slog.i(TAG, "Kill " + capp.processName
10983 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010984 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010985 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010986 capp.processName, capp.setAdj, "dying provider "
10987 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010988 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010989 }
10990 }
10991
10992 mLaunchingProviders.remove(cpr);
10993 }
10994
10995 /**
10996 * Main code for cleaning up a process when it has gone away. This is
10997 * called both as a result of the process dying, or directly when stopping
10998 * a process when running in single process mode.
10999 */
11000 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011001 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011002 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011003 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011004 }
11005
Dianne Hackborn36124872009-10-08 16:22:03 -070011006 mProcessesToGc.remove(app);
11007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011008 // Dismiss any open dialogs.
11009 if (app.crashDialog != null) {
11010 app.crashDialog.dismiss();
11011 app.crashDialog = null;
11012 }
11013 if (app.anrDialog != null) {
11014 app.anrDialog.dismiss();
11015 app.anrDialog = null;
11016 }
11017 if (app.waitDialog != null) {
11018 app.waitDialog.dismiss();
11019 app.waitDialog = null;
11020 }
11021
11022 app.crashing = false;
11023 app.notResponding = false;
11024
11025 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070011026 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011027 app.thread = null;
11028 app.forcingToForeground = null;
11029 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070011030 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070011031 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011032 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011033
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011034 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011035
11036 boolean restart = false;
11037
11038 int NL = mLaunchingProviders.size();
11039
11040 // Remove published content providers.
11041 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011042 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011043 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011044 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011045 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070011046 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011047
11048 // See if someone is waiting for this provider... in which
11049 // case we don't remove it, but just let it restart.
11050 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011051 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011052 for (; i<NL; i++) {
11053 if (mLaunchingProviders.get(i) == cpr) {
11054 restart = true;
11055 break;
11056 }
11057 }
11058 } else {
11059 i = NL;
11060 }
11061
11062 if (i >= NL) {
11063 removeDyingProviderLocked(app, cpr);
11064 NL = mLaunchingProviders.size();
11065 }
11066 }
11067 app.pubProviders.clear();
11068 }
11069
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011070 // Take care of any launching providers waiting for this process.
11071 if (checkAppInLaunchingProvidersLocked(app, false)) {
11072 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011073 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011075 // Unregister from connected content providers.
11076 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070011077 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011078 while (it.hasNext()) {
11079 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
11080 cpr.clients.remove(app);
11081 }
11082 app.conProviders.clear();
11083 }
11084
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011085 // At this point there may be remaining entries in mLaunchingProviders
11086 // where we were the only one waiting, so they are no longer of use.
11087 // Look for these and clean up if found.
11088 // XXX Commented out for now. Trying to figure out a way to reproduce
11089 // the actual situation to identify what is actually going on.
11090 if (false) {
11091 for (int i=0; i<NL; i++) {
11092 ContentProviderRecord cpr = (ContentProviderRecord)
11093 mLaunchingProviders.get(i);
11094 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
11095 synchronized (cpr) {
11096 cpr.launchingApp = null;
11097 cpr.notifyAll();
11098 }
11099 }
11100 }
11101 }
11102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011103 skipCurrentReceiverLocked(app);
11104
11105 // Unregister any receivers.
11106 if (app.receivers.size() > 0) {
11107 Iterator<ReceiverList> it = app.receivers.iterator();
11108 while (it.hasNext()) {
11109 removeReceiverLocked(it.next());
11110 }
11111 app.receivers.clear();
11112 }
11113
Christopher Tate181fafa2009-05-14 11:12:14 -070011114 // If the app is undergoing backup, tell the backup manager about it
11115 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011116 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070011117 try {
11118 IBackupManager bm = IBackupManager.Stub.asInterface(
11119 ServiceManager.getService(Context.BACKUP_SERVICE));
11120 bm.agentDisconnected(app.info.packageName);
11121 } catch (RemoteException e) {
11122 // can't happen; backup manager is local
11123 }
11124 }
11125
Jeff Sharkey287bd832011-05-28 19:36:26 -070011126 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070011127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011128 // If the caller is restarting this app, then leave it in its
11129 // current lists and let the caller take care of it.
11130 if (restarting) {
11131 return;
11132 }
11133
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011134 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011135 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011136 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011137 mProcessNames.remove(app.processName, app.uid);
11138 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070011139 if (mHeavyWeightProcess == app) {
11140 mHeavyWeightProcess = null;
11141 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
11142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011143 } else if (!app.removed) {
11144 // This app is persistent, so we need to keep its record around.
11145 // If it is not already on the pending app list, add it there
11146 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011147 if (mPersistentStartingProcesses.indexOf(app) < 0) {
11148 mPersistentStartingProcesses.add(app);
11149 restart = true;
11150 }
11151 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011152 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
11153 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011154 mProcessesOnHold.remove(app);
11155
The Android Open Source Project4df24232009-03-05 14:34:35 -080011156 if (app == mHomeProcess) {
11157 mHomeProcess = null;
11158 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070011159 if (app == mPreviousProcess) {
11160 mPreviousProcess = null;
11161 }
11162
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011163 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011164 // We have components that still need to be running in the
11165 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011166 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167 startProcessLocked(app, "restart", app.processName);
11168 } else if (app.pid > 0 && app.pid != MY_PID) {
11169 // Goodbye!
11170 synchronized (mPidsSelfLocked) {
11171 mPidsSelfLocked.remove(app.pid);
11172 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
11173 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070011174 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011175 }
11176 }
11177
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011178 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
11179 // Look through the content providers we are waiting to have launched,
11180 // and if any run in this process then either schedule a restart of
11181 // the process or kill the client waiting for it if this process has
11182 // gone bad.
11183 int NL = mLaunchingProviders.size();
11184 boolean restart = false;
11185 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011186 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011187 if (cpr.launchingApp == app) {
11188 if (!alwaysBad && !app.bad) {
11189 restart = true;
11190 } else {
11191 removeDyingProviderLocked(app, cpr);
11192 NL = mLaunchingProviders.size();
11193 }
11194 }
11195 }
11196 return restart;
11197 }
11198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011199 // =========================================================
11200 // SERVICES
11201 // =========================================================
11202
11203 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
11204 ActivityManager.RunningServiceInfo info =
11205 new ActivityManager.RunningServiceInfo();
11206 info.service = r.name;
11207 if (r.app != null) {
11208 info.pid = r.app.pid;
11209 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070011210 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 info.process = r.processName;
11212 info.foreground = r.isForeground;
11213 info.activeSince = r.createTime;
11214 info.started = r.startRequested;
11215 info.clientCount = r.connections.size();
11216 info.crashCount = r.crashCount;
11217 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070011218 if (r.isForeground) {
11219 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
11220 }
11221 if (r.startRequested) {
11222 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
11223 }
Dan Egnor42471dd2010-01-07 17:25:22 -080011224 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070011225 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
11226 }
11227 if (r.app != null && r.app.persistent) {
11228 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
11229 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011230
11231 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
11232 for (int i=0; i<connl.size(); i++) {
11233 ConnectionRecord conn = connl.get(i);
11234 if (conn.clientLabel != 0) {
11235 info.clientPackage = conn.binding.client.info.packageName;
11236 info.clientLabel = conn.clientLabel;
11237 return info;
11238 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011239 }
11240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011241 return info;
11242 }
11243
11244 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
11245 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011246 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011247 synchronized (this) {
11248 ArrayList<ActivityManager.RunningServiceInfo> res
11249 = new ArrayList<ActivityManager.RunningServiceInfo>();
11250
Amith Yamasani742a6712011-05-04 14:49:28 -070011251 int userId = UserId.getUserId(Binder.getCallingUid());
11252 if (mServiceMap.getAllServices(userId).size() > 0) {
11253 Iterator<ServiceRecord> it
11254 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011255 while (it.hasNext() && res.size() < maxNum) {
11256 res.add(makeRunningServiceInfoLocked(it.next()));
11257 }
11258 }
11259
11260 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
11261 ServiceRecord r = mRestartingServices.get(i);
11262 ActivityManager.RunningServiceInfo info =
11263 makeRunningServiceInfoLocked(r);
11264 info.restarting = r.nextRestartTime;
11265 res.add(info);
11266 }
11267
11268 return res;
11269 }
11270 }
11271
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011272 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011273 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011274 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011275 int userId = UserId.getUserId(Binder.getCallingUid());
11276 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011277 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011278 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
11279 for (int i=0; i<conn.size(); i++) {
11280 if (conn.get(i).clientIntent != null) {
11281 return conn.get(i).clientIntent;
11282 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011283 }
11284 }
11285 }
11286 }
11287 return null;
11288 }
11289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011290 private final ServiceRecord findServiceLocked(ComponentName name,
11291 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011292 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011293 return r == token ? r : null;
11294 }
11295
11296 private final class ServiceLookupResult {
11297 final ServiceRecord record;
11298 final String permission;
11299
11300 ServiceLookupResult(ServiceRecord _record, String _permission) {
11301 record = _record;
11302 permission = _permission;
11303 }
11304 };
11305
11306 private ServiceLookupResult findServiceLocked(Intent service,
11307 String resolvedType) {
11308 ServiceRecord r = null;
11309 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011310 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011311 }
11312 if (r == null) {
11313 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070011314 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011315 }
11316
11317 if (r == null) {
11318 try {
11319 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011320 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011321 service, resolvedType, 0);
11322 ServiceInfo sInfo =
11323 rInfo != null ? rInfo.serviceInfo : null;
11324 if (sInfo == null) {
11325 return null;
11326 }
11327
11328 ComponentName name = new ComponentName(
11329 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070011330 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 } catch (RemoteException ex) {
11332 // pm is in same process, this will never happen.
11333 }
11334 }
11335 if (r != null) {
11336 int callingPid = Binder.getCallingPid();
11337 int callingUid = Binder.getCallingUid();
11338 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011339 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011340 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011341 if (!r.exported) {
11342 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11343 + " from pid=" + callingPid
11344 + ", uid=" + callingUid
11345 + " that is not exported from uid " + r.appInfo.uid);
11346 return new ServiceLookupResult(null, "not exported from uid "
11347 + r.appInfo.uid);
11348 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011349 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011350 + " from pid=" + callingPid
11351 + ", uid=" + callingUid
11352 + " requires " + r.permission);
11353 return new ServiceLookupResult(null, r.permission);
11354 }
11355 return new ServiceLookupResult(r, null);
11356 }
11357 return null;
11358 }
11359
11360 private class ServiceRestarter implements Runnable {
11361 private ServiceRecord mService;
11362
11363 void setService(ServiceRecord service) {
11364 mService = service;
11365 }
11366
11367 public void run() {
11368 synchronized(ActivityManagerService.this) {
11369 performServiceRestartLocked(mService);
11370 }
11371 }
11372 }
11373
11374 private ServiceLookupResult retrieveServiceLocked(Intent service,
11375 String resolvedType, int callingPid, int callingUid) {
11376 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070011377 if (DEBUG_SERVICE)
11378 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
11379 + " origCallingUid=" + callingUid);
11380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011381 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011382 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011383 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011384 if (r == null) {
11385 Intent.FilterComparison filter = new Intent.FilterComparison(service);
11386 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
11387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011388 if (r == null) {
11389 try {
11390 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011391 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011392 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011393 ServiceInfo sInfo =
11394 rInfo != null ? rInfo.serviceInfo : null;
11395 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011396 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011397 ": not found");
11398 return null;
11399 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011400 if (Binder.getOrigCallingUser() > 0) {
11401 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo,
11402 Binder.getOrigCallingUser());
11403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011404 ComponentName name = new ComponentName(
11405 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070011406 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011407 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011408 Intent.FilterComparison filter = new Intent.FilterComparison(
11409 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011410 ServiceRestarter res = new ServiceRestarter();
11411 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11412 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11413 synchronized (stats) {
11414 ss = stats.getServiceStatsLocked(
11415 sInfo.applicationInfo.uid, sInfo.packageName,
11416 sInfo.name);
11417 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080011418 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011419 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070011420 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
11421 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011422
11423 // Make sure this component isn't in the pending list.
11424 int N = mPendingServices.size();
11425 for (int i=0; i<N; i++) {
11426 ServiceRecord pr = mPendingServices.get(i);
11427 if (pr.name.equals(name)) {
11428 mPendingServices.remove(i);
11429 i--;
11430 N--;
11431 }
11432 }
11433 }
11434 } catch (RemoteException ex) {
11435 // pm is in same process, this will never happen.
11436 }
11437 }
11438 if (r != null) {
11439 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011440 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011441 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011442 if (!r.exported) {
11443 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11444 + " from pid=" + callingPid
11445 + ", uid=" + callingUid
11446 + " that is not exported from uid " + r.appInfo.uid);
11447 return new ServiceLookupResult(null, "not exported from uid "
11448 + r.appInfo.uid);
11449 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011450 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011451 + " from pid=" + callingPid
11452 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 + " requires " + r.permission);
11454 return new ServiceLookupResult(null, r.permission);
11455 }
11456 return new ServiceLookupResult(r, null);
11457 }
11458 return null;
11459 }
11460
Dianne Hackborn287952c2010-09-22 22:34:31 -070011461 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11462 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11463 + why + " of " + r + " in app " + r.app);
11464 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11465 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011466 long now = SystemClock.uptimeMillis();
11467 if (r.executeNesting == 0 && r.app != null) {
11468 if (r.app.executingServices.size() == 0) {
11469 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11470 msg.obj = r.app;
11471 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11472 }
11473 r.app.executingServices.add(r);
11474 }
11475 r.executeNesting++;
11476 r.executingStart = now;
11477 }
11478
11479 private final void sendServiceArgsLocked(ServiceRecord r,
11480 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011481 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011482 if (N == 0) {
11483 return;
11484 }
11485
Dianne Hackborn39792d22010-08-19 18:01:52 -070011486 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011487 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011488 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011489 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11490 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011491 if (si.intent == null && N > 1) {
11492 // If somehow we got a dummy null intent in the middle,
11493 // then skip it. DO NOT skip a null intent when it is
11494 // the only one in the list -- this is to support the
11495 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011496 continue;
11497 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011498 si.deliveredTime = SystemClock.uptimeMillis();
11499 r.deliveredStarts.add(si);
11500 si.deliveryCount++;
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011501 if (si.targetPermissionUid >= 0 && si.intent != null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011502 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -070011503 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011504 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011505 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011506 if (!oomAdjusted) {
11507 oomAdjusted = true;
11508 updateOomAdjLocked(r.app);
11509 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011510 int flags = 0;
11511 if (si.deliveryCount > 0) {
11512 flags |= Service.START_FLAG_RETRY;
11513 }
11514 if (si.doneExecutingCount > 0) {
11515 flags |= Service.START_FLAG_REDELIVERY;
11516 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011517 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011518 } catch (RemoteException e) {
11519 // Remote process gone... we'll let the normal cleanup take
11520 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011521 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011522 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011523 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011524 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011525 break;
11526 }
11527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011528 }
11529
11530 private final boolean requestServiceBindingLocked(ServiceRecord r,
11531 IntentBindRecord i, boolean rebind) {
11532 if (r.app == null || r.app.thread == null) {
11533 // If service is not currently running, can't yet bind.
11534 return false;
11535 }
11536 if ((!i.requested || rebind) && i.apps.size() > 0) {
11537 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011538 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011539 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11540 if (!rebind) {
11541 i.requested = true;
11542 }
11543 i.hasBound = true;
11544 i.doRebind = false;
11545 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011546 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011547 return false;
11548 }
11549 }
11550 return true;
11551 }
11552
11553 private final void requestServiceBindingsLocked(ServiceRecord r) {
11554 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11555 while (bindings.hasNext()) {
11556 IntentBindRecord i = bindings.next();
11557 if (!requestServiceBindingLocked(r, i, false)) {
11558 break;
11559 }
11560 }
11561 }
11562
11563 private final void realStartServiceLocked(ServiceRecord r,
11564 ProcessRecord app) throws RemoteException {
11565 if (app.thread == null) {
11566 throw new RemoteException();
11567 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011568 if (DEBUG_MU)
11569 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011570 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011571 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011572 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011573
11574 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011575 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011576 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011577
11578 boolean created = false;
11579 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011580 mStringBuilder.setLength(0);
Dianne Hackborn90c52de2011-09-23 12:57:44 -070011581 r.intent.getIntent().toShortString(mStringBuilder, true, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011582 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011583 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011584 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011585 synchronized (r.stats.getBatteryStats()) {
11586 r.stats.startLaunchedLocked();
11587 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011588 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011589 app.thread.scheduleCreateService(r, r.serviceInfo,
11590 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011591 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011592 created = true;
11593 } finally {
11594 if (!created) {
11595 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011596 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011597 }
11598 }
11599
11600 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011601
11602 // If the service is in the started state, and there are no
11603 // pending arguments, then fake up one so its onStartCommand() will
11604 // be called.
11605 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011606 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
11607 null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011608 }
11609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011610 sendServiceArgsLocked(r, true);
11611 }
11612
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011613 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11614 boolean allowCancel) {
11615 boolean canceled = false;
11616
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011617 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011618 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011619 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011620
Dianne Hackborn070783f2010-12-29 16:46:28 -080011621 if ((r.serviceInfo.applicationInfo.flags
11622 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11623 minDuration /= 4;
11624 }
11625
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011626 // Any delivered but not yet finished starts should be put back
11627 // on the pending list.
11628 final int N = r.deliveredStarts.size();
11629 if (N > 0) {
11630 for (int i=N-1; i>=0; i--) {
11631 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011632 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011633 if (si.intent == null) {
11634 // We'll generate this again if needed.
11635 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11636 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11637 r.pendingStarts.add(0, si);
11638 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11639 dur *= 2;
11640 if (minDuration < dur) minDuration = dur;
11641 if (resetTime < dur) resetTime = dur;
11642 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011643 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011644 + r.name);
11645 canceled = true;
11646 }
11647 }
11648 r.deliveredStarts.clear();
11649 }
11650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011651 r.totalRestartCount++;
11652 if (r.restartDelay == 0) {
11653 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011654 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 } else {
11656 // If it has been a "reasonably long time" since the service
11657 // was started, then reset our restart duration back to
11658 // the beginning, so we don't infinitely increase the duration
11659 // on a service that just occasionally gets killed (which is
11660 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011661 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011662 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011663 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011664 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011665 if ((r.serviceInfo.applicationInfo.flags
11666 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11667 // Services in peristent processes will restart much more
11668 // quickly, since they are pretty important. (Think SystemUI).
11669 r.restartDelay += minDuration/2;
11670 } else {
11671 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11672 if (r.restartDelay < minDuration) {
11673 r.restartDelay = minDuration;
11674 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011676 }
11677 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011678
11679 r.nextRestartTime = now + r.restartDelay;
11680
11681 // Make sure that we don't end up restarting a bunch of services
11682 // all at the same time.
11683 boolean repeat;
11684 do {
11685 repeat = false;
11686 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11687 ServiceRecord r2 = mRestartingServices.get(i);
11688 if (r2 != r && r.nextRestartTime
11689 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11690 && r.nextRestartTime
11691 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11692 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11693 r.restartDelay = r.nextRestartTime - now;
11694 repeat = true;
11695 break;
11696 }
11697 }
11698 } while (repeat);
11699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011700 if (!mRestartingServices.contains(r)) {
11701 mRestartingServices.add(r);
11702 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011703
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011704 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011706 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011707 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011708 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011709 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011710 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011711 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011712 r.shortName, r.restartDelay);
11713
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011714 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011715 }
11716
11717 final void performServiceRestartLocked(ServiceRecord r) {
11718 if (!mRestartingServices.contains(r)) {
11719 return;
11720 }
11721 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11722 }
11723
11724 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11725 if (r.restartDelay == 0) {
11726 return false;
11727 }
11728 r.resetRestartCounter();
11729 mRestartingServices.remove(r);
11730 mHandler.removeCallbacks(r.restarter);
11731 return true;
11732 }
11733
11734 private final boolean bringUpServiceLocked(ServiceRecord r,
11735 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011736 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011737 //r.dump(" ");
11738
Dianne Hackborn36124872009-10-08 16:22:03 -070011739 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011740 sendServiceArgsLocked(r, false);
11741 return true;
11742 }
11743
11744 if (!whileRestarting && r.restartDelay > 0) {
11745 // If waiting for a restart, then do nothing.
11746 return true;
11747 }
11748
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011749 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011750
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011751 // We are now bringing the service up, so no longer in the
11752 // restarting state.
11753 mRestartingServices.remove(r);
11754
Dianne Hackborne7f97212011-02-24 14:40:20 -080011755 // Service is now being launched, its package can't be stopped.
11756 try {
11757 AppGlobals.getPackageManager().setPackageStoppedState(
11758 r.packageName, false);
11759 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011760 } catch (IllegalArgumentException e) {
11761 Slog.w(TAG, "Failed trying to unstop package "
11762 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011763 }
11764
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011765 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011766 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011767 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011768
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011769 if (!isolated) {
11770 app = getProcessRecordLocked(appName, r.appInfo.uid);
11771 if (DEBUG_MU)
11772 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11773 if (app != null && app.thread != null) {
11774 try {
11775 app.addPackage(r.appInfo.packageName);
11776 realStartServiceLocked(r, app);
11777 return true;
11778 } catch (RemoteException e) {
11779 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11780 }
11781
11782 // If a dead object exception was thrown -- fall through to
11783 // restart the application.
11784 }
11785 } else {
11786 // If this service runs in an isolated process, then each time
11787 // we call startProcessLocked() we will get a new isolated
11788 // process, starting another process if we are currently waiting
11789 // for a previous process to come up. To deal with this, we store
11790 // in the service any current isolated process it is running in or
11791 // waiting to have come up.
11792 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011793 }
11794
Dianne Hackborn36124872009-10-08 16:22:03 -070011795 // Not running -- get it started, and enqueue this service record
11796 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011797 if (app == null) {
11798 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11799 "service", r.name, false, isolated)) == null) {
11800 Slog.w(TAG, "Unable to launch app "
11801 + r.appInfo.packageName + "/"
11802 + r.appInfo.uid + " for service "
11803 + r.intent.getIntent() + ": process is bad");
11804 bringDownServiceLocked(r, true);
11805 return false;
11806 }
11807 if (isolated) {
11808 r.isolatedProc = app;
11809 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011810 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011812 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011813 mPendingServices.add(r);
11814 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011816 return true;
11817 }
11818
11819 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011820 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821 //r.dump(" ");
11822
11823 // Does it still need to run?
11824 if (!force && r.startRequested) {
11825 return;
11826 }
11827 if (r.connections.size() > 0) {
11828 if (!force) {
11829 // XXX should probably keep a count of the number of auto-create
11830 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011831 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011833 ArrayList<ConnectionRecord> cr = it.next();
11834 for (int i=0; i<cr.size(); i++) {
11835 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11836 return;
11837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011838 }
11839 }
11840 }
11841
11842 // Report to all of the connections that the service is no longer
11843 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011844 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011845 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011846 ArrayList<ConnectionRecord> c = it.next();
11847 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011848 ConnectionRecord cr = c.get(i);
11849 // There is still a connection to the service that is
11850 // being brought down. Mark it as dead.
11851 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011852 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011853 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011854 } catch (Exception e) {
11855 Slog.w(TAG, "Failure disconnecting service " + r.name +
11856 " to connection " + c.get(i).conn.asBinder() +
11857 " (in " + c.get(i).binding.client.processName + ")", e);
11858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011859 }
11860 }
11861 }
11862
11863 // Tell the service that it has been unbound.
11864 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11865 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11866 while (it.hasNext()) {
11867 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011868 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011869 + ": hasBound=" + ibr.hasBound);
11870 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11871 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011872 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011873 updateOomAdjLocked(r.app);
11874 ibr.hasBound = false;
11875 r.app.thread.scheduleUnbindService(r,
11876 ibr.intent.getIntent());
11877 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011878 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011879 + r.shortName, e);
11880 serviceDoneExecutingLocked(r, true);
11881 }
11882 }
11883 }
11884 }
11885
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011886 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011887 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011888 System.identityHashCode(r), r.shortName,
11889 (r.app != null) ? r.app.pid : -1);
11890
Amith Yamasani742a6712011-05-04 14:49:28 -070011891 mServiceMap.removeServiceByName(r.name, r.userId);
11892 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011893 r.totalRestartCount = 0;
11894 unscheduleServiceRestartLocked(r);
11895
11896 // Also make sure it is not on the pending list.
11897 int N = mPendingServices.size();
11898 for (int i=0; i<N; i++) {
11899 if (mPendingServices.get(i) == r) {
11900 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011901 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011902 i--;
11903 N--;
11904 }
11905 }
11906
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011907 r.cancelNotification();
11908 r.isForeground = false;
11909 r.foregroundId = 0;
11910 r.foregroundNoti = null;
11911
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011912 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011913 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011914 r.pendingStarts.clear();
11915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011916 if (r.app != null) {
11917 synchronized (r.stats.getBatteryStats()) {
11918 r.stats.stopLaunchedLocked();
11919 }
11920 r.app.services.remove(r);
11921 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011923 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011924 mStoppingServices.add(r);
11925 updateOomAdjLocked(r.app);
11926 r.app.thread.scheduleStopService(r);
11927 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011928 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011929 + r.shortName, e);
11930 serviceDoneExecutingLocked(r, true);
11931 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011932 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011933 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011934 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011935 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011936 }
11937 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011938 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011939 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011940 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011941
11942 if (r.bindings.size() > 0) {
11943 r.bindings.clear();
11944 }
11945
11946 if (r.restarter instanceof ServiceRestarter) {
11947 ((ServiceRestarter)r.restarter).setService(null);
11948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011949 }
11950
11951 ComponentName startServiceLocked(IApplicationThread caller,
11952 Intent service, String resolvedType,
11953 int callingPid, int callingUid) {
11954 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011955 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011956 + " type=" + resolvedType + " args=" + service.getExtras());
11957
11958 if (caller != null) {
11959 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11960 if (callerApp == null) {
11961 throw new SecurityException(
11962 "Unable to find app for caller " + caller
11963 + " (pid=" + Binder.getCallingPid()
11964 + ") when starting service " + service);
11965 }
11966 }
11967
11968 ServiceLookupResult res =
11969 retrieveServiceLocked(service, resolvedType,
11970 callingPid, callingUid);
11971 if (res == null) {
11972 return null;
11973 }
11974 if (res.record == null) {
11975 return new ComponentName("!", res.permission != null
11976 ? res.permission : "private to package");
11977 }
11978 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -070011979 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
11980 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011981 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011982 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011983 }
11984 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011985 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011986 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn39792d22010-08-19 18:01:52 -070011987 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011988 r.lastActivity = SystemClock.uptimeMillis();
11989 synchronized (r.stats.getBatteryStats()) {
11990 r.stats.startRunningLocked();
11991 }
11992 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11993 return new ComponentName("!", "Service process is bad");
11994 }
11995 return r.name;
11996 }
11997 }
11998
11999 public ComponentName startService(IApplicationThread caller, Intent service,
12000 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012001 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012002 // Refuse possible leaked file descriptors
12003 if (service != null && service.hasFileDescriptors() == true) {
12004 throw new IllegalArgumentException("File descriptors passed in Intent");
12005 }
12006
Amith Yamasani742a6712011-05-04 14:49:28 -070012007 if (DEBUG_SERVICE)
12008 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012009 synchronized(this) {
12010 final int callingPid = Binder.getCallingPid();
12011 final int callingUid = Binder.getCallingUid();
12012 final long origId = Binder.clearCallingIdentity();
12013 ComponentName res = startServiceLocked(caller, service,
12014 resolvedType, callingPid, callingUid);
12015 Binder.restoreCallingIdentity(origId);
12016 return res;
12017 }
12018 }
12019
12020 ComponentName startServiceInPackage(int uid,
12021 Intent service, String resolvedType) {
12022 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070012023 if (DEBUG_SERVICE)
12024 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012025 final long origId = Binder.clearCallingIdentity();
12026 ComponentName res = startServiceLocked(null, service,
12027 resolvedType, -1, uid);
12028 Binder.restoreCallingIdentity(origId);
12029 return res;
12030 }
12031 }
12032
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012033 private void stopServiceLocked(ServiceRecord service) {
12034 synchronized (service.stats.getBatteryStats()) {
12035 service.stats.stopRunningLocked();
12036 }
12037 service.startRequested = false;
12038 service.callStart = false;
12039 bringDownServiceLocked(service, false);
12040 }
12041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012042 public int stopService(IApplicationThread caller, Intent service,
12043 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012044 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012045 // Refuse possible leaked file descriptors
12046 if (service != null && service.hasFileDescriptors() == true) {
12047 throw new IllegalArgumentException("File descriptors passed in Intent");
12048 }
12049
12050 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012051 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012052 + " type=" + resolvedType);
12053
12054 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12055 if (caller != null && callerApp == null) {
12056 throw new SecurityException(
12057 "Unable to find app for caller " + caller
12058 + " (pid=" + Binder.getCallingPid()
12059 + ") when stopping service " + service);
12060 }
12061
12062 // If this service is active, make sure it is stopped.
12063 ServiceLookupResult r = findServiceLocked(service, resolvedType);
12064 if (r != null) {
12065 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012066 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012067 try {
12068 stopServiceLocked(r.record);
12069 } finally {
12070 Binder.restoreCallingIdentity(origId);
12071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012072 return 1;
12073 }
12074 return -1;
12075 }
12076 }
12077
12078 return 0;
12079 }
12080
12081 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012082 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012083 // Refuse possible leaked file descriptors
12084 if (service != null && service.hasFileDescriptors() == true) {
12085 throw new IllegalArgumentException("File descriptors passed in Intent");
12086 }
12087
12088 IBinder ret = null;
12089
12090 synchronized(this) {
12091 ServiceLookupResult r = findServiceLocked(service, resolvedType);
12092
12093 if (r != null) {
12094 // r.record is null if findServiceLocked() failed the caller permission check
12095 if (r.record == null) {
12096 throw new SecurityException(
12097 "Permission Denial: Accessing service " + r.record.name
12098 + " from pid=" + Binder.getCallingPid()
12099 + ", uid=" + Binder.getCallingUid()
12100 + " requires " + r.permission);
12101 }
12102 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
12103 if (ib != null) {
12104 ret = ib.binder;
12105 }
12106 }
12107 }
12108
12109 return ret;
12110 }
12111
12112 public boolean stopServiceToken(ComponentName className, IBinder token,
12113 int startId) {
12114 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012115 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012116 + " " + token + " startId=" + startId);
12117 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012118 if (r != null) {
12119 if (startId >= 0) {
12120 // Asked to only stop if done with all work. Note that
12121 // to avoid leaks, we will take this as dropping all
12122 // start items up to and including this one.
12123 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12124 if (si != null) {
12125 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070012126 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
12127 cur.removeUriPermissionsLocked();
12128 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012129 break;
12130 }
12131 }
12132 }
12133
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012134 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012135 return false;
12136 }
12137
12138 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012139 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012140 + " is last, but have " + r.deliveredStarts.size()
12141 + " remaining args");
12142 }
12143 }
12144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012145 synchronized (r.stats.getBatteryStats()) {
12146 r.stats.stopRunningLocked();
12147 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012148 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012149 }
12150 final long origId = Binder.clearCallingIdentity();
12151 bringDownServiceLocked(r, false);
12152 Binder.restoreCallingIdentity(origId);
12153 return true;
12154 }
12155 }
12156 return false;
12157 }
12158
12159 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012160 int id, Notification notification, boolean removeNotification) {
12161 final long origId = Binder.clearCallingIdentity();
12162 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012163 synchronized(this) {
12164 ServiceRecord r = findServiceLocked(className, token);
12165 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012166 if (id != 0) {
12167 if (notification == null) {
12168 throw new IllegalArgumentException("null notification");
12169 }
12170 if (r.foregroundId != id) {
12171 r.cancelNotification();
12172 r.foregroundId = id;
12173 }
12174 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
12175 r.foregroundNoti = notification;
12176 r.isForeground = true;
12177 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012178 if (r.app != null) {
12179 updateServiceForegroundLocked(r.app, true);
12180 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012181 } else {
12182 if (r.isForeground) {
12183 r.isForeground = false;
12184 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070012185 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012186 updateServiceForegroundLocked(r.app, true);
12187 }
12188 }
12189 if (removeNotification) {
12190 r.cancelNotification();
12191 r.foregroundId = 0;
12192 r.foregroundNoti = null;
12193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012194 }
12195 }
12196 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012197 } finally {
12198 Binder.restoreCallingIdentity(origId);
12199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012200 }
12201
12202 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
12203 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070012204 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012205 if (sr.isForeground) {
12206 anyForeground = true;
12207 break;
12208 }
12209 }
12210 if (anyForeground != proc.foregroundServices) {
12211 proc.foregroundServices = anyForeground;
12212 if (oomAdj) {
12213 updateOomAdjLocked();
12214 }
12215 }
12216 }
12217
12218 public int bindService(IApplicationThread caller, IBinder token,
12219 Intent service, String resolvedType,
12220 IServiceConnection connection, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012221 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012222 // Refuse possible leaked file descriptors
12223 if (service != null && service.hasFileDescriptors() == true) {
12224 throw new IllegalArgumentException("File descriptors passed in Intent");
12225 }
12226
12227 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012228 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012229 + " type=" + resolvedType + " conn=" + connection.asBinder()
12230 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070012231 if (DEBUG_MU)
12232 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
12233 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012234 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12235 if (callerApp == null) {
12236 throw new SecurityException(
12237 "Unable to find app for caller " + caller
12238 + " (pid=" + Binder.getCallingPid()
12239 + ") when binding service " + service);
12240 }
12241
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012242 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012243 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012244 activity = mMainStack.isInStackLocked(token);
12245 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012246 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012247 return 0;
12248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012249 }
12250
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012251 int clientLabel = 0;
12252 PendingIntent clientIntent = null;
12253
12254 if (callerApp.info.uid == Process.SYSTEM_UID) {
12255 // Hacky kind of thing -- allow system stuff to tell us
12256 // what they are, so we can report this elsewhere for
12257 // others to know why certain services are running.
12258 try {
12259 clientIntent = (PendingIntent)service.getParcelableExtra(
12260 Intent.EXTRA_CLIENT_INTENT);
12261 } catch (RuntimeException e) {
12262 }
12263 if (clientIntent != null) {
12264 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
12265 if (clientLabel != 0) {
12266 // There are no useful extras in the intent, trash them.
12267 // System code calling with this stuff just needs to know
12268 // this will happen.
12269 service = service.cloneFilter();
12270 }
12271 }
12272 }
12273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012274 ServiceLookupResult res =
12275 retrieveServiceLocked(service, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -070012276 Binder.getCallingPid(), Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012277 if (res == null) {
12278 return 0;
12279 }
12280 if (res.record == null) {
12281 return -1;
12282 }
12283 ServiceRecord s = res.record;
12284
12285 final long origId = Binder.clearCallingIdentity();
12286
12287 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012288 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012289 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012290 }
12291
12292 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
12293 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012294 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012295
12296 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012297 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12298 if (clist == null) {
12299 clist = new ArrayList<ConnectionRecord>();
12300 s.connections.put(binder, clist);
12301 }
12302 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012303 b.connections.add(c);
12304 if (activity != null) {
12305 if (activity.connections == null) {
12306 activity.connections = new HashSet<ConnectionRecord>();
12307 }
12308 activity.connections.add(c);
12309 }
12310 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012311 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12312 b.client.hasAboveClient = true;
12313 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012314 clist = mServiceConnections.get(binder);
12315 if (clist == null) {
12316 clist = new ArrayList<ConnectionRecord>();
12317 mServiceConnections.put(binder, clist);
12318 }
12319 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012320
12321 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
12322 s.lastActivity = SystemClock.uptimeMillis();
12323 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
12324 return 0;
12325 }
12326 }
12327
12328 if (s.app != null) {
12329 // This could have made the service more important.
12330 updateOomAdjLocked(s.app);
12331 }
12332
Joe Onorato8a9b2202010-02-26 18:56:32 -080012333 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012334 + ": received=" + b.intent.received
12335 + " apps=" + b.intent.apps.size()
12336 + " doRebind=" + b.intent.doRebind);
12337
12338 if (s.app != null && b.intent.received) {
12339 // Service is already running, so we can immediately
12340 // publish the connection.
12341 try {
12342 c.conn.connected(s.name, b.intent.binder);
12343 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012344 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012345 + " to connection " + c.conn.asBinder()
12346 + " (in " + c.binding.client.processName + ")", e);
12347 }
12348
12349 // If this is the first app connected back to this binding,
12350 // and the service had previously asked to be told when
12351 // rebound, then do so.
12352 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
12353 requestServiceBindingLocked(s, b.intent, true);
12354 }
12355 } else if (!b.intent.requested) {
12356 requestServiceBindingLocked(s, b.intent, false);
12357 }
12358
12359 Binder.restoreCallingIdentity(origId);
12360 }
12361
12362 return 1;
12363 }
12364
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012365 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012366 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012367 IBinder binder = c.conn.asBinder();
12368 AppBindRecord b = c.binding;
12369 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012370 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12371 if (clist != null) {
12372 clist.remove(c);
12373 if (clist.size() == 0) {
12374 s.connections.remove(binder);
12375 }
12376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012377 b.connections.remove(c);
12378 if (c.activity != null && c.activity != skipAct) {
12379 if (c.activity.connections != null) {
12380 c.activity.connections.remove(c);
12381 }
12382 }
12383 if (b.client != skipApp) {
12384 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012385 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12386 b.client.updateHasAboveClientLocked();
12387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012388 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012389 clist = mServiceConnections.get(binder);
12390 if (clist != null) {
12391 clist.remove(c);
12392 if (clist.size() == 0) {
12393 mServiceConnections.remove(binder);
12394 }
12395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012396
12397 if (b.connections.size() == 0) {
12398 b.intent.apps.remove(b.client);
12399 }
12400
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012401 if (!c.serviceDead) {
12402 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
12403 + ": shouldUnbind=" + b.intent.hasBound);
12404 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
12405 && b.intent.hasBound) {
12406 try {
12407 bumpServiceExecutingLocked(s, "unbind");
12408 updateOomAdjLocked(s.app);
12409 b.intent.hasBound = false;
12410 // Assume the client doesn't want to know about a rebind;
12411 // we will deal with that later if it asks for one.
12412 b.intent.doRebind = false;
12413 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
12414 } catch (Exception e) {
12415 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
12416 serviceDoneExecutingLocked(s, true);
12417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012418 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012419
12420 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
12421 bringDownServiceLocked(s, false);
12422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012423 }
12424 }
12425
12426 public boolean unbindService(IServiceConnection connection) {
12427 synchronized (this) {
12428 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012429 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012430 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
12431 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012432 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012433 + connection.asBinder());
12434 return false;
12435 }
12436
12437 final long origId = Binder.clearCallingIdentity();
12438
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012439 while (clist.size() > 0) {
12440 ConnectionRecord r = clist.get(0);
12441 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012442
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012443 if (r.binding.service.app != null) {
12444 // This could have made the service less important.
12445 updateOomAdjLocked(r.binding.service.app);
12446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012447 }
12448
12449 Binder.restoreCallingIdentity(origId);
12450 }
12451
12452 return true;
12453 }
12454
12455 public void publishService(IBinder token, Intent intent, IBinder service) {
12456 // Refuse possible leaked file descriptors
12457 if (intent != null && intent.hasFileDescriptors() == true) {
12458 throw new IllegalArgumentException("File descriptors passed in Intent");
12459 }
12460
12461 synchronized(this) {
12462 if (!(token instanceof ServiceRecord)) {
12463 throw new IllegalArgumentException("Invalid service token");
12464 }
12465 ServiceRecord r = (ServiceRecord)token;
12466
12467 final long origId = Binder.clearCallingIdentity();
12468
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012469 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012470 + " " + intent + ": " + service);
12471 if (r != null) {
12472 Intent.FilterComparison filter
12473 = new Intent.FilterComparison(intent);
12474 IntentBindRecord b = r.bindings.get(filter);
12475 if (b != null && !b.received) {
12476 b.binder = service;
12477 b.requested = true;
12478 b.received = true;
12479 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012480 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012481 = r.connections.values().iterator();
12482 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012483 ArrayList<ConnectionRecord> clist = it.next();
12484 for (int i=0; i<clist.size(); i++) {
12485 ConnectionRecord c = clist.get(i);
12486 if (!filter.equals(c.binding.intent.intent)) {
12487 if (DEBUG_SERVICE) Slog.v(
12488 TAG, "Not publishing to: " + c);
12489 if (DEBUG_SERVICE) Slog.v(
12490 TAG, "Bound intent: " + c.binding.intent.intent);
12491 if (DEBUG_SERVICE) Slog.v(
12492 TAG, "Published intent: " + intent);
12493 continue;
12494 }
12495 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12496 try {
12497 c.conn.connected(r.name, service);
12498 } catch (Exception e) {
12499 Slog.w(TAG, "Failure sending service " + r.name +
12500 " to connection " + c.conn.asBinder() +
12501 " (in " + c.binding.client.processName + ")", e);
12502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012503 }
12504 }
12505 }
12506 }
12507
12508 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12509
12510 Binder.restoreCallingIdentity(origId);
12511 }
12512 }
12513 }
12514
12515 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12516 // Refuse possible leaked file descriptors
12517 if (intent != null && intent.hasFileDescriptors() == true) {
12518 throw new IllegalArgumentException("File descriptors passed in Intent");
12519 }
12520
12521 synchronized(this) {
12522 if (!(token instanceof ServiceRecord)) {
12523 throw new IllegalArgumentException("Invalid service token");
12524 }
12525 ServiceRecord r = (ServiceRecord)token;
12526
12527 final long origId = Binder.clearCallingIdentity();
12528
12529 if (r != null) {
12530 Intent.FilterComparison filter
12531 = new Intent.FilterComparison(intent);
12532 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012533 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012534 + " at " + b + ": apps="
12535 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012536
12537 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012538 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012539 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012540 // Applications have already bound since the last
12541 // unbind, so just rebind right here.
12542 requestServiceBindingLocked(r, b, true);
12543 } else {
12544 // Note to tell the service the next time there is
12545 // a new client.
12546 b.doRebind = true;
12547 }
12548 }
12549
Per Edelberg78f9fff2010-08-30 20:01:35 +020012550 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012551
12552 Binder.restoreCallingIdentity(origId);
12553 }
12554 }
12555 }
12556
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012557 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012558 synchronized(this) {
12559 if (!(token instanceof ServiceRecord)) {
12560 throw new IllegalArgumentException("Invalid service token");
12561 }
12562 ServiceRecord r = (ServiceRecord)token;
12563 boolean inStopping = mStoppingServices.contains(token);
12564 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012565 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012566 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012567 + " with incorrect token: given " + token
12568 + ", expected " + r);
12569 return;
12570 }
12571
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012572 if (type == 1) {
12573 // This is a call from a service start... take care of
12574 // book-keeping.
12575 r.callStart = true;
12576 switch (res) {
12577 case Service.START_STICKY_COMPATIBILITY:
12578 case Service.START_STICKY: {
12579 // We are done with the associated start arguments.
12580 r.findDeliveredStart(startId, true);
12581 // Don't stop if killed.
12582 r.stopIfKilled = false;
12583 break;
12584 }
12585 case Service.START_NOT_STICKY: {
12586 // We are done with the associated start arguments.
12587 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012588 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012589 // There is no more work, and this service
12590 // doesn't want to hang around if killed.
12591 r.stopIfKilled = true;
12592 }
12593 break;
12594 }
12595 case Service.START_REDELIVER_INTENT: {
12596 // We'll keep this item until they explicitly
12597 // call stop for it, but keep track of the fact
12598 // that it was delivered.
12599 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12600 if (si != null) {
12601 si.deliveryCount = 0;
12602 si.doneExecutingCount++;
12603 // Don't stop if killed.
12604 r.stopIfKilled = true;
12605 }
12606 break;
12607 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012608 case Service.START_TASK_REMOVED_COMPLETE: {
12609 // Special processing for onTaskRemoved(). Don't
12610 // impact normal onStartCommand() processing.
12611 r.findDeliveredStart(startId, true);
12612 break;
12613 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012614 default:
12615 throw new IllegalArgumentException(
12616 "Unknown service start result: " + res);
12617 }
12618 if (res == Service.START_STICKY_COMPATIBILITY) {
12619 r.callStart = false;
12620 }
12621 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012622 if (DEBUG_MU)
12623 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12624 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012625 final long origId = Binder.clearCallingIdentity();
12626 serviceDoneExecutingLocked(r, inStopping);
12627 Binder.restoreCallingIdentity(origId);
12628 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012629 Slog.w(TAG, "Done executing unknown service from pid "
12630 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012631 }
12632 }
12633 }
12634
12635 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012636 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12637 + ": nesting=" + r.executeNesting
12638 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012639 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012640 r.executeNesting--;
12641 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012642 if (DEBUG_SERVICE) Slog.v(TAG,
12643 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012644 r.app.executingServices.remove(r);
12645 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012646 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12647 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012648 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12649 }
12650 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012651 if (DEBUG_SERVICE) Slog.v(TAG,
12652 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012653 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012654 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012655 }
12656 updateOomAdjLocked(r.app);
12657 }
12658 }
12659
12660 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012661 String anrMessage = null;
12662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012663 synchronized(this) {
12664 if (proc.executingServices.size() == 0 || proc.thread == null) {
12665 return;
12666 }
12667 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12668 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12669 ServiceRecord timeout = null;
12670 long nextTime = 0;
12671 while (it.hasNext()) {
12672 ServiceRecord sr = it.next();
12673 if (sr.executingStart < maxTime) {
12674 timeout = sr;
12675 break;
12676 }
12677 if (sr.executingStart > nextTime) {
12678 nextTime = sr.executingStart;
12679 }
12680 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012681 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012682 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012683 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012684 } else {
12685 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12686 msg.obj = proc;
12687 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12688 }
12689 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012690
12691 if (anrMessage != null) {
12692 appNotResponding(proc, null, null, anrMessage);
12693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012694 }
12695
12696 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012697 // BACKUP AND RESTORE
12698 // =========================================================
12699
12700 // Cause the target app to be launched if necessary and its backup agent
12701 // instantiated. The backup agent will invoke backupAgentCreated() on the
12702 // activity manager to announce its creation.
12703 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012704 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012705 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12706
12707 synchronized(this) {
12708 // !!! TODO: currently no check here that we're already bound
12709 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12710 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12711 synchronized (stats) {
12712 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12713 }
12714
Dianne Hackborne7f97212011-02-24 14:40:20 -080012715 // Backup agent is now in use, its package can't be stopped.
12716 try {
12717 AppGlobals.getPackageManager().setPackageStoppedState(
12718 app.packageName, false);
12719 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012720 } catch (IllegalArgumentException e) {
12721 Slog.w(TAG, "Failed trying to unstop package "
12722 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012723 }
12724
Christopher Tate181fafa2009-05-14 11:12:14 -070012725 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012726 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12727 ? new ComponentName(app.packageName, app.backupAgentName)
12728 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012729 // startProcessLocked() returns existing proc's record if it's already running
12730 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012731 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012732 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012733 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012734 return false;
12735 }
12736
12737 r.app = proc;
12738 mBackupTarget = r;
12739 mBackupAppName = app.packageName;
12740
Christopher Tate6fa95972009-06-05 18:43:55 -070012741 // Try not to kill the process during backup
12742 updateOomAdjLocked(proc);
12743
Christopher Tate181fafa2009-05-14 11:12:14 -070012744 // If the process is already attached, schedule the creation of the backup agent now.
12745 // If it is not yet live, this will be done when it attaches to the framework.
12746 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012747 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012748 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012749 proc.thread.scheduleCreateBackupAgent(app,
12750 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012751 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012752 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012753 }
12754 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012755 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012756 }
12757 // Invariants: at this point, the target app process exists and the application
12758 // is either already running or in the process of coming up. mBackupTarget and
12759 // mBackupAppName describe the app, so that when it binds back to the AM we
12760 // know that it's scheduled for a backup-agent operation.
12761 }
12762
12763 return true;
12764 }
12765
12766 // A backup agent has just come up
12767 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012768 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012769 + " = " + agent);
12770
12771 synchronized(this) {
12772 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012773 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012774 return;
12775 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012776 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012777
Dianne Hackborn06740692010-09-22 22:46:21 -070012778 long oldIdent = Binder.clearCallingIdentity();
12779 try {
12780 IBackupManager bm = IBackupManager.Stub.asInterface(
12781 ServiceManager.getService(Context.BACKUP_SERVICE));
12782 bm.agentConnected(agentPackageName, agent);
12783 } catch (RemoteException e) {
12784 // can't happen; the backup manager service is local
12785 } catch (Exception e) {
12786 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12787 e.printStackTrace();
12788 } finally {
12789 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012790 }
12791 }
12792
12793 // done with this agent
12794 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012795 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012796 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012797 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012798 return;
12799 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012800
12801 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012802 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012803 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012804 return;
12805 }
12806
Christopher Tate181fafa2009-05-14 11:12:14 -070012807 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012808 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012809 return;
12810 }
12811
Christopher Tate6fa95972009-06-05 18:43:55 -070012812 ProcessRecord proc = mBackupTarget.app;
12813 mBackupTarget = null;
12814 mBackupAppName = null;
12815
12816 // Not backing this app up any more; reset its OOM adjustment
12817 updateOomAdjLocked(proc);
12818
Christopher Tatec7b31e32009-06-10 15:49:30 -070012819 // If the app crashed during backup, 'thread' will be null here
12820 if (proc.thread != null) {
12821 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012822 proc.thread.scheduleDestroyBackupAgent(appInfo,
12823 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012824 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012825 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012826 e.printStackTrace();
12827 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012828 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012829 }
12830 }
12831 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012832 // BROADCASTS
12833 // =========================================================
12834
Josh Bartel7f208742010-02-25 11:01:44 -060012835 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012836 List cur) {
12837 final ContentResolver resolver = mContext.getContentResolver();
12838 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12839 if (list == null) {
12840 return cur;
12841 }
12842 int N = list.size();
12843 for (int i=0; i<N; i++) {
12844 Intent intent = list.get(i);
12845 if (filter.match(resolver, intent, true, TAG) >= 0) {
12846 if (cur == null) {
12847 cur = new ArrayList<Intent>();
12848 }
12849 cur.add(intent);
12850 }
12851 }
12852 return cur;
12853 }
12854
Christopher Tatef46723b2012-01-26 14:19:24 -080012855 boolean isPendingBroadcastProcessLocked(int pid) {
12856 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12857 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012859
Christopher Tatef46723b2012-01-26 14:19:24 -080012860 void skipPendingBroadcastLocked(int pid) {
12861 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12862 for (BroadcastQueue queue : mBroadcastQueues) {
12863 queue.skipPendingBroadcastLocked(pid);
12864 }
12865 }
12866
12867 // The app just attached; send any pending broadcasts that it should receive
12868 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12869 boolean didSomething = false;
12870 for (BroadcastQueue queue : mBroadcastQueues) {
12871 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012872 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012873 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012874 }
12875
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012876 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012877 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012878 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012879 synchronized(this) {
12880 ProcessRecord callerApp = null;
12881 if (caller != null) {
12882 callerApp = getRecordForAppLocked(caller);
12883 if (callerApp == null) {
12884 throw new SecurityException(
12885 "Unable to find app for caller " + caller
12886 + " (pid=" + Binder.getCallingPid()
12887 + ") when registering receiver " + receiver);
12888 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012889 if (callerApp.info.uid != Process.SYSTEM_UID &&
12890 !callerApp.pkgList.contains(callerPackage)) {
12891 throw new SecurityException("Given caller package " + callerPackage
12892 + " is not running in process " + callerApp);
12893 }
12894 } else {
12895 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012896 }
12897
12898 List allSticky = null;
12899
12900 // Look for any matching sticky broadcasts...
12901 Iterator actions = filter.actionsIterator();
12902 if (actions != null) {
12903 while (actions.hasNext()) {
12904 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012905 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012906 }
12907 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012908 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012909 }
12910
12911 // The first sticky in the list is returned directly back to
12912 // the client.
12913 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12914
Joe Onorato8a9b2202010-02-26 18:56:32 -080012915 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012916 + ": " + sticky);
12917
12918 if (receiver == null) {
12919 return sticky;
12920 }
12921
12922 ReceiverList rl
12923 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12924 if (rl == null) {
12925 rl = new ReceiverList(this, callerApp,
12926 Binder.getCallingPid(),
12927 Binder.getCallingUid(), receiver);
12928 if (rl.app != null) {
12929 rl.app.receivers.add(rl);
12930 } else {
12931 try {
12932 receiver.asBinder().linkToDeath(rl, 0);
12933 } catch (RemoteException e) {
12934 return sticky;
12935 }
12936 rl.linkedToDeath = true;
12937 }
12938 mRegisteredReceivers.put(receiver.asBinder(), rl);
12939 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012940 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012941 rl.add(bf);
12942 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012943 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012944 }
12945 mReceiverResolver.addFilter(bf);
12946
12947 // Enqueue broadcasts for all existing stickies that match
12948 // this filter.
12949 if (allSticky != null) {
12950 ArrayList receivers = new ArrayList();
12951 receivers.add(bf);
12952
12953 int N = allSticky.size();
12954 for (int i=0; i<N; i++) {
12955 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012956 BroadcastQueue queue = broadcastQueueForIntent(intent);
12957 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012958 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012959 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012960 queue.enqueueParallelBroadcastLocked(r);
12961 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012962 }
12963 }
12964
12965 return sticky;
12966 }
12967 }
12968
12969 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012970 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012971
Christopher Tatef46723b2012-01-26 14:19:24 -080012972 final long origId = Binder.clearCallingIdentity();
12973 try {
12974 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012975
Christopher Tatef46723b2012-01-26 14:19:24 -080012976 synchronized(this) {
12977 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012978 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012979 if (rl != null) {
12980 if (rl.curBroadcast != null) {
12981 BroadcastRecord r = rl.curBroadcast;
12982 final boolean doNext = finishReceiverLocked(
12983 receiver.asBinder(), r.resultCode, r.resultData,
12984 r.resultExtras, r.resultAbort, true);
12985 if (doNext) {
12986 doTrim = true;
12987 r.queue.processNextBroadcast(false);
12988 }
12989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012990
Christopher Tatef46723b2012-01-26 14:19:24 -080012991 if (rl.app != null) {
12992 rl.app.receivers.remove(rl);
12993 }
12994 removeReceiverLocked(rl);
12995 if (rl.linkedToDeath) {
12996 rl.linkedToDeath = false;
12997 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012999 }
13000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013001
Christopher Tatef46723b2012-01-26 14:19:24 -080013002 // If we actually concluded any broadcasts, we might now be able
13003 // to trim the recipients' apps from our working set
13004 if (doTrim) {
13005 trimApplications();
13006 return;
13007 }
13008
13009 } finally {
13010 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013012 }
13013
13014 void removeReceiverLocked(ReceiverList rl) {
13015 mRegisteredReceivers.remove(rl.receiver.asBinder());
13016 int N = rl.size();
13017 for (int i=0; i<N; i++) {
13018 mReceiverResolver.removeFilter(rl.get(i));
13019 }
13020 }
13021
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070013022 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
13023 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13024 ProcessRecord r = mLruProcesses.get(i);
13025 if (r.thread != null) {
13026 try {
13027 r.thread.dispatchPackageBroadcast(cmd, packages);
13028 } catch (RemoteException ex) {
13029 }
13030 }
13031 }
13032 }
13033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013034 private final int broadcastIntentLocked(ProcessRecord callerApp,
13035 String callerPackage, Intent intent, String resolvedType,
13036 IIntentReceiver resultTo, int resultCode, String resultData,
13037 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013038 boolean ordered, boolean sticky, int callingPid, int callingUid,
13039 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013040 intent = new Intent(intent);
13041
Dianne Hackborne7f97212011-02-24 14:40:20 -080013042 // By default broadcasts do not go to stopped apps.
13043 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
13044
Joe Onorato8a9b2202010-02-26 18:56:32 -080013045 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013046 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
13047 + " ordered=" + ordered);
13048 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013049 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013050 }
13051
13052 // Handle special intents: if this broadcast is from the package
13053 // manager about a package being removed, we need to remove all of
13054 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013055 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013056 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013057 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
13058 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080013059 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013060 || uidRemoved) {
13061 if (checkComponentPermission(
13062 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080013063 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013064 == PackageManager.PERMISSION_GRANTED) {
13065 if (uidRemoved) {
13066 final Bundle intentExtras = intent.getExtras();
13067 final int uid = intentExtras != null
13068 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
13069 if (uid >= 0) {
13070 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
13071 synchronized (bs) {
13072 bs.removeUidStatsLocked(uid);
13073 }
13074 }
13075 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013076 // If resources are unvailble just force stop all
13077 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080013078 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013079 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
13080 if (list != null && (list.length > 0)) {
13081 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070013082 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013083 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070013084 sendPackageBroadcastLocked(
13085 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013086 }
13087 } else {
13088 Uri data = intent.getData();
13089 String ssp;
13090 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
13091 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
13092 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070013093 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070013094 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013095 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070013096 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
13097 new String[] {ssp});
13098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013099 }
13100 }
13101 }
13102 } else {
13103 String msg = "Permission Denial: " + intent.getAction()
13104 + " broadcast from " + callerPackage + " (pid=" + callingPid
13105 + ", uid=" + callingUid + ")"
13106 + " requires "
13107 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013108 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013109 throw new SecurityException(msg);
13110 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013111
13112 // Special case for adding a package: by default turn on compatibility
13113 // mode.
13114 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070013115 Uri data = intent.getData();
13116 String ssp;
13117 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
13118 mCompatModePackages.handlePackageAddedLocked(ssp,
13119 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013121 }
13122
13123 /*
13124 * If this is the time zone changed action, queue up a message that will reset the timezone
13125 * of all currently running processes. This message will get queued up before the broadcast
13126 * happens.
13127 */
13128 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
13129 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
13130 }
13131
Robert Greenwalt03595d02010-11-02 14:08:23 -070013132 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
13133 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
13134 }
13135
Robert Greenwalt434203a2010-10-11 16:00:27 -070013136 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
13137 ProxyProperties proxy = intent.getParcelableExtra("proxy");
13138 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
13139 }
13140
Dianne Hackborn854060af2009-07-09 18:14:31 -070013141 /*
13142 * Prevent non-system code (defined here to be non-persistent
13143 * processes) from sending protected broadcasts.
13144 */
13145 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
13146 || callingUid == Process.SHELL_UID || callingUid == 0) {
13147 // Always okay.
13148 } else if (callerApp == null || !callerApp.persistent) {
13149 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013150 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070013151 intent.getAction())) {
13152 String msg = "Permission Denial: not allowed to send broadcast "
13153 + intent.getAction() + " from pid="
13154 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013155 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070013156 throw new SecurityException(msg);
13157 }
13158 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013159 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070013160 return BROADCAST_SUCCESS;
13161 }
13162 }
13163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013164 // Add to the sticky list if requested.
13165 if (sticky) {
13166 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
13167 callingPid, callingUid)
13168 != PackageManager.PERMISSION_GRANTED) {
13169 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
13170 + callingPid + ", uid=" + callingUid
13171 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013172 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013173 throw new SecurityException(msg);
13174 }
13175 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013176 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013177 + " and enforce permission " + requiredPermission);
13178 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
13179 }
13180 if (intent.getComponent() != null) {
13181 throw new SecurityException(
13182 "Sticky broadcasts can't target a specific component");
13183 }
13184 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13185 if (list == null) {
13186 list = new ArrayList<Intent>();
13187 mStickyBroadcasts.put(intent.getAction(), list);
13188 }
13189 int N = list.size();
13190 int i;
13191 for (i=0; i<N; i++) {
13192 if (intent.filterEquals(list.get(i))) {
13193 // This sticky already exists, replace it.
13194 list.set(i, new Intent(intent));
13195 break;
13196 }
13197 }
13198 if (i >= N) {
13199 list.add(new Intent(intent));
13200 }
13201 }
13202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013203 // Figure out who all will receive this broadcast.
13204 List receivers = null;
13205 List<BroadcastFilter> registeredReceivers = null;
13206 try {
13207 if (intent.getComponent() != null) {
13208 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013209 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070013210 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013211 if (ai != null) {
13212 receivers = new ArrayList();
13213 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070013214 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013215 receivers.add(ri);
13216 }
13217 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070013218 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013219 // Need to resolve the intent to interested receivers...
13220 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
13221 == 0) {
13222 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013223 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013224 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013225 }
Mihai Preda074edef2009-05-18 17:13:31 +020013226 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013227 }
13228 } catch (RemoteException ex) {
13229 // pm is in same process, this will never happen.
13230 }
13231
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013232 final boolean replacePending =
13233 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
13234
Joe Onorato8a9b2202010-02-26 18:56:32 -080013235 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013236 + " replacePending=" + replacePending);
13237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013238 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
13239 if (!ordered && NR > 0) {
13240 // If we are not serializing this broadcast, then send the
13241 // registered receivers separately so they don't wait for the
13242 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080013243 final BroadcastQueue queue = broadcastQueueForIntent(intent);
13244 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013245 callerPackage, callingPid, callingUid, requiredPermission,
13246 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013247 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013248 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080013249 TAG, "Enqueueing parallel broadcast " + r);
13250 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013251 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013252 queue.enqueueParallelBroadcastLocked(r);
13253 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013255 registeredReceivers = null;
13256 NR = 0;
13257 }
13258
13259 // Merge into one list.
13260 int ir = 0;
13261 if (receivers != null) {
13262 // A special case for PACKAGE_ADDED: do not allow the package
13263 // being added to see this broadcast. This prevents them from
13264 // using this as a back door to get run as soon as they are
13265 // installed. Maybe in the future we want to have a special install
13266 // broadcast or such for apps, but we'd like to deliberately make
13267 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013268 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013269 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
13270 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
13271 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013272 Uri data = intent.getData();
13273 if (data != null) {
13274 String pkgName = data.getSchemeSpecificPart();
13275 if (pkgName != null) {
13276 skipPackages = new String[] { pkgName };
13277 }
13278 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013279 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013280 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070013281 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013282 if (skipPackages != null && (skipPackages.length > 0)) {
13283 for (String skipPackage : skipPackages) {
13284 if (skipPackage != null) {
13285 int NT = receivers.size();
13286 for (int it=0; it<NT; it++) {
13287 ResolveInfo curt = (ResolveInfo)receivers.get(it);
13288 if (curt.activityInfo.packageName.equals(skipPackage)) {
13289 receivers.remove(it);
13290 it--;
13291 NT--;
13292 }
13293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013294 }
13295 }
13296 }
13297
13298 int NT = receivers != null ? receivers.size() : 0;
13299 int it = 0;
13300 ResolveInfo curt = null;
13301 BroadcastFilter curr = null;
13302 while (it < NT && ir < NR) {
13303 if (curt == null) {
13304 curt = (ResolveInfo)receivers.get(it);
13305 }
13306 if (curr == null) {
13307 curr = registeredReceivers.get(ir);
13308 }
13309 if (curr.getPriority() >= curt.priority) {
13310 // Insert this broadcast record into the final list.
13311 receivers.add(it, curr);
13312 ir++;
13313 curr = null;
13314 it++;
13315 NT++;
13316 } else {
13317 // Skip to the next ResolveInfo in the final list.
13318 it++;
13319 curt = null;
13320 }
13321 }
13322 }
13323 while (ir < NR) {
13324 if (receivers == null) {
13325 receivers = new ArrayList();
13326 }
13327 receivers.add(registeredReceivers.get(ir));
13328 ir++;
13329 }
13330
13331 if ((receivers != null && receivers.size() > 0)
13332 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013333 BroadcastQueue queue = broadcastQueueForIntent(intent);
13334 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013335 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013336 receivers, resultTo, resultCode, resultData, map, ordered,
13337 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013338 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013339 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080013340 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013341 if (DEBUG_BROADCAST) {
13342 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013343 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013344 }
Christopher Tatef46723b2012-01-26 14:19:24 -080013345 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013346 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013347 queue.enqueueOrderedBroadcastLocked(r);
13348 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013350 }
13351
13352 return BROADCAST_SUCCESS;
13353 }
13354
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013355 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013356 // Refuse possible leaked file descriptors
13357 if (intent != null && intent.hasFileDescriptors() == true) {
13358 throw new IllegalArgumentException("File descriptors passed in Intent");
13359 }
13360
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013361 int flags = intent.getFlags();
13362
13363 if (!mProcessesReady) {
13364 // if the caller really truly claims to know what they're doing, go
13365 // ahead and allow the broadcast without launching any receivers
13366 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
13367 intent = new Intent(intent);
13368 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13369 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
13370 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
13371 + " before boot completion");
13372 throw new IllegalStateException("Cannot broadcast before boot completed");
13373 }
13374 }
13375
13376 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
13377 throw new IllegalArgumentException(
13378 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
13379 }
13380
13381 return intent;
13382 }
13383
13384 public final int broadcastIntent(IApplicationThread caller,
13385 Intent intent, String resolvedType, IIntentReceiver resultTo,
13386 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013387 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013388 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013389 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013390 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070013391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013392 final ProcessRecord callerApp = getRecordForAppLocked(caller);
13393 final int callingPid = Binder.getCallingPid();
13394 final int callingUid = Binder.getCallingUid();
13395 final long origId = Binder.clearCallingIdentity();
13396 int res = broadcastIntentLocked(callerApp,
13397 callerApp != null ? callerApp.info.packageName : null,
13398 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070013399 resultCode, resultData, map, requiredPermission, serialized, sticky,
13400 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013401 Binder.restoreCallingIdentity(origId);
13402 return res;
13403 }
13404 }
13405
13406 int broadcastIntentInPackage(String packageName, int uid,
13407 Intent intent, String resolvedType, IIntentReceiver resultTo,
13408 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013409 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013410 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013411 intent = verifyBroadcastLocked(intent);
13412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013413 final long origId = Binder.clearCallingIdentity();
13414 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
13415 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013416 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013417 Binder.restoreCallingIdentity(origId);
13418 return res;
13419 }
13420 }
13421
Amith Yamasani742a6712011-05-04 14:49:28 -070013422 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
13423 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013424 // Refuse possible leaked file descriptors
13425 if (intent != null && intent.hasFileDescriptors() == true) {
13426 throw new IllegalArgumentException("File descriptors passed in Intent");
13427 }
13428
13429 synchronized(this) {
13430 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13431 != PackageManager.PERMISSION_GRANTED) {
13432 String msg = "Permission Denial: unbroadcastIntent() from pid="
13433 + Binder.getCallingPid()
13434 + ", uid=" + Binder.getCallingUid()
13435 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013436 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013437 throw new SecurityException(msg);
13438 }
13439 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13440 if (list != null) {
13441 int N = list.size();
13442 int i;
13443 for (i=0; i<N; i++) {
13444 if (intent.filterEquals(list.get(i))) {
13445 list.remove(i);
13446 break;
13447 }
13448 }
13449 }
13450 }
13451 }
13452
13453 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13454 String resultData, Bundle resultExtras, boolean resultAbort,
13455 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013456 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13457 if (r == null) {
13458 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013459 return false;
13460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013461
Christopher Tatef46723b2012-01-26 14:19:24 -080013462 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13463 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013464 }
13465
13466 public void finishReceiver(IBinder who, int resultCode, String resultData,
13467 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013468 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013469
13470 // Refuse possible leaked file descriptors
13471 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13472 throw new IllegalArgumentException("File descriptors passed in Bundle");
13473 }
13474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013475 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013476 try {
13477 boolean doNext = false;
13478 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013479
Christopher Tatef46723b2012-01-26 14:19:24 -080013480 synchronized(this) {
13481 r = broadcastRecordForReceiverLocked(who);
13482 if (r != null) {
13483 doNext = r.queue.finishReceiverLocked(r, resultCode,
13484 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013486 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013487
Christopher Tatef46723b2012-01-26 14:19:24 -080013488 if (doNext) {
13489 r.queue.processNextBroadcast(false);
13490 }
13491 trimApplications();
13492 } finally {
13493 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013495 }
13496
13497 private final void processCurBroadcastLocked(BroadcastRecord r,
13498 ProcessRecord app) throws RemoteException {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013499 if (DEBUG_BROADCAST) Slog.v(TAG,
13500 "Process cur broadcast " + r + " for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013501 if (app.thread == null) {
13502 throw new RemoteException();
13503 }
13504 r.receiver = app.thread.asBinder();
13505 r.curApp = app;
13506 app.curReceiver = r;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013507 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013508
13509 // Tell the application to launch this receiver.
13510 r.intent.setComponent(r.curComponent);
13511
13512 boolean started = false;
13513 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013514 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013515 "Delivering to component " + r.curComponent
13516 + ": " + r);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070013517 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013518 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
Dianne Hackborne2515ee2011-04-27 18:52:56 -040013519 compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013520 r.resultCode, r.resultData, r.resultExtras, r.ordered);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013521 if (DEBUG_BROADCAST) Slog.v(TAG,
13522 "Process cur broadcast " + r + " DELIVERED for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013523 started = true;
13524 } finally {
13525 if (!started) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013526 if (DEBUG_BROADCAST) Slog.v(TAG,
13527 "Process cur broadcast " + r + ": NOT STARTED!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013528 r.receiver = null;
13529 r.curApp = null;
13530 app.curReceiver = null;
13531 }
13532 }
13533
13534 }
13535
Jeff Brown4d94a762010-09-23 11:33:28 -070013536 static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013537 Intent intent, int resultCode, String data, Bundle extras,
13538 boolean ordered, boolean sticky) throws RemoteException {
Jeff Brown4d94a762010-09-23 11:33:28 -070013539 // Send the intent to the receiver asynchronously using one-way binder calls.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013540 if (app != null && app.thread != null) {
13541 // If we have an app thread, do the call through that so it is
13542 // correctly ordered with other one-way calls.
13543 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013544 data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013545 } else {
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013546 receiver.performReceive(intent, resultCode, data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013547 }
13548 }
13549
Jeff Brown4d94a762010-09-23 11:33:28 -070013550 private final void deliverToRegisteredReceiverLocked(BroadcastRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013551 BroadcastFilter filter, boolean ordered) {
13552 boolean skip = false;
13553 if (filter.requiredPermission != null) {
13554 int perm = checkComponentPermission(filter.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080013555 r.callingPid, r.callingUid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013556 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013557 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013558 + r.intent.toString()
13559 + " from " + r.callerPackage + " (pid="
13560 + r.callingPid + ", uid=" + r.callingUid + ")"
13561 + " requires " + filter.requiredPermission
13562 + " due to registered receiver " + filter);
13563 skip = true;
13564 }
13565 }
13566 if (r.requiredPermission != null) {
13567 int perm = checkComponentPermission(r.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080013568 filter.receiverList.pid, filter.receiverList.uid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013569 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013570 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013571 + r.intent.toString()
13572 + " to " + filter.receiverList.app
13573 + " (pid=" + filter.receiverList.pid
13574 + ", uid=" + filter.receiverList.uid + ")"
13575 + " requires " + r.requiredPermission
13576 + " due to sender " + r.callerPackage
13577 + " (uid " + r.callingUid + ")");
13578 skip = true;
13579 }
13580 }
13581
13582 if (!skip) {
13583 // If this is not being sent as an ordered broadcast, then we
13584 // don't want to touch the fields that keep track of the current
13585 // state of ordered broadcasts.
13586 if (ordered) {
13587 r.receiver = filter.receiverList.receiver.asBinder();
13588 r.curFilter = filter;
13589 filter.receiverList.curBroadcast = r;
13590 r.state = BroadcastRecord.CALL_IN_RECEIVE;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013591 if (filter.receiverList.app != null) {
13592 // Bump hosting application to no longer be in background
13593 // scheduling class. Note that we can't do that if there
13594 // isn't an app... but we can only be in that case for
13595 // things that directly call the IActivityManager API, which
13596 // are already core system stuff so don't matter for this.
13597 r.curApp = filter.receiverList.app;
13598 filter.receiverList.app.curReceiver = r;
13599 updateOomAdjLocked();
13600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013601 }
13602 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013603 if (DEBUG_BROADCAST_LIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013604 int seq = r.intent.getIntExtra("seq", -1);
Dianne Hackborn399cccb2010-04-13 22:57:49 -070013605 Slog.i(TAG, "Delivering to " + filter
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013606 + " (seq=" + seq + "): " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013607 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013608 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013609 new Intent(r.intent), r.resultCode,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013610 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013611 if (ordered) {
13612 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
13613 }
13614 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013615 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013616 if (ordered) {
13617 r.receiver = null;
13618 r.curFilter = null;
13619 filter.receiverList.curBroadcast = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013620 if (filter.receiverList.app != null) {
13621 filter.receiverList.app.curReceiver = null;
13622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013623 }
13624 }
13625 }
13626 }
13627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013628 // =========================================================
13629 // INSTRUMENTATION
13630 // =========================================================
13631
13632 public boolean startInstrumentation(ComponentName className,
13633 String profileFile, int flags, Bundle arguments,
13634 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013635 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013636 // Refuse possible leaked file descriptors
13637 if (arguments != null && arguments.hasFileDescriptors()) {
13638 throw new IllegalArgumentException("File descriptors passed in Bundle");
13639 }
13640
13641 synchronized(this) {
13642 InstrumentationInfo ii = null;
13643 ApplicationInfo ai = null;
13644 try {
13645 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013646 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013647 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013648 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013649 } catch (PackageManager.NameNotFoundException e) {
13650 }
13651 if (ii == null) {
13652 reportStartInstrumentationFailure(watcher, className,
13653 "Unable to find instrumentation info for: " + className);
13654 return false;
13655 }
13656 if (ai == null) {
13657 reportStartInstrumentationFailure(watcher, className,
13658 "Unable to find instrumentation target package: " + ii.targetPackage);
13659 return false;
13660 }
13661
13662 int match = mContext.getPackageManager().checkSignatures(
13663 ii.targetPackage, ii.packageName);
13664 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13665 String msg = "Permission Denial: starting instrumentation "
13666 + className + " from pid="
13667 + Binder.getCallingPid()
13668 + ", uid=" + Binder.getCallingPid()
13669 + " not allowed because package " + ii.packageName
13670 + " does not have a signature matching the target "
13671 + ii.targetPackage;
13672 reportStartInstrumentationFailure(watcher, className, msg);
13673 throw new SecurityException(msg);
13674 }
13675
13676 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013677 // Instrumentation can kill and relaunch even persistent processes
13678 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013679 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013680 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013681 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013682 app.instrumentationProfileFile = profileFile;
13683 app.instrumentationArguments = arguments;
13684 app.instrumentationWatcher = watcher;
13685 app.instrumentationResultClass = className;
13686 Binder.restoreCallingIdentity(origId);
13687 }
13688
13689 return true;
13690 }
13691
13692 /**
13693 * Report errors that occur while attempting to start Instrumentation. Always writes the
13694 * error to the logs, but if somebody is watching, send the report there too. This enables
13695 * the "am" command to report errors with more information.
13696 *
13697 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13698 * @param cn The component name of the instrumentation.
13699 * @param report The error report.
13700 */
13701 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13702 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013703 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013704 try {
13705 if (watcher != null) {
13706 Bundle results = new Bundle();
13707 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13708 results.putString("Error", report);
13709 watcher.instrumentationStatus(cn, -1, results);
13710 }
13711 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013712 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013713 }
13714 }
13715
13716 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13717 if (app.instrumentationWatcher != null) {
13718 try {
13719 // NOTE: IInstrumentationWatcher *must* be oneway here
13720 app.instrumentationWatcher.instrumentationFinished(
13721 app.instrumentationClass,
13722 resultCode,
13723 results);
13724 } catch (RemoteException e) {
13725 }
13726 }
13727 app.instrumentationWatcher = null;
13728 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013729 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013730 app.instrumentationProfileFile = null;
13731 app.instrumentationArguments = null;
13732
Christopher Tate3dacd842011-08-19 14:56:15 -070013733 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013734 }
13735
13736 public void finishInstrumentation(IApplicationThread target,
13737 int resultCode, Bundle results) {
13738 // Refuse possible leaked file descriptors
13739 if (results != null && results.hasFileDescriptors()) {
13740 throw new IllegalArgumentException("File descriptors passed in Intent");
13741 }
13742
13743 synchronized(this) {
13744 ProcessRecord app = getRecordForAppLocked(target);
13745 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013746 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013747 return;
13748 }
13749 final long origId = Binder.clearCallingIdentity();
13750 finishInstrumentationLocked(app, resultCode, results);
13751 Binder.restoreCallingIdentity(origId);
13752 }
13753 }
13754
13755 // =========================================================
13756 // CONFIGURATION
13757 // =========================================================
13758
13759 public ConfigurationInfo getDeviceConfigurationInfo() {
13760 ConfigurationInfo config = new ConfigurationInfo();
13761 synchronized (this) {
13762 config.reqTouchScreen = mConfiguration.touchscreen;
13763 config.reqKeyboardType = mConfiguration.keyboard;
13764 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013765 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13766 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013767 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13768 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013769 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13770 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013771 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13772 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013773 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013774 }
13775 return config;
13776 }
13777
13778 public Configuration getConfiguration() {
13779 Configuration ci;
13780 synchronized(this) {
13781 ci = new Configuration(mConfiguration);
13782 }
13783 return ci;
13784 }
13785
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013786 public void updatePersistentConfiguration(Configuration values) {
13787 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13788 "updateConfiguration()");
13789 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13790 "updateConfiguration()");
13791 if (values == null) {
13792 throw new NullPointerException("Configuration must not be null");
13793 }
13794
13795 synchronized(this) {
13796 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013797 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013798 Binder.restoreCallingIdentity(origId);
13799 }
13800 }
13801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013802 public void updateConfiguration(Configuration values) {
13803 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13804 "updateConfiguration()");
13805
13806 synchronized(this) {
13807 if (values == null && mWindowManager != null) {
13808 // sentinel: fetch the current configuration from the window manager
13809 values = mWindowManager.computeNewConfiguration();
13810 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013811
13812 if (mWindowManager != null) {
13813 mProcessList.applyDisplaySize(mWindowManager);
13814 }
13815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013816 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013817 if (values != null) {
13818 Settings.System.clearConfiguration(values);
13819 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013820 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013821 Binder.restoreCallingIdentity(origId);
13822 }
13823 }
13824
13825 /**
13826 * Do either or both things: (1) change the current configuration, and (2)
13827 * make sure the given activity is running with the (now) current
13828 * configuration. Returns true if the activity has been left running, or
13829 * false if <var>starting</var> is being destroyed to match the new
13830 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013831 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013832 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013833 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013834 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013835 // do nothing if we are headless
13836 if (mHeadless) return true;
13837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013838 int changes = 0;
13839
13840 boolean kept = true;
13841
13842 if (values != null) {
13843 Configuration newConfig = new Configuration(mConfiguration);
13844 changes = newConfig.updateFrom(values);
13845 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013846 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013847 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013848 }
13849
Doug Zongker2bec3d42009-12-04 12:52:44 -080013850 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013851
Dianne Hackborn813075a62011-11-14 17:45:19 -080013852 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013853 saveLocaleLocked(values.locale,
13854 !values.locale.equals(mConfiguration.locale),
13855 values.userSetLocale);
13856 }
13857
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013858 mConfigurationSeq++;
13859 if (mConfigurationSeq <= 0) {
13860 mConfigurationSeq = 1;
13861 }
13862 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013863 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013864 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013865
13866 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013867
13868 // TODO: If our config changes, should we auto dismiss any currently
13869 // showing dialogs?
13870 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013871
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013872 AttributeCache ac = AttributeCache.instance();
13873 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013874 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013876
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013877 // Make sure all resources in our process are updated
13878 // right now, so that anyone who is going to retrieve
13879 // resource values after we return will be sure to get
13880 // the new ones. This is especially important during
13881 // boot, where the first config change needs to guarantee
13882 // all resources have that config before following boot
13883 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013884 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013885
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013886 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013887 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013888 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013889 mHandler.sendMessage(msg);
13890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013891
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013892 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13893 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013894 try {
13895 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013896 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013897 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013898 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013899 }
13900 } catch (Exception e) {
13901 }
13902 }
13903 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013904 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13905 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013906 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013907 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013908 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13909 broadcastIntentLocked(null, null,
13910 new Intent(Intent.ACTION_LOCALE_CHANGED),
13911 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013912 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013914 }
13915 }
13916
13917 if (changes != 0 && starting == null) {
13918 // If the configuration changed, and the caller is not already
13919 // in the process of starting an activity, then find the top
13920 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013921 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013922 }
13923
13924 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013925 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013926 // And we need to make sure at this point that all other activities
13927 // are made visible with the correct configuration.
13928 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013929 }
13930
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013931 if (values != null && mWindowManager != null) {
13932 mWindowManager.setNewConfiguration(mConfiguration);
13933 }
13934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013935 return kept;
13936 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013937
13938 /**
13939 * Decide based on the configuration whether we should shouw the ANR,
13940 * crash, etc dialogs. The idea is that if there is no affordnace to
13941 * press the on-screen buttons, we shouldn't show the dialog.
13942 *
13943 * A thought: SystemUI might also want to get told about this, the Power
13944 * dialog / global actions also might want different behaviors.
13945 */
13946 private static final boolean shouldShowDialogs(Configuration config) {
13947 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13948 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013950
13951 /**
13952 * Save the locale. You must be inside a synchronized (this) block.
13953 */
13954 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13955 if(isDiff) {
13956 SystemProperties.set("user.language", l.getLanguage());
13957 SystemProperties.set("user.region", l.getCountry());
13958 }
13959
13960 if(isPersist) {
13961 SystemProperties.set("persist.sys.language", l.getLanguage());
13962 SystemProperties.set("persist.sys.country", l.getCountry());
13963 SystemProperties.set("persist.sys.localevar", l.getVariant());
13964 }
13965 }
13966
13967 // =========================================================
13968 // LIFETIME MANAGEMENT
13969 // =========================================================
13970
Christopher Tatef46723b2012-01-26 14:19:24 -080013971 // Returns which broadcast queue the app is the current [or imminent] receiver
13972 // on, or 'null' if the app is not an active broadcast recipient.
13973 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13974 BroadcastRecord r = app.curReceiver;
13975 if (r != null) {
13976 return r.queue;
13977 }
13978
13979 // It's not the current receiver, but it might be starting up to become one
13980 synchronized (this) {
13981 for (BroadcastQueue queue : mBroadcastQueues) {
13982 r = queue.mPendingBroadcast;
13983 if (r != null && r.curApp == app) {
13984 // found it; report which queue it's in
13985 return queue;
13986 }
13987 }
13988 }
13989
13990 return null;
13991 }
13992
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013993 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013994 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013995 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013996 // This adjustment has already been computed. If we are calling
13997 // from the top, we may have already computed our adjustment with
13998 // an earlier hidden adjustment that isn't really for us... if
13999 // so, use the new hidden adjustment.
14000 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014001 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014002 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014003 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014004 }
14005
14006 if (app.thread == null) {
14007 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014008 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014009 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014010 }
14011
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014012 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
14013 app.adjSource = null;
14014 app.adjTarget = null;
14015 app.empty = false;
14016 app.hidden = false;
14017
14018 final int activitiesSize = app.activities.size();
14019
Dianne Hackborn7d608422011-08-07 16:24:18 -070014020 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014021 // The max adjustment doesn't allow this app to be anything
14022 // below foreground, so it is not worth doing work for it.
14023 app.adjType = "fixed";
14024 app.adjSeq = mAdjSeq;
14025 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014026 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014027 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014028 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014029 // System process can do UI, and when they do we want to have
14030 // them trim their memory after the user leaves the UI. To
14031 // facilitate this, here we need to determine whether or not it
14032 // is currently showing UI.
14033 app.systemNoUi = true;
14034 if (app == TOP_APP) {
14035 app.systemNoUi = false;
14036 } else if (activitiesSize > 0) {
14037 for (int j = 0; j < activitiesSize; j++) {
14038 final ActivityRecord r = app.activities.get(j);
14039 if (r.visible) {
14040 app.systemNoUi = false;
14041 break;
14042 }
14043 }
14044 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014045 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014046 }
14047
14048 final boolean hadForegroundActivities = app.foregroundActivities;
14049
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014050 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014051 app.keeping = false;
14052 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014053
The Android Open Source Project4df24232009-03-05 14:34:35 -080014054 // Determine the importance of the process, starting with most
14055 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014056 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014057 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080014058 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014059 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014060 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014061 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014062 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014063 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014064 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014065 } else if (app.instrumentationClass != null) {
14066 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014067 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014068 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014069 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080014070 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014071 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080014072 // counts as being in the foreground for OOM killer purposes.
14073 // It's placed in a sched group based on the nature of the
14074 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014075 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080014076 schedGroup = (queue == mFgBroadcastQueue)
14077 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014078 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014079 } else if (app.executingServices.size() > 0) {
14080 // An app that is currently executing a service callback also
14081 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014082 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014083 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014084 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014085 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014086 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014087 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014088 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014089 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014090 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014091 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014092 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014093 // A very not-needed process. If this is lower in the lru list,
14094 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014095 adj = hiddenAdj;
14096 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014097 app.hidden = true;
14098 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014099 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014100 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014101
14102 // Examine all activities if not already foreground.
14103 if (!app.foregroundActivities && activitiesSize > 0) {
14104 for (int j = 0; j < activitiesSize; j++) {
14105 final ActivityRecord r = app.activities.get(j);
14106 if (r.visible) {
14107 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014108 if (adj > ProcessList.VISIBLE_APP_ADJ) {
14109 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014110 app.adjType = "visible";
14111 }
14112 schedGroup = Process.THREAD_GROUP_DEFAULT;
14113 app.hidden = false;
14114 app.foregroundActivities = true;
14115 break;
14116 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
14117 || r.state == ActivityState.STOPPING) {
14118 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014119 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14120 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014121 app.adjType = "stopping";
14122 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080014123 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014124 app.foregroundActivities = true;
14125 }
14126 }
14127 }
14128
Dianne Hackborn7d608422011-08-07 16:24:18 -070014129 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014130 if (app.foregroundServices) {
14131 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014132 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014133 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014134 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014135 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014136 } else if (app.forcingToForeground != null) {
14137 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014138 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014139 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014140 app.adjType = "force-foreground";
14141 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014142 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014143 }
14144 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014145
Dianne Hackborn7d608422011-08-07 16:24:18 -070014146 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014147 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014148 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014149 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014150 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014151 app.adjType = "heavy";
14152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014153
Dianne Hackborn7d608422011-08-07 16:24:18 -070014154 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014155 // This process is hosting what we currently consider to be the
14156 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014157 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014158 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014159 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014160 app.adjType = "home";
14161 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014162
Dianne Hackbornf35fe232011-11-01 19:25:20 -070014163 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
14164 && app.activities.size() > 0) {
14165 // This was the previous process that showed UI to the user.
14166 // We want to try to keep it around more aggressively, to give
14167 // a good experience around switching between two apps.
14168 adj = ProcessList.PREVIOUS_APP_ADJ;
14169 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
14170 app.hidden = false;
14171 app.adjType = "previous";
14172 }
14173
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014174 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
14175 + " reason=" + app.adjType);
14176
The Android Open Source Project4df24232009-03-05 14:34:35 -080014177 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014178 // there are applications dependent on our services or providers, but
14179 // this gives us a baseline and makes sure we don't get into an
14180 // infinite recursion.
14181 app.adjSeq = mAdjSeq;
14182 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014183
Christopher Tate6fa95972009-06-05 18:43:55 -070014184 if (mBackupTarget != null && app == mBackupTarget.app) {
14185 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070014186 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014187 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014188 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014189 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014190 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070014191 }
14192 }
14193
Dianne Hackborn7d608422011-08-07 16:24:18 -070014194 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014195 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014196 final long now = SystemClock.uptimeMillis();
14197 // This process is more important if the top activity is
14198 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070014199 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014200 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014201 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014202 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014203 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014204 // If this process has shown some UI, let it immediately
14205 // go to the LRU list because it may be pretty heavy with
14206 // UI stuff. We'll tag it with a label just to help
14207 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014208 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014209 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014210 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014211 } else {
14212 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
14213 // This service has seen some activity within
14214 // recent memory, so we will keep its process ahead
14215 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014216 if (adj > ProcessList.SERVICE_ADJ) {
14217 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014218 app.adjType = "started-services";
14219 app.hidden = false;
14220 }
14221 }
14222 // If we have let the service slide into the background
14223 // state, still have some text describing what it is doing
14224 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014225 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014226 app.adjType = "started-bg-services";
14227 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014228 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014229 // Don't kill this process because it is doing work; it
14230 // has said it is doing work.
14231 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014232 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014233 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014234 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014235 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014236 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014237 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014238 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014239 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014240 // XXX should compute this based on the max of
14241 // all connected clients.
14242 ConnectionRecord cr = clist.get(i);
14243 if (cr.binding.client == app) {
14244 // Binding to ourself is not interesting.
14245 continue;
14246 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014247 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014248 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014249 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014250 int myHiddenAdj = hiddenAdj;
14251 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014252 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014253 myHiddenAdj = client.hiddenAdj;
14254 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014255 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014256 }
14257 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014258 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014259 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014260 String adjType = null;
14261 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
14262 // Not doing bind OOM management, so treat
14263 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014264 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014265 // If this process has shown some UI, let it immediately
14266 // go to the LRU list because it may be pretty heavy with
14267 // UI stuff. We'll tag it with a label just to help
14268 // debug and understand what is going on.
14269 if (adj > clientAdj) {
14270 adjType = "bound-bg-ui-services";
14271 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014272 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014273 clientAdj = adj;
14274 } else {
14275 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
14276 // This service has not seen activity within
14277 // recent memory, so allow it to drop to the
14278 // LRU list if there is no other reason to keep
14279 // it around. We'll also tag it with a label just
14280 // to help debug and undertand what is going on.
14281 if (adj > clientAdj) {
14282 adjType = "bound-bg-services";
14283 }
14284 clientAdj = adj;
14285 }
14286 }
14287 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014288 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014289 // If this process has recently shown UI, and
14290 // the process that is binding to it is less
14291 // important than being visible, then we don't
14292 // care about the binding as much as we care
14293 // about letting this process get into the LRU
14294 // list to be killed and restarted if needed for
14295 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014296 if (app.hasShownUi && app != mHomeProcess
14297 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014298 adjType = "bound-bg-ui-services";
14299 } else {
14300 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
14301 |Context.BIND_IMPORTANT)) != 0) {
14302 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014303 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
14304 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
14305 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14306 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14307 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014308 adj = clientAdj;
14309 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014310 app.pendingUiClean = true;
14311 if (adj > ProcessList.VISIBLE_APP_ADJ) {
14312 adj = ProcessList.VISIBLE_APP_ADJ;
14313 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014314 }
14315 if (!client.hidden) {
14316 app.hidden = false;
14317 }
14318 if (client.keeping) {
14319 app.keeping = true;
14320 }
14321 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014322 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014323 }
14324 if (adjType != null) {
14325 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014326 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14327 .REASON_SERVICE_IN_USE;
14328 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014329 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014330 app.adjTarget = s.name;
14331 }
14332 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14333 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14334 schedGroup = Process.THREAD_GROUP_DEFAULT;
14335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014336 }
14337 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014338 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
14339 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014340 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014341 (a.visible || a.state == ActivityState.RESUMED
14342 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014343 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014344 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14345 schedGroup = Process.THREAD_GROUP_DEFAULT;
14346 }
14347 app.hidden = false;
14348 app.adjType = "service";
14349 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14350 .REASON_SERVICE_IN_USE;
14351 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014352 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014353 app.adjTarget = s.name;
14354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014356 }
14357 }
14358 }
14359 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014360
Dianne Hackborn287952c2010-09-22 22:34:31 -070014361 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014362 // would like to avoid killing it unless it would prevent the current
14363 // application from running. By default we put the process in
14364 // with the rest of the background processes; as we scan through
14365 // its services we may bump it up from there.
14366 if (adj > hiddenAdj) {
14367 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014368 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014369 app.adjType = "bg-services";
14370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014371 }
14372
Dianne Hackborn7d608422011-08-07 16:24:18 -070014373 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014374 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014375 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014376 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014377 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014378 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014379 if (cpr.clients.size() != 0) {
14380 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014381 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014382 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070014383 if (client == app) {
14384 // Being our own client is not interesting.
14385 continue;
14386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014387 int myHiddenAdj = hiddenAdj;
14388 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014389 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014390 myHiddenAdj = client.hiddenAdj;
14391 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014392 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014393 }
14394 }
14395 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014396 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014397 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014398 if (app.hasShownUi && app != mHomeProcess
14399 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014400 app.adjType = "bg-ui-provider";
14401 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014402 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
14403 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014404 app.adjType = "provider";
14405 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014406 if (!client.hidden) {
14407 app.hidden = false;
14408 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014409 if (client.keeping) {
14410 app.keeping = true;
14411 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070014412 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14413 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014414 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014415 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014416 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014417 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014418 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14419 schedGroup = Process.THREAD_GROUP_DEFAULT;
14420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014421 }
14422 }
14423 // If the provider has external (non-framework) process
14424 // dependencies, ensure that its adjustment is at least
14425 // FOREGROUND_APP_ADJ.
14426 if (cpr.externals != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014427 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
14428 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014429 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014430 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014431 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014432 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014433 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014434 }
14435 }
14436 }
14437 }
14438
14439 app.curRawAdj = adj;
14440
Joe Onorato8a9b2202010-02-26 18:56:32 -080014441 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014442 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14443 if (adj > app.maxAdj) {
14444 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014445 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014446 schedGroup = Process.THREAD_GROUP_DEFAULT;
14447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014448 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014449 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014450 app.keeping = true;
14451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014452
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014453 if (app.hasAboveClient) {
14454 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14455 // then we need to drop its adjustment to be lower than the service's
14456 // in order to honor the request. We want to drop it by one adjustment
14457 // level... but there is special meaning applied to various levels so
14458 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014459 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014460 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014461 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14462 adj = ProcessList.VISIBLE_APP_ADJ;
14463 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14464 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14465 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14466 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014467 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014468 adj++;
14469 }
14470 }
14471
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014472 if (adj == ProcessList.SERVICE_ADJ) {
14473 if (doingAll) {
14474 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
14475 mNewNumServiceProcs++;
14476 }
14477 if (app.serviceb) {
14478 adj = ProcessList.SERVICE_B_ADJ;
14479 }
14480 } else {
14481 app.serviceb = false;
14482 }
14483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014484 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014485 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014486
14487 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014488 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14489 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014490 }
14491
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014492 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014493 }
14494
14495 /**
14496 * Ask a given process to GC right now.
14497 */
14498 final void performAppGcLocked(ProcessRecord app) {
14499 try {
14500 app.lastRequestedGc = SystemClock.uptimeMillis();
14501 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014502 if (app.reportLowMemory) {
14503 app.reportLowMemory = false;
14504 app.thread.scheduleLowMemory();
14505 } else {
14506 app.thread.processInBackground();
14507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014508 }
14509 } catch (Exception e) {
14510 // whatever.
14511 }
14512 }
14513
14514 /**
14515 * Returns true if things are idle enough to perform GCs.
14516 */
Josh Bartel7f208742010-02-25 11:01:44 -060014517 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014518 boolean processingBroadcasts = false;
14519 for (BroadcastQueue q : mBroadcastQueues) {
14520 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14521 processingBroadcasts = true;
14522 }
14523 }
14524 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014525 && (mSleeping || (mMainStack.mResumedActivity != null &&
14526 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014527 }
14528
14529 /**
14530 * Perform GCs on all processes that are waiting for it, but only
14531 * if things are idle.
14532 */
14533 final void performAppGcsLocked() {
14534 final int N = mProcessesToGc.size();
14535 if (N <= 0) {
14536 return;
14537 }
Josh Bartel7f208742010-02-25 11:01:44 -060014538 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014539 while (mProcessesToGc.size() > 0) {
14540 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014541 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014542 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14543 <= SystemClock.uptimeMillis()) {
14544 // To avoid spamming the system, we will GC processes one
14545 // at a time, waiting a few seconds between each.
14546 performAppGcLocked(proc);
14547 scheduleAppGcsLocked();
14548 return;
14549 } else {
14550 // It hasn't been long enough since we last GCed this
14551 // process... put it in the list to wait for its time.
14552 addProcessToGcListLocked(proc);
14553 break;
14554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014555 }
14556 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014557
14558 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014559 }
14560 }
14561
14562 /**
14563 * If all looks good, perform GCs on all processes waiting for them.
14564 */
14565 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014566 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014567 performAppGcsLocked();
14568 return;
14569 }
14570 // Still not idle, wait some more.
14571 scheduleAppGcsLocked();
14572 }
14573
14574 /**
14575 * Schedule the execution of all pending app GCs.
14576 */
14577 final void scheduleAppGcsLocked() {
14578 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014579
14580 if (mProcessesToGc.size() > 0) {
14581 // Schedule a GC for the time to the next process.
14582 ProcessRecord proc = mProcessesToGc.get(0);
14583 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14584
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014585 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014586 long now = SystemClock.uptimeMillis();
14587 if (when < (now+GC_TIMEOUT)) {
14588 when = now + GC_TIMEOUT;
14589 }
14590 mHandler.sendMessageAtTime(msg, when);
14591 }
14592 }
14593
14594 /**
14595 * Add a process to the array of processes waiting to be GCed. Keeps the
14596 * list in sorted order by the last GC time. The process can't already be
14597 * on the list.
14598 */
14599 final void addProcessToGcListLocked(ProcessRecord proc) {
14600 boolean added = false;
14601 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14602 if (mProcessesToGc.get(i).lastRequestedGc <
14603 proc.lastRequestedGc) {
14604 added = true;
14605 mProcessesToGc.add(i+1, proc);
14606 break;
14607 }
14608 }
14609 if (!added) {
14610 mProcessesToGc.add(0, proc);
14611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014612 }
14613
14614 /**
14615 * Set up to ask a process to GC itself. This will either do it
14616 * immediately, or put it on the list of processes to gc the next
14617 * time things are idle.
14618 */
14619 final void scheduleAppGcLocked(ProcessRecord app) {
14620 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014621 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014622 return;
14623 }
14624 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014625 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014626 scheduleAppGcsLocked();
14627 }
14628 }
14629
Dianne Hackborn287952c2010-09-22 22:34:31 -070014630 final void checkExcessivePowerUsageLocked(boolean doKills) {
14631 updateCpuStatsNow();
14632
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014633 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014634 boolean doWakeKills = doKills;
14635 boolean doCpuKills = doKills;
14636 if (mLastPowerCheckRealtime == 0) {
14637 doWakeKills = false;
14638 }
14639 if (mLastPowerCheckUptime == 0) {
14640 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014641 }
14642 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014643 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014644 }
14645 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014646 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14647 final long curUptime = SystemClock.uptimeMillis();
14648 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14649 mLastPowerCheckRealtime = curRealtime;
14650 mLastPowerCheckUptime = curUptime;
14651 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14652 doWakeKills = false;
14653 }
14654 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14655 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014656 }
14657 int i = mLruProcesses.size();
14658 while (i > 0) {
14659 i--;
14660 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014661 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014662 long wtime;
14663 synchronized (stats) {
14664 wtime = stats.getProcessWakeTime(app.info.uid,
14665 app.pid, curRealtime);
14666 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014667 long wtimeUsed = wtime - app.lastWakeTime;
14668 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14669 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014670 StringBuilder sb = new StringBuilder(128);
14671 sb.append("Wake for ");
14672 app.toShortString(sb);
14673 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014674 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014675 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014676 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014677 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014678 sb.append((wtimeUsed*100)/realtimeSince);
14679 sb.append("%)");
14680 Slog.i(TAG, sb.toString());
14681 sb.setLength(0);
14682 sb.append("CPU for ");
14683 app.toShortString(sb);
14684 sb.append(": over ");
14685 TimeUtils.formatDuration(uptimeSince, sb);
14686 sb.append(" used ");
14687 TimeUtils.formatDuration(cputimeUsed, sb);
14688 sb.append(" (");
14689 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014690 sb.append("%)");
14691 Slog.i(TAG, sb.toString());
14692 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014693 // If a process has held a wake lock for more
14694 // than 50% of the time during this period,
14695 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014696 if (doWakeKills && realtimeSince > 0
14697 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14698 synchronized (stats) {
14699 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14700 realtimeSince, wtimeUsed);
14701 }
14702 Slog.w(TAG, "Excessive wake lock in " + app.processName
14703 + " (pid " + app.pid + "): held " + wtimeUsed
14704 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014705 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14706 app.processName, app.setAdj, "excessive wake lock");
14707 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014708 } else if (doCpuKills && uptimeSince > 0
14709 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14710 synchronized (stats) {
14711 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14712 uptimeSince, cputimeUsed);
14713 }
14714 Slog.w(TAG, "Excessive CPU in " + app.processName
14715 + " (pid " + app.pid + "): used " + cputimeUsed
14716 + " during " + uptimeSince);
14717 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14718 app.processName, app.setAdj, "excessive cpu");
14719 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014720 } else {
14721 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014722 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014723 }
14724 }
14725 }
14726 }
14727
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014728 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014729 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014730 app.hiddenAdj = hiddenAdj;
14731
14732 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014733 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014734 }
14735
Dianne Hackborn287952c2010-09-22 22:34:31 -070014736 final boolean wasKeeping = app.keeping;
14737
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014738 boolean success = true;
14739
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014740 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014741
Jeff Brown10e89712011-07-08 18:52:57 -070014742 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070014743 if (false) {
14744 // Removing for now. Forcing GCs is not so useful anymore
14745 // with Dalvik, and the new memory level hint facility is
14746 // better for what we need to do these days.
14747 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14748 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14749 // If this app is transitioning from foreground to
14750 // non-foreground, have it do a gc.
14751 scheduleAppGcLocked(app);
14752 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14753 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14754 // Likewise do a gc when an app is moving in to the
14755 // background (such as a service stopping).
14756 scheduleAppGcLocked(app);
14757 }
Jeff Brown10e89712011-07-08 18:52:57 -070014758 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014759
Jeff Brown10e89712011-07-08 18:52:57 -070014760 if (wasKeeping && !app.keeping) {
14761 // This app is no longer something we want to keep. Note
14762 // its current wake lock time to later know to kill it if
14763 // it is not behaving well.
14764 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14765 synchronized (stats) {
14766 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14767 app.pid, SystemClock.elapsedRealtime());
14768 }
14769 app.lastCpuTime = app.curCpuTime;
14770 }
14771
14772 app.setRawAdj = app.curRawAdj;
14773 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014774
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014775 if (app.curAdj != app.setAdj) {
14776 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014777 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014778 TAG, "Set " + app.pid + " " + app.processName +
14779 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014780 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014781 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014782 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014783 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014784 }
14785 }
14786 if (app.setSchedGroup != app.curSchedGroup) {
14787 app.setSchedGroup = app.curSchedGroup;
14788 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14789 "Setting process group of " + app.processName
14790 + " to " + app.curSchedGroup);
14791 if (app.waitingToKill != null &&
14792 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14793 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14794 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14795 app.processName, app.setAdj, app.waitingToKill);
14796 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014797 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014798 } else {
14799 if (true) {
14800 long oldId = Binder.clearCallingIdentity();
14801 try {
14802 Process.setProcessGroup(app.pid, app.curSchedGroup);
14803 } catch (Exception e) {
14804 Slog.w(TAG, "Failed setting process group of " + app.pid
14805 + " to " + app.curSchedGroup);
14806 e.printStackTrace();
14807 } finally {
14808 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014809 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014810 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014811 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014812 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014813 app.thread.setSchedulingGroup(app.curSchedGroup);
14814 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014815 }
14816 }
14817 }
14818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014819 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014820 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014821 }
14822
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014823 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014824 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014825 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborncbb722e2012-02-07 18:33:49 -080014826 for (int i=mMainStack.mPausingActivities.size()-1; i>=0; i--) {
14827 ActivityRecord r = mMainStack.mPausingActivities.get(i);
14828 if (r.app != null) {
14829 resumedActivity = r;
14830 break;
14831 }
14832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014833 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014834 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014835 }
14836 }
14837 return resumedActivity;
14838 }
14839
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014840 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014841 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014842 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14843 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014844 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14845 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014846
14847 mAdjSeq++;
14848
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014849 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014850 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14851 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014852 if (nowHidden != wasHidden) {
14853 // Changed to/from hidden state, so apps after it in the LRU
14854 // list may also be changed.
14855 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014856 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014857 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014858 }
14859
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014860 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014861 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014862 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14863
14864 if (false) {
14865 RuntimeException e = new RuntimeException();
14866 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014867 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014868 }
14869
14870 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014871 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014872
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014873 // Let's determine how many processes we have running vs.
14874 // how many slots we have for background processes; we may want
14875 // to put multiple processes in a slot of there are enough of
14876 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014877 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014878 int factor = (mLruProcesses.size()-4)/numSlots;
14879 if (factor < 1) factor = 1;
14880 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014881 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014882
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014883 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014884 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014885 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014886 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014887 while (i > 0) {
14888 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014889 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014890 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014891 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14892 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014893 && app.curAdj == curHiddenAdj) {
14894 step++;
14895 if (step >= factor) {
14896 step = 0;
14897 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014898 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014899 }
14900 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014901 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014902 numHidden++;
14903 if (numHidden > mProcessLimit) {
14904 Slog.i(TAG, "No longer want " + app.processName
14905 + " (pid " + app.pid + "): hidden #" + numHidden);
14906 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14907 app.processName, app.setAdj, "too many background");
14908 app.killedBackground = true;
14909 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014910 }
14911 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014912 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14913 // If this is an isolated process, and there are no
14914 // services running in it, then the process is no longer
14915 // needed. We agressively kill these because we can by
14916 // definition not re-use the same process again, and it is
14917 // good to avoid having whatever code was running in them
14918 // left sitting around after no longer needed.
14919 Slog.i(TAG, "Isolated process " + app.processName
14920 + " (pid " + app.pid + ") no longer needed");
14921 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14922 app.processName, app.setAdj, "isolated not needed");
14923 app.killedBackground = true;
14924 Process.killProcessQuiet(app.pid);
14925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014926 }
14927 }
14928
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014929 mNumServiceProcs = mNewNumServiceProcs;
14930
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014931 // Now determine the memory trimming level of background processes.
14932 // Unfortunately we need to start at the back of the list to do this
14933 // properly. We only do this if the number of background apps we
14934 // are managing to keep around is less than half the maximum we desire;
14935 // if we are keeping a good number around, we'll let them use whatever
14936 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014937 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014938 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014939 factor = numHidden/3;
14940 int minFactor = 2;
14941 if (mHomeProcess != null) minFactor++;
14942 if (mPreviousProcess != null) minFactor++;
14943 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014944 step = 0;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014945 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014946 for (i=0; i<N; i++) {
14947 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014948 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14949 && app.curAdj != ProcessList.SERVICE_B_ADJ
14950 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014951 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14952 try {
14953 app.thread.scheduleTrimMemory(curLevel);
14954 } catch (RemoteException e) {
14955 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014956 if (false) {
14957 // For now we won't do this; our memory trimming seems
14958 // to be good enough at this point that destroying
14959 // activities causes more harm than good.
14960 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14961 && app != mHomeProcess && app != mPreviousProcess) {
14962 // For these apps we will also finish their activities
14963 // to help them free memory.
14964 mMainStack.destroyActivitiesLocked(app, false, "trim");
14965 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014966 }
14967 }
14968 app.trimMemoryLevel = curLevel;
14969 step++;
14970 if (step >= factor) {
14971 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014972 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14973 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014974 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014975 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14976 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014977 break;
14978 }
14979 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014980 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014981 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014982 && app.thread != null) {
14983 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014984 app.thread.scheduleTrimMemory(
14985 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014986 } catch (RemoteException e) {
14987 }
14988 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014989 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014990 } else if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014991 && app.pendingUiClean) {
14992 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14993 && app.thread != null) {
14994 try {
14995 app.thread.scheduleTrimMemory(
14996 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14997 } catch (RemoteException e) {
14998 }
14999 }
15000 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
15001 app.pendingUiClean = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015002 } else {
15003 app.trimMemoryLevel = 0;
15004 }
15005 }
15006 } else {
15007 final int N = mLruProcesses.size();
15008 for (i=0; i<N; i++) {
15009 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070015010 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015011 && app.pendingUiClean) {
15012 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
15013 && app.thread != null) {
15014 try {
15015 app.thread.scheduleTrimMemory(
15016 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
15017 } catch (RemoteException e) {
15018 }
15019 }
15020 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
15021 app.pendingUiClean = false;
15022 } else {
15023 app.trimMemoryLevel = 0;
15024 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015025 }
15026 }
15027
15028 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070015029 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015031 }
15032
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070015033 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015034 synchronized (this) {
15035 int i;
15036
15037 // First remove any unused application processes whose package
15038 // has been removed.
15039 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
15040 final ProcessRecord app = mRemovedProcesses.get(i);
15041 if (app.activities.size() == 0
15042 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080015043 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015044 TAG, "Exiting empty application process "
15045 + app.processName + " ("
15046 + (app.thread != null ? app.thread.asBinder() : null)
15047 + ")\n");
15048 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070015049 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
15050 app.processName, app.setAdj, "empty");
15051 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015052 } else {
15053 try {
15054 app.thread.scheduleExit();
15055 } catch (Exception e) {
15056 // Ignore exceptions.
15057 }
15058 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070015059 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015060 mRemovedProcesses.remove(i);
15061
15062 if (app.persistent) {
15063 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080015064 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015065 }
15066 }
15067 }
15068 }
15069
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015070 // Now update the oom adj for all processes.
15071 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015072 }
15073 }
15074
15075 /** This method sends the specified signal to each of the persistent apps */
15076 public void signalPersistentProcesses(int sig) throws RemoteException {
15077 if (sig != Process.SIGNAL_USR1) {
15078 throw new SecurityException("Only SIGNAL_USR1 is allowed");
15079 }
15080
15081 synchronized (this) {
15082 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
15083 != PackageManager.PERMISSION_GRANTED) {
15084 throw new SecurityException("Requires permission "
15085 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
15086 }
15087
Dianne Hackborndd71fc82009-12-16 19:24:32 -080015088 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
15089 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015090 if (r.thread != null && r.persistent) {
15091 Process.sendSignal(r.pid, sig);
15092 }
15093 }
15094 }
15095 }
15096
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015097 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
15098 if (proc == null || proc == mProfileProc) {
15099 proc = mProfileProc;
15100 path = mProfileFile;
15101 profileType = mProfileType;
15102 clearProfilerLocked();
15103 }
15104 if (proc == null) {
15105 return;
15106 }
15107 try {
15108 proc.thread.profilerControl(false, path, null, profileType);
15109 } catch (RemoteException e) {
15110 throw new IllegalStateException("Process disappeared");
15111 }
15112 }
15113
15114 private void clearProfilerLocked() {
15115 if (mProfileFd != null) {
15116 try {
15117 mProfileFd.close();
15118 } catch (IOException e) {
15119 }
15120 }
15121 mProfileApp = null;
15122 mProfileProc = null;
15123 mProfileFile = null;
15124 mProfileType = 0;
15125 mAutoStopProfiler = false;
15126 }
15127
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015128 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070015129 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015130
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015131 try {
15132 synchronized (this) {
15133 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
15134 // its own permission.
15135 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15136 != PackageManager.PERMISSION_GRANTED) {
15137 throw new SecurityException("Requires permission "
15138 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015139 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015140
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015141 if (start && fd == null) {
15142 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015143 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015144
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015145 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015146 if (process != null) {
15147 try {
15148 int pid = Integer.parseInt(process);
15149 synchronized (mPidsSelfLocked) {
15150 proc = mPidsSelfLocked.get(pid);
15151 }
15152 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015153 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015154
15155 if (proc == null) {
15156 HashMap<String, SparseArray<ProcessRecord>> all
15157 = mProcessNames.getMap();
15158 SparseArray<ProcessRecord> procs = all.get(process);
15159 if (procs != null && procs.size() > 0) {
15160 proc = procs.valueAt(0);
15161 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015162 }
15163 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015164
15165 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015166 throw new IllegalArgumentException("Unknown process: " + process);
15167 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015168
15169 if (start) {
15170 stopProfilerLocked(null, null, 0);
15171 setProfileApp(proc.info, proc.processName, path, fd, false);
15172 mProfileProc = proc;
15173 mProfileType = profileType;
15174 try {
15175 fd = fd.dup();
15176 } catch (IOException e) {
15177 fd = null;
15178 }
15179 proc.thread.profilerControl(start, path, fd, profileType);
15180 fd = null;
15181 mProfileFd = null;
15182 } else {
15183 stopProfilerLocked(proc, path, profileType);
15184 if (fd != null) {
15185 try {
15186 fd.close();
15187 } catch (IOException e) {
15188 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015189 }
15190 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015191
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015192 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015193 }
15194 } catch (RemoteException e) {
15195 throw new IllegalStateException("Process disappeared");
15196 } finally {
15197 if (fd != null) {
15198 try {
15199 fd.close();
15200 } catch (IOException e) {
15201 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015202 }
15203 }
15204 }
Andy McFadden824c5102010-07-09 16:26:57 -070015205
15206 public boolean dumpHeap(String process, boolean managed,
15207 String path, ParcelFileDescriptor fd) throws RemoteException {
15208
15209 try {
15210 synchronized (this) {
15211 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
15212 // its own permission (same as profileControl).
15213 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15214 != PackageManager.PERMISSION_GRANTED) {
15215 throw new SecurityException("Requires permission "
15216 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
15217 }
15218
15219 if (fd == null) {
15220 throw new IllegalArgumentException("null fd");
15221 }
15222
15223 ProcessRecord proc = null;
15224 try {
15225 int pid = Integer.parseInt(process);
15226 synchronized (mPidsSelfLocked) {
15227 proc = mPidsSelfLocked.get(pid);
15228 }
15229 } catch (NumberFormatException e) {
15230 }
15231
15232 if (proc == null) {
15233 HashMap<String, SparseArray<ProcessRecord>> all
15234 = mProcessNames.getMap();
15235 SparseArray<ProcessRecord> procs = all.get(process);
15236 if (procs != null && procs.size() > 0) {
15237 proc = procs.valueAt(0);
15238 }
15239 }
15240
15241 if (proc == null || proc.thread == null) {
15242 throw new IllegalArgumentException("Unknown process: " + process);
15243 }
15244
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080015245 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
15246 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070015247 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
15248 throw new SecurityException("Process not debuggable: " + proc);
15249 }
15250 }
15251
15252 proc.thread.dumpHeap(managed, path, fd);
15253 fd = null;
15254 return true;
15255 }
15256 } catch (RemoteException e) {
15257 throw new IllegalStateException("Process disappeared");
15258 } finally {
15259 if (fd != null) {
15260 try {
15261 fd.close();
15262 } catch (IOException e) {
15263 }
15264 }
15265 }
15266 }
15267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015268 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
15269 public void monitor() {
15270 synchronized (this) { }
15271 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015272
Dianne Hackborna573f6a2012-02-09 16:12:18 -080015273 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015274 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
15275 ProcessRecord processRecord = mLruProcesses.get(i);
15276 try {
15277 if (processRecord.thread != null) {
15278 processRecord.thread.setCoreSettings(settings);
15279 }
15280 } catch (RemoteException re) {
15281 /* ignore */
15282 }
15283 }
15284 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015285
15286 // Multi-user methods
15287
Amith Yamasani742a6712011-05-04 14:49:28 -070015288 private int mCurrentUserId;
15289 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
15290
15291 public boolean switchUser(int userId) {
15292 final int callingUid = Binder.getCallingUid();
15293 if (callingUid != 0 && callingUid != Process.myUid()) {
15294 Slog.e(TAG, "Trying to switch user from unauthorized app");
15295 return false;
15296 }
15297 if (mCurrentUserId == userId)
15298 return true;
15299
15300 synchronized (this) {
15301 // Check if user is already logged in, otherwise check if user exists first before
15302 // adding to the list of logged in users.
15303 if (mLoggedInUsers.indexOfKey(userId) < 0) {
15304 if (!userExists(userId)) {
15305 return false;
15306 }
15307 mLoggedInUsers.append(userId, userId);
15308 }
15309
15310 mCurrentUserId = userId;
15311 boolean haveActivities = mMainStack.switchUser(userId);
15312 if (!haveActivities) {
15313 startHomeActivityLocked(userId);
15314 }
15315 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015316 return true;
15317 }
Amith Yamasani742a6712011-05-04 14:49:28 -070015318
15319 private boolean userExists(int userId) {
15320 try {
15321 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
15322 for (UserInfo user : users) {
15323 if (user.id == userId) {
15324 return true;
15325 }
15326 }
15327 } catch (RemoteException re) {
15328 // Won't happen, in same process
15329 }
15330
15331 return false;
15332 }
15333
15334
15335 private int applyUserId(int uid, int userId) {
15336 return UserId.getUid(userId, uid);
15337 }
15338
15339 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080015340 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070015341 ApplicationInfo newInfo = new ApplicationInfo(info);
15342 newInfo.uid = applyUserId(info.uid, userId);
15343 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
15344 newInfo.dataDir = USER_DATA_DIR + userId + "/"
15345 + info.packageName;
15346 }
15347 return newInfo;
15348 }
15349
15350 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080015351 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070015352 || userId < 1) {
15353 return aInfo;
15354 }
15355
15356 ActivityInfo info = new ActivityInfo(aInfo);
15357 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
15358 return info;
15359 }
15360
15361 static class ServiceMap {
15362
15363 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
15364 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
15365 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
15366 mServicesByIntentPerUser = new SparseArray<
15367 HashMap<Intent.FilterComparison, ServiceRecord>>();
15368
15369 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
15370 // TODO: Deal with global services
15371 if (DEBUG_MU)
15372 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
15373 return getServices(callingUser).get(name);
15374 }
15375
15376 ServiceRecord getServiceByName(ComponentName name) {
15377 return getServiceByName(name, -1);
15378 }
15379
15380 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15381 // TODO: Deal with global services
15382 if (DEBUG_MU)
15383 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
15384 return getServicesByIntent(callingUser).get(filter);
15385 }
15386
15387 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
15388 return getServiceByIntent(filter, -1);
15389 }
15390
15391 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
15392 // TODO: Deal with global services
15393 getServices(callingUser).put(name, value);
15394 }
15395
15396 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
15397 ServiceRecord value) {
15398 // TODO: Deal with global services
15399 getServicesByIntent(callingUser).put(filter, value);
15400 }
15401
15402 void removeServiceByName(ComponentName name, int callingUser) {
15403 // TODO: Deal with global services
15404 ServiceRecord removed = getServices(callingUser).remove(name);
15405 if (DEBUG_MU)
15406 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15407 + " removed=" + removed);
15408 }
15409
15410 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15411 // TODO: Deal with global services
15412 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15413 if (DEBUG_MU)
15414 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15415 + " removed=" + removed);
15416 }
15417
15418 Collection<ServiceRecord> getAllServices(int callingUser) {
15419 // TODO: Deal with global services
15420 return getServices(callingUser).values();
15421 }
15422
15423 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15424 HashMap map = mServicesByNamePerUser.get(callingUser);
15425 if (map == null) {
15426 map = new HashMap<ComponentName, ServiceRecord>();
15427 mServicesByNamePerUser.put(callingUser, map);
15428 }
15429 return map;
15430 }
15431
15432 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15433 int callingUser) {
15434 HashMap map = mServicesByIntentPerUser.get(callingUser);
15435 if (map == null) {
15436 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15437 mServicesByIntentPerUser.put(callingUser, map);
15438 }
15439 return map;
15440 }
15441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015442}