blob: e38d96ed83434b2f1a301994325d4602d18ab561 [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;
271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700273 * Description of a request to start a new activity, which has been held
274 * due to app switches being disabled.
275 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700276 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700277 ActivityRecord r;
278 ActivityRecord sourceRecord;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700279 Uri[] grantedUriPermissions;
280 int grantedMode;
281 boolean onlyIfNeeded;
282 }
283
284 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
285 = new ArrayList<PendingActivityLaunch>();
286
287 /**
Christopher Tatef46723b2012-01-26 14:19:24 -0800288 * BROADCASTS
289 *
290 * We keep two broadcast queues and associated bookkeeping, one for those at
291 * foreground priority, and one for normal (background-priority) broadcasts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 */
Christopher Tatef46723b2012-01-26 14:19:24 -0800293 public class BroadcastQueue {
294 static final String TAG = "BroadcastQueue";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295
Christopher Tatef46723b2012-01-26 14:19:24 -0800296 static final int MAX_BROADCAST_HISTORY = 25;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297
Christopher Tatef46723b2012-01-26 14:19:24 -0800298 /**
299 * Recognizable moniker for this queue
300 */
301 String mQueueName;
Dianne Hackborn12527f92009-11-11 17:39:50 -0800302
Christopher Tatef46723b2012-01-26 14:19:24 -0800303 /**
304 * Timeout period for this queue's broadcasts
305 */
306 long mTimeoutPeriod;
307
308 /**
309 * Lists of all active broadcasts that are to be executed immediately
310 * (without waiting for another broadcast to finish). Currently this only
311 * contains broadcasts to registered receivers, to avoid spinning up
312 * a bunch of processes to execute IntentReceiver components. Background-
313 * and foreground-priority broadcasts are queued separately.
314 */
315 final ArrayList<BroadcastRecord> mParallelBroadcasts
316 = new ArrayList<BroadcastRecord>();
317 /**
318 * List of all active broadcasts that are to be executed one at a time.
319 * The object at the top of the list is the currently activity broadcasts;
320 * those after it are waiting for the top to finish. As with parallel
321 * broadcasts, separate background- and foreground-priority queues are
322 * maintained.
323 */
324 final ArrayList<BroadcastRecord> mOrderedBroadcasts
325 = new ArrayList<BroadcastRecord>();
326
327 /**
328 * Historical data of past broadcasts, for debugging.
329 */
330 final BroadcastRecord[] mBroadcastHistory
331 = new BroadcastRecord[MAX_BROADCAST_HISTORY];
332
333 /**
334 * Set when we current have a BROADCAST_INTENT_MSG in flight.
335 */
336 boolean mBroadcastsScheduled = false;
337
338 /**
339 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
340 */
341 boolean mPendingBroadcastTimeoutMessage;
342
343 /**
344 * Intent broadcasts that we have tried to start, but are
345 * waiting for the application's process to be created. We only
346 * need one per scheduling class (instead of a list) because we always
347 * process broadcasts one at a time, so no others can be started while
348 * waiting for this one.
349 */
350 BroadcastRecord mPendingBroadcast = null;
351
352 /**
353 * The receiver index that is pending, to restart the broadcast if needed.
354 */
355 int mPendingBroadcastRecvIndex;
356
357 BroadcastQueue(String name, long timeoutPeriod) {
358 mQueueName = name;
359 mTimeoutPeriod = timeoutPeriod;
360 }
361
362 public boolean isPendingBroadcastProcessLocked(int pid) {
363 return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
364 }
365
366 public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
367 mParallelBroadcasts.add(r);
368 }
369
370 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
371 mOrderedBroadcasts.add(r);
372 }
373
374 public final boolean replaceParallelBroadcastLocked(BroadcastRecord r) {
375 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
376 if (r.intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
377 if (DEBUG_BROADCAST) Slog.v(TAG,
378 "***** DROPPING PARALLEL ["
379 + mQueueName + "]: " + r.intent);
380 mParallelBroadcasts.set(i, r);
381 return true;
382 }
383 }
384 return false;
385 }
386
387 public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
388 for (int i=mOrderedBroadcasts.size()-1; i>0; i--) {
389 if (r.intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
390 if (DEBUG_BROADCAST) Slog.v(TAG,
391 "***** DROPPING ORDERED ["
392 + mQueueName + "]: " + r.intent);
393 mOrderedBroadcasts.set(i, r);
394 return true;
395 }
396 }
397 return false;
398 }
399
400 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
401 boolean didSomething = false;
402 final BroadcastRecord br = mPendingBroadcast;
403 if (br != null && br.curApp.pid == app.pid) {
404 try {
405 mPendingBroadcast = null;
406 processCurBroadcastLocked(br, app);
407 didSomething = true;
408 } catch (Exception e) {
409 Slog.w(TAG, "Exception in new application when starting receiver "
410 + br.curComponent.flattenToShortString(), e);
411 logBroadcastReceiverDiscardLocked(br);
412 finishReceiverLocked(br, br.resultCode, br.resultData,
413 br.resultExtras, br.resultAbort, true);
414 scheduleBroadcastsLocked();
415 // We need to reset the state if we fails to start the receiver.
416 br.state = BroadcastRecord.IDLE;
417 throw new RuntimeException(e.getMessage());
418 }
419 }
420 return didSomething;
421 }
422
423 public void skipPendingBroadcastLocked(int pid) {
424 final BroadcastRecord br = mPendingBroadcast;
425 if (br != null && br.curApp.pid == pid) {
426 br.state = BroadcastRecord.IDLE;
427 br.nextReceiver = mPendingBroadcastRecvIndex;
428 mPendingBroadcast = null;
429 scheduleBroadcastsLocked();
430 }
431 }
432
433 public void skipCurrentReceiverLocked(ProcessRecord app) {
434 boolean reschedule = false;
435 BroadcastRecord r = app.curReceiver;
436 if (r != null) {
437 // The current broadcast is waiting for this app's receiver
438 // to be finished. Looks like that's not going to happen, so
439 // let the broadcast continue.
440 logBroadcastReceiverDiscardLocked(r);
441 finishReceiverLocked(r, r.resultCode, r.resultData,
442 r.resultExtras, r.resultAbort, true);
443 reschedule = true;
444 }
445
446 r = mPendingBroadcast;
447 if (r != null && r.curApp == app) {
448 if (DEBUG_BROADCAST) Slog.v(TAG,
449 "[" + mQueueName + "] skip & discard pending app " + r);
450 logBroadcastReceiverDiscardLocked(r);
451 finishReceiverLocked(r, r.resultCode, r.resultData,
452 r.resultExtras, r.resultAbort, true);
453 reschedule = true;
454 }
455 if (reschedule) {
456 scheduleBroadcastsLocked();
457 }
458 }
459
460 public void scheduleBroadcastsLocked() {
461 if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts ["
462 + mQueueName + "]: current="
463 + mBroadcastsScheduled);
464
465 if (mBroadcastsScheduled) {
466 return;
467 }
468 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
469 mBroadcastsScheduled = true;
470 }
471
472 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
473 if (mOrderedBroadcasts.size() > 0) {
474 final BroadcastRecord r = mOrderedBroadcasts.get(0);
475 if (r != null && r.receiver == receiver) {
476 return r;
477 }
478 }
479 return null;
480 }
481
482 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
483 String resultData, Bundle resultExtras, boolean resultAbort,
484 boolean explicit) {
485 int state = r.state;
486 r.state = BroadcastRecord.IDLE;
487 if (state == BroadcastRecord.IDLE) {
488 if (explicit) {
489 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
490 }
491 }
492 r.receiver = null;
493 r.intent.setComponent(null);
494 if (r.curApp != null) {
495 r.curApp.curReceiver = null;
496 }
497 if (r.curFilter != null) {
498 r.curFilter.receiverList.curBroadcast = null;
499 }
500 r.curFilter = null;
501 r.curApp = null;
502 r.curComponent = null;
503 r.curReceiver = null;
504 mPendingBroadcast = null;
505
506 r.resultCode = resultCode;
507 r.resultData = resultData;
508 r.resultExtras = resultExtras;
509 r.resultAbort = resultAbort;
510
511 // We will process the next receiver right now if this is finishing
512 // an app receiver (which is always asynchronous) or after we have
513 // come back from calling a receiver.
514 return state == BroadcastRecord.APP_RECEIVE
515 || state == BroadcastRecord.CALL_DONE_RECEIVE;
516 }
517
518 private final void processNextBroadcast(boolean fromMsg) {
519 synchronized(ActivityManagerService.this) {
520 BroadcastRecord r;
521
522 if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast ["
523 + mQueueName + "]: "
524 + mParallelBroadcasts.size() + " broadcasts, "
525 + mOrderedBroadcasts.size() + " ordered broadcasts");
526
527 updateCpuStats();
528
529 if (fromMsg) {
530 mBroadcastsScheduled = false;
531 }
532
533 // First, deliver any non-serialized broadcasts right away.
534 while (mParallelBroadcasts.size() > 0) {
535 r = mParallelBroadcasts.remove(0);
536 r.dispatchTime = SystemClock.uptimeMillis();
537 r.dispatchClockTime = System.currentTimeMillis();
538 final int N = r.receivers.size();
539 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast ["
540 + mQueueName + "] " + r);
541 for (int i=0; i<N; i++) {
542 Object target = r.receivers.get(i);
543 if (DEBUG_BROADCAST) Slog.v(TAG,
544 "Delivering non-ordered on [" + mQueueName + "] to registered "
545 + target + ": " + r);
546 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
547 }
548 addBroadcastToHistoryLocked(r);
549 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast ["
550 + mQueueName + "] " + r);
551 }
552
553 // Now take care of the next serialized one...
554
555 // If we are waiting for a process to come up to handle the next
556 // broadcast, then do nothing at this point. Just in case, we
557 // check that the process we're waiting for still exists.
558 if (mPendingBroadcast != null) {
559 if (DEBUG_BROADCAST_LIGHT) {
560 Slog.v(TAG, "processNextBroadcast ["
561 + mQueueName + "]: waiting for "
562 + mPendingBroadcast.curApp);
563 }
564
565 boolean isDead;
566 synchronized (mPidsSelfLocked) {
567 isDead = (mPidsSelfLocked.get(mPendingBroadcast.curApp.pid) == null);
568 }
569 if (!isDead) {
570 // It's still alive, so keep waiting
571 return;
572 } else {
573 Slog.w(TAG, "pending app ["
574 + mQueueName + "]" + mPendingBroadcast.curApp
575 + " died before responding to broadcast");
576 mPendingBroadcast.state = BroadcastRecord.IDLE;
577 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
578 mPendingBroadcast = null;
579 }
580 }
581
582 boolean looped = false;
583
584 do {
585 if (mOrderedBroadcasts.size() == 0) {
586 // No more broadcasts pending, so all done!
587 scheduleAppGcsLocked();
588 if (looped) {
589 // If we had finished the last ordered broadcast, then
590 // make sure all processes have correct oom and sched
591 // adjustments.
592 updateOomAdjLocked();
593 }
594 return;
595 }
596 r = mOrderedBroadcasts.get(0);
597 boolean forceReceive = false;
598
599 // Ensure that even if something goes awry with the timeout
600 // detection, we catch "hung" broadcasts here, discard them,
601 // and continue to make progress.
602 //
603 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
604 // receivers don't get executed with timeouts. They're intended for
605 // one time heavy lifting after system upgrades and can take
606 // significant amounts of time.
607 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
608 if (mProcessesReady && r.dispatchTime > 0) {
609 long now = SystemClock.uptimeMillis();
610 if ((numReceivers > 0) &&
611 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
612 Slog.w(TAG, "Hung broadcast ["
613 + mQueueName + "] discarded after timeout failure:"
614 + " now=" + now
615 + " dispatchTime=" + r.dispatchTime
616 + " startTime=" + r.receiverTime
617 + " intent=" + r.intent
618 + " numReceivers=" + numReceivers
619 + " nextReceiver=" + r.nextReceiver
620 + " state=" + r.state);
621 broadcastTimeoutLocked(false); // forcibly finish this broadcast
622 forceReceive = true;
623 r.state = BroadcastRecord.IDLE;
624 }
625 }
626
627 if (r.state != BroadcastRecord.IDLE) {
628 if (DEBUG_BROADCAST) Slog.d(TAG,
629 "processNextBroadcast("
630 + mQueueName + ") called when not idle (state="
631 + r.state + ")");
632 return;
633 }
634
635 if (r.receivers == null || r.nextReceiver >= numReceivers
636 || r.resultAbort || forceReceive) {
637 // No more receivers for this broadcast! Send the final
638 // result if requested...
639 if (r.resultTo != null) {
640 try {
641 if (DEBUG_BROADCAST) {
642 int seq = r.intent.getIntExtra("seq", -1);
643 Slog.i(TAG, "Finishing broadcast ["
644 + mQueueName + "] " + r.intent.getAction()
645 + " seq=" + seq + " app=" + r.callerApp);
646 }
647 performReceiveLocked(r.callerApp, r.resultTo,
648 new Intent(r.intent), r.resultCode,
649 r.resultData, r.resultExtras, false, false);
650 // Set this to null so that the reference
651 // (local and remote) isnt kept in the mBroadcastHistory.
652 r.resultTo = null;
653 } catch (RemoteException e) {
654 Slog.w(TAG, "Failure ["
655 + mQueueName + "] sending broadcast result of "
656 + r.intent, e);
657 }
658 }
659
660 if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
661 cancelBroadcastTimeoutLocked();
662
663 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
664 + r);
665
666 // ... and on to the next...
667 addBroadcastToHistoryLocked(r);
668 mOrderedBroadcasts.remove(0);
669 r = null;
670 looped = true;
671 continue;
672 }
673 } while (r == null);
674
675 // Get the next receiver...
676 int recIdx = r.nextReceiver++;
677
678 // Keep track of when this receiver started, and make sure there
679 // is a timeout message pending to kill it if need be.
680 r.receiverTime = SystemClock.uptimeMillis();
681 if (recIdx == 0) {
682 r.dispatchTime = r.receiverTime;
683 r.dispatchClockTime = System.currentTimeMillis();
684 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast ["
685 + mQueueName + "] " + r);
686 }
687 if (! mPendingBroadcastTimeoutMessage) {
688 long timeoutTime = r.receiverTime + mTimeoutPeriod;
689 if (DEBUG_BROADCAST) Slog.v(TAG,
690 "Submitting BROADCAST_TIMEOUT_MSG ["
691 + mQueueName + "] for " + r + " at " + timeoutTime);
692 setBroadcastTimeoutLocked(timeoutTime);
693 }
694
695 Object nextReceiver = r.receivers.get(recIdx);
696 if (nextReceiver instanceof BroadcastFilter) {
697 // Simple case: this is a registered receiver who gets
698 // a direct call.
699 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
700 if (DEBUG_BROADCAST) Slog.v(TAG,
701 "Delivering ordered ["
702 + mQueueName + "] to registered "
703 + filter + ": " + r);
704 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
705 if (r.receiver == null || !r.ordered) {
706 // The receiver has already finished, so schedule to
707 // process the next one.
708 if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing ["
709 + mQueueName + "]: ordered="
710 + r.ordered + " receiver=" + r.receiver);
711 r.state = BroadcastRecord.IDLE;
712 scheduleBroadcastsLocked();
713 }
714 return;
715 }
716
717 // Hard case: need to instantiate the receiver, possibly
718 // starting its application process to host it.
719
720 ResolveInfo info =
721 (ResolveInfo)nextReceiver;
722
723 boolean skip = false;
724 int perm = checkComponentPermission(info.activityInfo.permission,
725 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
726 info.activityInfo.exported);
727 if (perm != PackageManager.PERMISSION_GRANTED) {
728 if (!info.activityInfo.exported) {
729 Slog.w(TAG, "Permission Denial: broadcasting "
730 + r.intent.toString()
731 + " from " + r.callerPackage + " (pid=" + r.callingPid
732 + ", uid=" + r.callingUid + ")"
733 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
734 + " due to receiver " + info.activityInfo.packageName
735 + "/" + info.activityInfo.name);
736 } else {
737 Slog.w(TAG, "Permission Denial: broadcasting "
738 + r.intent.toString()
739 + " from " + r.callerPackage + " (pid=" + r.callingPid
740 + ", uid=" + r.callingUid + ")"
741 + " requires " + info.activityInfo.permission
742 + " due to receiver " + info.activityInfo.packageName
743 + "/" + info.activityInfo.name);
744 }
745 skip = true;
746 }
747 if (info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
748 r.requiredPermission != null) {
749 try {
750 perm = AppGlobals.getPackageManager().
751 checkPermission(r.requiredPermission,
752 info.activityInfo.applicationInfo.packageName);
753 } catch (RemoteException e) {
754 perm = PackageManager.PERMISSION_DENIED;
755 }
756 if (perm != PackageManager.PERMISSION_GRANTED) {
757 Slog.w(TAG, "Permission Denial: receiving "
758 + r.intent + " to "
759 + info.activityInfo.applicationInfo.packageName
760 + " requires " + r.requiredPermission
761 + " due to sender " + r.callerPackage
762 + " (uid " + r.callingUid + ")");
763 skip = true;
764 }
765 }
766 if (r.curApp != null && r.curApp.crashing) {
767 // If the target process is crashing, just skip it.
768 if (DEBUG_BROADCAST) Slog.v(TAG,
769 "Skipping deliver ordered ["
770 + mQueueName + "] " + r + " to " + r.curApp
771 + ": process crashing");
772 skip = true;
773 }
774
775 if (skip) {
776 if (DEBUG_BROADCAST) Slog.v(TAG,
777 "Skipping delivery of ordered ["
778 + mQueueName + "] " + r + " for whatever reason");
779 r.receiver = null;
780 r.curFilter = null;
781 r.state = BroadcastRecord.IDLE;
782 scheduleBroadcastsLocked();
783 return;
784 }
785
786 r.state = BroadcastRecord.APP_RECEIVE;
787 String targetProcess = info.activityInfo.processName;
788 r.curComponent = new ComponentName(
789 info.activityInfo.applicationInfo.packageName,
790 info.activityInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -0700791 if (r.callingUid != Process.SYSTEM_UID) {
792 info.activityInfo = getActivityInfoForUser(info.activityInfo, UserId
793 .getUserId(r.callingUid));
794 }
Christopher Tatef46723b2012-01-26 14:19:24 -0800795 r.curReceiver = info.activityInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -0700796 if (DEBUG_MU && r.callingUid > UserId.PER_USER_RANGE) {
797 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
798 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
799 + info.activityInfo.applicationInfo.uid);
800 }
Christopher Tatef46723b2012-01-26 14:19:24 -0800801
802 // Broadcast is being executed, its package can't be stopped.
803 try {
804 AppGlobals.getPackageManager().setPackageStoppedState(
805 r.curComponent.getPackageName(), false);
806 } catch (RemoteException e) {
807 } catch (IllegalArgumentException e) {
808 Slog.w(TAG, "Failed trying to unstop package "
809 + r.curComponent.getPackageName() + ": " + e);
810 }
811
812 // Is this receiver's application already running?
813 ProcessRecord app = getProcessRecordLocked(targetProcess,
814 info.activityInfo.applicationInfo.uid);
815 if (app != null && app.thread != null) {
816 try {
817 app.addPackage(info.activityInfo.packageName);
818 processCurBroadcastLocked(r, app);
819 return;
820 } catch (RemoteException e) {
821 Slog.w(TAG, "Exception when sending broadcast to "
822 + r.curComponent, e);
823 }
824
825 // If a dead object exception was thrown -- fall through to
826 // restart the application.
827 }
828
829 // Not running -- get it started, to be executed when the app comes up.
830 if (DEBUG_BROADCAST) Slog.v(TAG,
831 "Need to start app ["
832 + mQueueName + "] " + targetProcess + " for broadcast " + r);
833 if ((r.curApp=startProcessLocked(targetProcess,
834 info.activityInfo.applicationInfo, true,
835 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
836 "broadcast", r.curComponent,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800837 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false))
Christopher Tatef46723b2012-01-26 14:19:24 -0800838 == null) {
839 // Ah, this recipient is unavailable. Finish it if necessary,
840 // and mark the broadcast record as ready for the next.
841 Slog.w(TAG, "Unable to launch app "
842 + info.activityInfo.applicationInfo.packageName + "/"
843 + info.activityInfo.applicationInfo.uid + " for broadcast "
844 + r.intent + ": process is bad");
845 logBroadcastReceiverDiscardLocked(r);
846 finishReceiverLocked(r, r.resultCode, r.resultData,
847 r.resultExtras, r.resultAbort, true);
848 scheduleBroadcastsLocked();
849 r.state = BroadcastRecord.IDLE;
850 return;
851 }
852
853 mPendingBroadcast = r;
854 mPendingBroadcastRecvIndex = recIdx;
855 }
856 }
857
858 final void setBroadcastTimeoutLocked(long timeoutTime) {
859 if (! mPendingBroadcastTimeoutMessage) {
860 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
861 mHandler.sendMessageAtTime(msg, timeoutTime);
862 mPendingBroadcastTimeoutMessage = true;
863 }
864 }
865
866 final void cancelBroadcastTimeoutLocked() {
867 if (mPendingBroadcastTimeoutMessage) {
868 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
869 mPendingBroadcastTimeoutMessage = false;
870 }
871 }
872
873 final void broadcastTimeoutLocked(boolean fromMsg) {
874 if (fromMsg) {
875 mPendingBroadcastTimeoutMessage = false;
876 }
877
878 if (mOrderedBroadcasts.size() == 0) {
879 return;
880 }
881
882 long now = SystemClock.uptimeMillis();
883 BroadcastRecord r = mOrderedBroadcasts.get(0);
884 if (fromMsg) {
885 if (mDidDexOpt) {
886 // Delay timeouts until dexopt finishes.
887 mDidDexOpt = false;
888 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
889 setBroadcastTimeoutLocked(timeoutTime);
890 return;
891 }
892 if (! mProcessesReady) {
893 // Only process broadcast timeouts if the system is ready. That way
894 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
895 // to do heavy lifting for system up.
896 return;
897 }
898
899 long timeoutTime = r.receiverTime + mTimeoutPeriod;
900 if (timeoutTime > now) {
901 // We can observe premature timeouts because we do not cancel and reset the
902 // broadcast timeout message after each receiver finishes. Instead, we set up
903 // an initial timeout then kick it down the road a little further as needed
904 // when it expires.
905 if (DEBUG_BROADCAST) Slog.v(TAG,
906 "Premature timeout ["
907 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
908 + timeoutTime);
909 setBroadcastTimeoutLocked(timeoutTime);
910 return;
911 }
912 }
913
914 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
915 + ", started " + (now - r.receiverTime) + "ms ago");
916 r.receiverTime = now;
917 r.anrCount++;
918
919 // Current receiver has passed its expiration date.
920 if (r.nextReceiver <= 0) {
921 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
922 return;
923 }
924
925 ProcessRecord app = null;
926 String anrMessage = null;
927
928 Object curReceiver = r.receivers.get(r.nextReceiver-1);
929 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
930 logBroadcastReceiverDiscardLocked(r);
931 if (curReceiver instanceof BroadcastFilter) {
932 BroadcastFilter bf = (BroadcastFilter)curReceiver;
933 if (bf.receiverList.pid != 0
934 && bf.receiverList.pid != MY_PID) {
935 synchronized (ActivityManagerService.this.mPidsSelfLocked) {
936 app = ActivityManagerService.this.mPidsSelfLocked.get(
937 bf.receiverList.pid);
938 }
939 }
940 } else {
941 app = r.curApp;
942 }
943
944 if (app != null) {
945 anrMessage = "Broadcast of " + r.intent.toString();
946 }
947
948 if (mPendingBroadcast == r) {
949 mPendingBroadcast = null;
950 }
951
952 // Move on to the next receiver.
953 finishReceiverLocked(r, r.resultCode, r.resultData,
954 r.resultExtras, r.resultAbort, true);
955 scheduleBroadcastsLocked();
956
957 if (anrMessage != null) {
958 // Post the ANR to the handler since we do not want to process ANRs while
959 // potentially holding our lock.
960 mHandler.post(new AppNotResponding(app, anrMessage));
961 }
962 }
963
964 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
965 if (r.callingUid < 0) {
966 // This was from a registerReceiver() call; ignore it.
967 return;
968 }
969 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
970 MAX_BROADCAST_HISTORY-1);
971 r.finishTime = SystemClock.uptimeMillis();
972 mBroadcastHistory[0] = r;
973 }
974
975 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
976 if (r.nextReceiver > 0) {
977 Object curReceiver = r.receivers.get(r.nextReceiver-1);
978 if (curReceiver instanceof BroadcastFilter) {
979 BroadcastFilter bf = (BroadcastFilter) curReceiver;
980 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
981 System.identityHashCode(r),
982 r.intent.getAction(),
983 r.nextReceiver - 1,
984 System.identityHashCode(bf));
985 } else {
986 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
987 System.identityHashCode(r),
988 r.intent.getAction(),
989 r.nextReceiver - 1,
990 ((ResolveInfo)curReceiver).toString());
991 }
992 } else {
993 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
994 + r);
995 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
996 System.identityHashCode(r),
997 r.intent.getAction(),
998 r.nextReceiver,
999 "NONE");
1000 }
1001 }
1002
1003 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1004 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
1005 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1006 || mPendingBroadcast != null) {
1007 boolean printed = false;
1008 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
1009 BroadcastRecord br = mParallelBroadcasts.get(i);
1010 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1011 continue;
1012 }
1013 if (!printed) {
1014 if (needSep) {
1015 pw.println();
1016 needSep = false;
1017 }
1018 printed = true;
1019 pw.println(" Active broadcasts [" + mQueueName + "]:");
1020 }
1021 pw.println(" Broadcast #" + i + ":");
1022 br.dump(pw, " ");
1023 }
1024 printed = false;
1025 needSep = true;
1026 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
1027 BroadcastRecord br = mOrderedBroadcasts.get(i);
1028 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1029 continue;
1030 }
1031 if (!printed) {
1032 if (needSep) {
1033 pw.println();
1034 }
1035 needSep = true;
1036 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1037 }
1038 pw.println(" Ordered Broadcast #" + i + ":");
1039 mOrderedBroadcasts.get(i).dump(pw, " ");
1040 }
1041 if (dumpPackage == null || (mPendingBroadcast != null
1042 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1043 if (needSep) {
1044 pw.println();
1045 }
1046 pw.println(" Pending broadcast [" + mQueueName + "]:");
1047 if (mPendingBroadcast != null) {
1048 mPendingBroadcast.dump(pw, " ");
1049 } else {
1050 pw.println(" (null)");
1051 }
1052 needSep = true;
1053 }
1054 }
1055
1056 boolean printed = false;
1057 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
1058 BroadcastRecord r = mBroadcastHistory[i];
1059 if (r == null) {
1060 break;
1061 }
1062 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1063 continue;
1064 }
1065 if (!printed) {
1066 if (needSep) {
1067 pw.println();
1068 }
1069 needSep = true;
1070 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1071 printed = true;
1072 }
1073 if (dumpAll) {
1074 pw.print(" Historical Broadcast #"); pw.print(i); pw.println(":");
1075 r.dump(pw, " ");
1076 } else {
1077 if (i >= 50) {
1078 pw.println(" ...");
1079 break;
1080 }
1081 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1082 }
1083 }
1084
1085 return needSep;
1086 }
1087 }
1088
1089 final BroadcastQueue mFgBroadcastQueue = new BroadcastQueue("foreground", BROADCAST_FG_TIMEOUT);
1090 final BroadcastQueue mBgBroadcastQueue = new BroadcastQueue("background", BROADCAST_BG_TIMEOUT);
1091 // Convenient for easy iteration over the queues. Foreground is first
1092 // so that dispatch of foreground broadcasts gets precedence.
1093 final BroadcastQueue[] mBroadcastQueues = { mFgBroadcastQueue, mBgBroadcastQueue };
1094
1095 BroadcastQueue broadcastQueueForIntent(Intent intent) {
1096 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
1097 if (DEBUG_BACKGROUND_BROADCAST) {
1098 Slog.i(TAG, "Broadcast intent " + intent + " on "
1099 + (isFg ? "foreground" : "background")
1100 + " queue");
1101 }
1102 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
1103 }
1104
1105 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
1106 for (BroadcastQueue queue : mBroadcastQueues) {
1107 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
1108 if (r != null) {
1109 return r;
1110 }
1111 }
1112 return null;
1113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114
1115 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 * Activity we have told the window manager to have key focus.
1117 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001118 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07001119 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 * List of intents that were used to start the most recent tasks.
1121 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001122 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123
1124 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -07001125 * Process management.
1126 */
1127 final ProcessList mProcessList = new ProcessList();
1128
1129 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 * All of the applications we currently have running organized by name.
1131 * The keys are strings of the application package name (as
1132 * returned by the package manager), and the keys are ApplicationRecord
1133 * objects.
1134 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001135 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136
1137 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001138 * The currently running isolated processes.
1139 */
1140 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
1141
1142 /**
1143 * Counter for assigning isolated process uids, to avoid frequently reusing the
1144 * same ones.
1145 */
1146 int mNextIsolatedProcessUid = 0;
1147
1148 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -07001149 * The currently running heavy-weight process, if any.
1150 */
1151 ProcessRecord mHeavyWeightProcess = null;
1152
1153 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 * The last time that various processes have crashed.
1155 */
1156 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
1157
1158 /**
1159 * Set of applications that we consider to be bad, and will reject
1160 * incoming broadcasts from (which the user has no control over).
1161 * Processes are added to this set when they have crashed twice within
1162 * a minimum amount of time; they are removed from it when they are
1163 * later restarted (hopefully due to some user action). The value is the
1164 * time it was added to the list.
1165 */
1166 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
1167
1168 /**
1169 * All of the processes we currently have running organized by pid.
1170 * The keys are the pid running the application.
1171 *
1172 * <p>NOTE: This object is protected by its own lock, NOT the global
1173 * activity manager lock!
1174 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001175 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176
1177 /**
1178 * All of the processes that have been forced to be foreground. The key
1179 * is the pid of the caller who requested it (we hold a death
1180 * link on it).
1181 */
1182 abstract class ForegroundToken implements IBinder.DeathRecipient {
1183 int pid;
1184 IBinder token;
1185 }
1186 final SparseArray<ForegroundToken> mForegroundProcesses
1187 = new SparseArray<ForegroundToken>();
1188
1189 /**
1190 * List of records for processes that someone had tried to start before the
1191 * system was ready. We don't start them at that point, but ensure they
1192 * are started by the time booting is complete.
1193 */
1194 final ArrayList<ProcessRecord> mProcessesOnHold
1195 = new ArrayList<ProcessRecord>();
1196
1197 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 * List of persistent applications that are in the process
1199 * of being started.
1200 */
1201 final ArrayList<ProcessRecord> mPersistentStartingProcesses
1202 = new ArrayList<ProcessRecord>();
1203
1204 /**
1205 * Processes that are being forcibly torn down.
1206 */
1207 final ArrayList<ProcessRecord> mRemovedProcesses
1208 = new ArrayList<ProcessRecord>();
1209
1210 /**
1211 * List of running applications, sorted by recent usage.
1212 * The first entry in the list is the least recently used.
1213 * It contains ApplicationRecord objects. This list does NOT include
1214 * any persistent application records (since we never want to exit them).
1215 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001216 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 = new ArrayList<ProcessRecord>();
1218
1219 /**
1220 * List of processes that should gc as soon as things are idle.
1221 */
1222 final ArrayList<ProcessRecord> mProcessesToGc
1223 = new ArrayList<ProcessRecord>();
1224
1225 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -08001226 * This is the process holding what we currently consider to be
1227 * the "home" activity.
1228 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001229 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -08001230
1231 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -07001232 * This is the process holding the activity the user last visited that
1233 * is in a different process from the one they are currently in.
1234 */
1235 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -08001236
1237 /**
1238 * The time at which the previous process was last visible.
1239 */
1240 long mPreviousProcessVisibleTime;
1241
Dianne Hackbornf35fe232011-11-01 19:25:20 -07001242 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001243 * Packages that the user has asked to have run in screen size
1244 * compatibility mode instead of filling the screen.
1245 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001246 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001247
1248 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 * Set of PendingResultRecord objects that are currently active.
1250 */
1251 final HashSet mPendingResultRecords = new HashSet();
1252
1253 /**
1254 * Set of IntentSenderRecord objects that are currently active.
1255 */
1256 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
1257 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
1258
1259 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08001260 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07001261 * already logged DropBox entries for. Guarded by itself. If
1262 * something (rogue user app) forces this over
1263 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
1264 */
1265 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
1266 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
1267
1268 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07001269 * Strict Mode background batched logging state.
1270 *
1271 * The string buffer is guarded by itself, and its lock is also
1272 * used to determine if another batched write is already
1273 * in-flight.
1274 */
1275 private final StringBuilder mStrictModeBuffer = new StringBuilder();
1276
1277 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 * Keeps track of all IIntentReceivers that have been registered for
1279 * broadcasts. Hash keys are the receiver IBinder, hash value is
1280 * a ReceiverList.
1281 */
1282 final HashMap mRegisteredReceivers = new HashMap();
1283
1284 /**
1285 * Resolver for broadcast intents to registered receivers.
1286 * Holds BroadcastFilter (subclass of IntentFilter).
1287 */
1288 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
1289 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
1290 @Override
1291 protected boolean allowFilterResult(
1292 BroadcastFilter filter, List<BroadcastFilter> dest) {
1293 IBinder target = filter.receiverList.receiver.asBinder();
1294 for (int i=dest.size()-1; i>=0; i--) {
1295 if (dest.get(i).receiverList.receiver.asBinder() == target) {
1296 return false;
1297 }
1298 }
1299 return true;
1300 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001301
1302 @Override
1303 protected String packageForFilter(BroadcastFilter filter) {
1304 return filter.packageName;
1305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 };
1307
1308 /**
1309 * State of all active sticky broadcasts. Keys are the action of the
1310 * sticky Intent, values are an ArrayList of all broadcasted intents with
1311 * that action (which should usually be one).
1312 */
1313 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
1314 new HashMap<String, ArrayList<Intent>>();
1315
Amith Yamasani742a6712011-05-04 14:49:28 -07001316 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317
1318 /**
1319 * All currently bound service connections. Keys are the IBinder of
1320 * the client's IServiceConnection.
1321 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07001322 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
1323 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324
1325 /**
1326 * List of services that we have been asked to start,
1327 * but haven't yet been able to. It is used to hold start requests
1328 * while waiting for their corresponding application thread to get
1329 * going.
1330 */
1331 final ArrayList<ServiceRecord> mPendingServices
1332 = new ArrayList<ServiceRecord>();
1333
1334 /**
1335 * List of services that are scheduled to restart following a crash.
1336 */
1337 final ArrayList<ServiceRecord> mRestartingServices
1338 = new ArrayList<ServiceRecord>();
1339
1340 /**
1341 * List of services that are in the process of being stopped.
1342 */
1343 final ArrayList<ServiceRecord> mStoppingServices
1344 = new ArrayList<ServiceRecord>();
1345
1346 /**
Christopher Tate181fafa2009-05-14 11:12:14 -07001347 * Backup/restore process management
1348 */
1349 String mBackupAppName = null;
1350 BackupRecord mBackupTarget = null;
1351
1352 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 * List of PendingThumbnailsRecord objects of clients who are still
1354 * waiting to receive all of the thumbnails for a task.
1355 */
1356 final ArrayList mPendingThumbnails = new ArrayList();
1357
1358 /**
1359 * List of HistoryRecord objects that have been finished and must
1360 * still report back to a pending thumbnail receiver.
1361 */
1362 final ArrayList mCancelledThumbnails = new ArrayList();
1363
1364 /**
1365 * All of the currently running global content providers. Keys are a
1366 * string containing the provider name and values are a
1367 * ContentProviderRecord object containing the data about it. Note
1368 * that a single provider may be published under multiple names, so
1369 * there may be multiple entries here for a single one in mProvidersByClass.
1370 */
Dianne Hackborn860755f2010-06-03 18:47:52 -07001371 final HashMap<String, ContentProviderRecord> mProvidersByName
1372 = new HashMap<String, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373
1374 /**
1375 * All of the currently running global content providers. Keys are a
1376 * string containing the provider's implementation class and values are a
1377 * ContentProviderRecord object containing the data about it.
1378 */
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07001379 final HashMap<ComponentName, ContentProviderRecord> mProvidersByClass
1380 = new HashMap<ComponentName, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381
Amith Yamasani742a6712011-05-04 14:49:28 -07001382 final ProviderMap mProviderMap = new ProviderMap();
1383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 /**
1385 * List of content providers who have clients waiting for them. The
1386 * application is currently being launched and the provider will be
1387 * removed from this list once it is published.
1388 */
Dianne Hackborn860755f2010-06-03 18:47:52 -07001389 final ArrayList<ContentProviderRecord> mLaunchingProviders
1390 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391
1392 /**
1393 * Global set of specific Uri permissions that have been granted.
1394 */
1395 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
1396 = new SparseArray<HashMap<Uri, UriPermission>>();
1397
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001398 CoreSettingsObserver mCoreSettingsObserver;
1399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 /**
1401 * Thread-local storage used to carry caller permissions over through
1402 * indirect content-provider access.
1403 * @see #ActivityManagerService.openContentUri()
1404 */
1405 private class Identity {
1406 public int pid;
1407 public int uid;
1408
1409 Identity(int _pid, int _uid) {
1410 pid = _pid;
1411 uid = _uid;
1412 }
1413 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
1416
1417 /**
1418 * All information we have collected about the runtime performance of
1419 * any user id that can impact battery performance.
1420 */
1421 final BatteryStatsService mBatteryStatsService;
1422
1423 /**
1424 * information about component usage
1425 */
1426 final UsageStatsService mUsageStatsService;
1427
1428 /**
1429 * Current configuration information. HistoryRecord objects are given
1430 * a reference to this object to indicate which configuration they are
1431 * currently running in, so this object must be kept immutable.
1432 */
1433 Configuration mConfiguration = new Configuration();
1434
1435 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001436 * Current sequencing integer of the configuration, for skipping old
1437 * configurations.
1438 */
1439 int mConfigurationSeq = 0;
1440
1441 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -07001442 * Hardware-reported OpenGLES version.
1443 */
1444 final int GL_ES_VERSION;
1445
1446 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 * List of initialization arguments to pass to all processes when binding applications to them.
1448 * For example, references to the commonly used services.
1449 */
1450 HashMap<String, IBinder> mAppBindArgs;
1451
1452 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07001453 * Temporary to avoid allocations. Protected by main lock.
1454 */
1455 final StringBuilder mStringBuilder = new StringBuilder(256);
1456
1457 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 * Used to control how we initialize the service.
1459 */
1460 boolean mStartRunning = false;
1461 ComponentName mTopComponent;
1462 String mTopAction;
1463 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001464 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 boolean mSystemReady = false;
1466 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001467 boolean mWaitingUpdate = false;
1468 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001469 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001470 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471
1472 Context mContext;
1473
1474 int mFactoryTest;
1475
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001476 boolean mCheckedForSetup;
1477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001479 * The time at which we will allow normal application switches again,
1480 * after a call to {@link #stopAppSwitches()}.
1481 */
1482 long mAppSwitchesAllowedTime;
1483
1484 /**
1485 * This is set to true after the first switch after mAppSwitchesAllowedTime
1486 * is set; any switches after that will clear the time.
1487 */
1488 boolean mDidAppSwitch;
1489
1490 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -07001491 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001492 */
Dianne Hackborn287952c2010-09-22 22:34:31 -07001493 long mLastPowerCheckRealtime;
1494
1495 /**
1496 * Last time (in uptime) at which we checked for power usage.
1497 */
1498 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001499
1500 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 * Set while we are wanting to sleep, to prevent any
1502 * activities from being started/resumed.
1503 */
1504 boolean mSleeping = false;
1505
1506 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -07001507 * Set if we are shutting down the system, similar to sleeping.
1508 */
1509 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510
1511 /**
1512 * Task identifier that activities are currently being started
1513 * in. Incremented each time a new task is created.
1514 * todo: Replace this with a TokenSpace class that generates non-repeating
1515 * integers that won't wrap.
1516 */
1517 int mCurTask = 1;
1518
1519 /**
1520 * Current sequence id for oom_adj computation traversal.
1521 */
1522 int mAdjSeq = 0;
1523
1524 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -07001525 * Current sequence id for process LRU updating.
1526 */
1527 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528
1529 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -07001530 * Keep track of the number of service processes we last found, to
1531 * determine on the next iteration which should be B services.
1532 */
1533 int mNumServiceProcs = 0;
1534 int mNewNumServiceProcs = 0;
1535
1536 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 * System monitoring: number of processes that died since the last
1538 * N procs were started.
1539 */
1540 int[] mProcDeaths = new int[20];
1541
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001542 /**
1543 * This is set if we had to do a delayed dexopt of an app before launching
1544 * it, to increasing the ANR timeouts in that case.
1545 */
1546 boolean mDidDexOpt;
1547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 String mDebugApp = null;
1549 boolean mWaitForDebugger = false;
1550 boolean mDebugTransient = false;
1551 String mOrigDebugApp = null;
1552 boolean mOrigWaitForDebugger = false;
1553 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001554 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001555 String mProfileApp = null;
1556 ProcessRecord mProfileProc = null;
1557 String mProfileFile;
1558 ParcelFileDescriptor mProfileFd;
1559 int mProfileType = 0;
1560 boolean mAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561
Jeff Sharkeya4620792011-05-20 15:29:23 -07001562 final RemoteCallbackList<IProcessObserver> mProcessObservers
1563 = new RemoteCallbackList<IProcessObserver>();
1564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 /**
1566 * Callback of last caller to {@link #requestPss}.
1567 */
1568 Runnable mRequestPssCallback;
1569
1570 /**
1571 * Remaining processes for which we are waiting results from the last
1572 * call to {@link #requestPss}.
1573 */
1574 final ArrayList<ProcessRecord> mRequestPssList
1575 = new ArrayList<ProcessRecord>();
1576
1577 /**
1578 * Runtime statistics collection thread. This object's lock is used to
1579 * protect all related state.
1580 */
1581 final Thread mProcessStatsThread;
1582
1583 /**
1584 * Used to collect process stats when showing not responding dialog.
1585 * Protected by mProcessStatsThread.
1586 */
1587 final ProcessStats mProcessStats = new ProcessStats(
1588 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001589 final AtomicLong mLastCpuTime = new AtomicLong(0);
1590 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
1591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 long mLastWriteTime = 0;
1593
1594 /**
1595 * Set to true after the system has finished booting.
1596 */
1597 boolean mBooted = false;
1598
Dianne Hackborn7d608422011-08-07 16:24:18 -07001599 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001600 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601
1602 WindowManagerService mWindowManager;
1603
1604 static ActivityManagerService mSelf;
1605 static ActivityThread mSystemThread;
1606
1607 private final class AppDeathRecipient implements IBinder.DeathRecipient {
1608 final ProcessRecord mApp;
1609 final int mPid;
1610 final IApplicationThread mAppThread;
1611
1612 AppDeathRecipient(ProcessRecord app, int pid,
1613 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001614 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 TAG, "New death recipient " + this
1616 + " for thread " + thread.asBinder());
1617 mApp = app;
1618 mPid = pid;
1619 mAppThread = thread;
1620 }
1621
1622 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001623 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 TAG, "Death received in " + this
1625 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 synchronized(ActivityManagerService.this) {
1627 appDiedLocked(mApp, mPid, mAppThread);
1628 }
1629 }
1630 }
1631
1632 static final int SHOW_ERROR_MSG = 1;
1633 static final int SHOW_NOT_RESPONDING_MSG = 2;
1634 static final int SHOW_FACTORY_ERROR_MSG = 3;
1635 static final int UPDATE_CONFIGURATION_MSG = 4;
1636 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1637 static final int WAIT_FOR_DEBUGGER_MSG = 6;
1638 static final int BROADCAST_INTENT_MSG = 7;
1639 static final int BROADCAST_TIMEOUT_MSG = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 static final int SERVICE_TIMEOUT_MSG = 12;
1641 static final int UPDATE_TIME_ZONE = 13;
1642 static final int SHOW_UID_ERROR_MSG = 14;
1643 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001645 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001646 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001647 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001648 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
1649 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001650 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001651 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001652 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001653 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001654 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001655 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
1656 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001657 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658
1659 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001660 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001661 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662
1663 final Handler mHandler = new Handler() {
1664 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001665 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 //}
1667
1668 public void handleMessage(Message msg) {
1669 switch (msg.what) {
1670 case SHOW_ERROR_MSG: {
1671 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 synchronized (ActivityManagerService.this) {
1673 ProcessRecord proc = (ProcessRecord)data.get("app");
1674 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001675 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 return;
1677 }
1678 AppErrorResult res = (AppErrorResult) data.get("result");
Dianne Hackborn55280a92009-05-07 15:53:46 -07001679 if (!mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -08001680 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 d.show();
1682 proc.crashDialog = d;
1683 } else {
1684 // The device is asleep, so just pretend that the user
1685 // saw a crash dialog and hit "force quit".
1686 res.set(0);
1687 }
1688 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001689
1690 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 } break;
1692 case SHOW_NOT_RESPONDING_MSG: {
1693 synchronized (ActivityManagerService.this) {
1694 HashMap data = (HashMap) msg.obj;
1695 ProcessRecord proc = (ProcessRecord)data.get("app");
1696 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001697 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 return;
1699 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001700
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001701 Intent intent = new Intent("android.intent.action.ANR");
1702 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -08001703 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1704 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001705 }
1706 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -08001707 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07001708 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -08001709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001711 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 d.show();
1713 proc.anrDialog = d;
1714 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001715
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001716 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001718 case SHOW_STRICT_MODE_VIOLATION_MSG: {
1719 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1720 synchronized (ActivityManagerService.this) {
1721 ProcessRecord proc = (ProcessRecord) data.get("app");
1722 if (proc == null) {
1723 Slog.e(TAG, "App not found when showing strict mode dialog.");
1724 break;
1725 }
1726 if (proc.crashDialog != null) {
1727 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1728 return;
1729 }
1730 AppErrorResult res = (AppErrorResult) data.get("result");
1731 if (!mSleeping && !mShuttingDown) {
1732 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
1733 d.show();
1734 proc.crashDialog = d;
1735 } else {
1736 // The device is asleep, so just pretend that the user
1737 // saw a crash dialog and hit "force quit".
1738 res.set(0);
1739 }
1740 }
1741 ensureBootCompleted();
1742 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 case SHOW_FACTORY_ERROR_MSG: {
1744 Dialog d = new FactoryErrorDialog(
1745 mContext, msg.getData().getCharSequence("msg"));
1746 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001747 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 } break;
1749 case UPDATE_CONFIGURATION_MSG: {
1750 final ContentResolver resolver = mContext.getContentResolver();
1751 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1752 } break;
1753 case GC_BACKGROUND_PROCESSES_MSG: {
1754 synchronized (ActivityManagerService.this) {
1755 performAppGcsIfAppropriateLocked();
1756 }
1757 } break;
1758 case WAIT_FOR_DEBUGGER_MSG: {
1759 synchronized (ActivityManagerService.this) {
1760 ProcessRecord app = (ProcessRecord)msg.obj;
1761 if (msg.arg1 != 0) {
1762 if (!app.waitedForDebugger) {
1763 Dialog d = new AppWaitingForDebuggerDialog(
1764 ActivityManagerService.this,
1765 mContext, app);
1766 app.waitDialog = d;
1767 app.waitedForDebugger = true;
1768 d.show();
1769 }
1770 } else {
1771 if (app.waitDialog != null) {
1772 app.waitDialog.dismiss();
1773 app.waitDialog = null;
1774 }
1775 }
1776 }
1777 } break;
1778 case BROADCAST_INTENT_MSG: {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001779 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 TAG, "Received BROADCAST_INTENT_MSG");
Christopher Tatef46723b2012-01-26 14:19:24 -08001781 BroadcastQueue queue = (BroadcastQueue) msg.obj;
1782 queue.processNextBroadcast(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 } break;
1784 case BROADCAST_TIMEOUT_MSG: {
Christopher Tatef46723b2012-01-26 14:19:24 -08001785 final BroadcastQueue queue = (BroadcastQueue) msg.obj;
Jeff Brown4d94a762010-09-23 11:33:28 -07001786 synchronized (ActivityManagerService.this) {
Christopher Tatef46723b2012-01-26 14:19:24 -08001787 queue.broadcastTimeoutLocked(true);
Jeff Hamiltonacf84742010-05-25 22:10:18 -05001788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001791 if (mDidDexOpt) {
1792 mDidDexOpt = false;
1793 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1794 nmsg.obj = msg.obj;
1795 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
1796 return;
1797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 serviceTimeout((ProcessRecord)msg.obj);
1799 } break;
1800 case UPDATE_TIME_ZONE: {
1801 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001802 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1803 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 if (r.thread != null) {
1805 try {
1806 r.thread.updateTimeZone();
1807 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001808 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810 }
1811 }
1812 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001813 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001814 case CLEAR_DNS_CACHE: {
1815 synchronized (ActivityManagerService.this) {
1816 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1817 ProcessRecord r = mLruProcesses.get(i);
1818 if (r.thread != null) {
1819 try {
1820 r.thread.clearDnsCache();
1821 } catch (RemoteException ex) {
1822 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1823 }
1824 }
1825 }
1826 }
1827 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001828 case UPDATE_HTTP_PROXY: {
1829 ProxyProperties proxy = (ProxyProperties)msg.obj;
1830 String host = "";
1831 String port = "";
1832 String exclList = "";
1833 if (proxy != null) {
1834 host = proxy.getHost();
1835 port = Integer.toString(proxy.getPort());
1836 exclList = proxy.getExclusionList();
1837 }
1838 synchronized (ActivityManagerService.this) {
1839 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1840 ProcessRecord r = mLruProcesses.get(i);
1841 if (r.thread != null) {
1842 try {
1843 r.thread.setHttpProxy(host, port, exclList);
1844 } catch (RemoteException ex) {
1845 Slog.w(TAG, "Failed to update http proxy for: " +
1846 r.info.processName);
1847 }
1848 }
1849 }
1850 }
1851 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 case SHOW_UID_ERROR_MSG: {
1853 // XXX This is a temporary dialog, no need to localize.
1854 AlertDialog d = new BaseErrorDialog(mContext);
1855 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1856 d.setCancelable(false);
1857 d.setTitle("System UIDs Inconsistent");
1858 d.setMessage("UIDs on the system are inconsistent, you need to wipe your data partition or your device will be unstable.");
Christian Mehlmauer7664e202010-07-20 08:46:17 +02001859 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1861 mUidAlert = d;
1862 d.show();
1863 } break;
1864 case IM_FEELING_LUCKY_MSG: {
1865 if (mUidAlert != null) {
1866 mUidAlert.dismiss();
1867 mUidAlert = null;
1868 }
1869 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001871 if (mDidDexOpt) {
1872 mDidDexOpt = false;
1873 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1874 nmsg.obj = msg.obj;
1875 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1876 return;
1877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 ProcessRecord app = (ProcessRecord)msg.obj;
1879 synchronized (ActivityManagerService.this) {
1880 processStartTimedOutLocked(app);
1881 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001882 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001883 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1884 synchronized (ActivityManagerService.this) {
1885 doPendingActivityLaunchesLocked(true);
1886 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001887 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001888 case KILL_APPLICATION_MSG: {
1889 synchronized (ActivityManagerService.this) {
1890 int uid = msg.arg1;
1891 boolean restart = (msg.arg2 == 1);
1892 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001893 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001894 }
1895 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001896 case FINALIZE_PENDING_INTENT_MSG: {
1897 ((PendingIntentRecord)msg.obj).completeFinalize();
1898 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001899 case POST_HEAVY_NOTIFICATION_MSG: {
1900 INotificationManager inm = NotificationManager.getService();
1901 if (inm == null) {
1902 return;
1903 }
1904
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001905 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001906 ProcessRecord process = root.app;
1907 if (process == null) {
1908 return;
1909 }
1910
1911 try {
1912 Context context = mContext.createPackageContext(process.info.packageName, 0);
1913 String text = mContext.getString(R.string.heavy_weight_notification,
1914 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1915 Notification notification = new Notification();
1916 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1917 notification.when = 0;
1918 notification.flags = Notification.FLAG_ONGOING_EVENT;
1919 notification.tickerText = text;
1920 notification.defaults = 0; // please be quiet
1921 notification.sound = null;
1922 notification.vibrate = null;
1923 notification.setLatestEventInfo(context, text,
1924 mContext.getText(R.string.heavy_weight_notification_detail),
1925 PendingIntent.getActivity(mContext, 0, root.intent,
1926 PendingIntent.FLAG_CANCEL_CURRENT));
1927
1928 try {
1929 int[] outId = new int[1];
1930 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1931 notification, outId);
1932 } catch (RuntimeException e) {
1933 Slog.w(ActivityManagerService.TAG,
1934 "Error showing notification for heavy-weight app", e);
1935 } catch (RemoteException e) {
1936 }
1937 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001938 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001939 }
1940 } break;
1941 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1942 INotificationManager inm = NotificationManager.getService();
1943 if (inm == null) {
1944 return;
1945 }
1946 try {
1947 inm.cancelNotification("android",
1948 R.string.heavy_weight_notification);
1949 } catch (RuntimeException e) {
1950 Slog.w(ActivityManagerService.TAG,
1951 "Error canceling notification for service", e);
1952 } catch (RemoteException e) {
1953 }
1954 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001955 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1956 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001957 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001958 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001959 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1960 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001961 }
1962 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001963 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1964 synchronized (ActivityManagerService.this) {
1965 ActivityRecord ar = (ActivityRecord)msg.obj;
1966 if (mCompatModeDialog != null) {
1967 if (mCompatModeDialog.mAppInfo.packageName.equals(
1968 ar.info.applicationInfo.packageName)) {
1969 return;
1970 }
1971 mCompatModeDialog.dismiss();
1972 mCompatModeDialog = null;
1973 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001974 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001975 if (mCompatModePackages.getPackageAskCompatModeLocked(
1976 ar.packageName)) {
1977 int mode = mCompatModePackages.computeCompatModeLocked(
1978 ar.info.applicationInfo);
1979 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1980 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1981 mCompatModeDialog = new CompatModeDialog(
1982 ActivityManagerService.this, mContext,
1983 ar.info.applicationInfo);
1984 mCompatModeDialog.show();
1985 }
1986 }
1987 }
1988 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001989 break;
1990 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001991 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001992 final int pid = msg.arg1;
1993 final int uid = msg.arg2;
1994 final boolean foregroundActivities = (Boolean) msg.obj;
1995 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001996 break;
1997 }
1998 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001999 final int pid = msg.arg1;
2000 final int uid = msg.arg2;
2001 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002002 break;
2003 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002004 case REPORT_MEM_USAGE: {
2005 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
2006 if (!isDebuggable) {
2007 return;
2008 }
2009 synchronized (ActivityManagerService.this) {
2010 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002011 if (now < (mLastMemUsageReportTime+5*60*1000)) {
2012 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002013 // avoid spamming.
2014 return;
2015 }
2016 mLastMemUsageReportTime = now;
2017 }
2018 Thread thread = new Thread() {
2019 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002020 StringBuilder dropBuilder = new StringBuilder(1024);
2021 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08002022 StringWriter oomSw = new StringWriter();
2023 PrintWriter oomPw = new PrintWriter(oomSw);
2024 StringWriter catSw = new StringWriter();
2025 PrintWriter catPw = new PrintWriter(catSw);
2026 String[] emptyArgs = new String[] { };
2027 StringBuilder tag = new StringBuilder(128);
2028 StringBuilder stack = new StringBuilder(128);
2029 tag.append("Low on memory -- ");
2030 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
2031 tag, stack);
2032 dropBuilder.append(stack);
2033 dropBuilder.append('\n');
2034 dropBuilder.append('\n');
2035 String oomString = oomSw.toString();
2036 dropBuilder.append(oomString);
2037 dropBuilder.append('\n');
2038 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002039 try {
2040 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
2041 "procrank", });
2042 final InputStreamReader converter = new InputStreamReader(
2043 proc.getInputStream());
2044 BufferedReader in = new BufferedReader(converter);
2045 String line;
2046 while (true) {
2047 line = in.readLine();
2048 if (line == null) {
2049 break;
2050 }
2051 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002052 logBuilder.append(line);
2053 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002054 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002055 dropBuilder.append(line);
2056 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002057 }
2058 converter.close();
2059 } catch (IOException e) {
2060 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002061 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08002062 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002063 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002064 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002065 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002066 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002067 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002068 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002069 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08002070 addErrorToDropBox("lowmem", null, "system_server", null,
2071 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002072 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002073 synchronized (ActivityManagerService.this) {
2074 long now = SystemClock.uptimeMillis();
2075 if (mLastMemUsageReportTime < now) {
2076 mLastMemUsageReportTime = now;
2077 }
2078 }
2079 }
2080 };
2081 thread.start();
2082 break;
2083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 }
2085 }
2086 };
2087
2088 public static void setSystemProcess() {
2089 try {
2090 ActivityManagerService m = mSelf;
2091
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002092 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07002094 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08002095 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 if (MONITOR_CPU_USAGE) {
2097 ServiceManager.addService("cpuinfo", new CpuBinder(m));
2098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 ServiceManager.addService("permission", new PermissionController(m));
2100
2101 ApplicationInfo info =
2102 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07002103 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07002104 mSystemThread.installSystemApplicationInfo(info);
2105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 synchronized (mSelf) {
2107 ProcessRecord app = mSelf.newProcessRecordLocked(
2108 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002109 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08002111 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07002112 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002113 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 synchronized (mSelf.mPidsSelfLocked) {
2115 mSelf.mPidsSelfLocked.put(app.pid, app);
2116 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002117 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 }
2119 } catch (PackageManager.NameNotFoundException e) {
2120 throw new RuntimeException(
2121 "Unable to find android system package", e);
2122 }
2123 }
2124
2125 public void setWindowManager(WindowManagerService wm) {
2126 mWindowManager = wm;
2127 }
2128
2129 public static final Context main(int factoryTest) {
2130 AThread thr = new AThread();
2131 thr.start();
2132
2133 synchronized (thr) {
2134 while (thr.mService == null) {
2135 try {
2136 thr.wait();
2137 } catch (InterruptedException e) {
2138 }
2139 }
2140 }
2141
2142 ActivityManagerService m = thr.mService;
2143 mSelf = m;
2144 ActivityThread at = ActivityThread.systemMain();
2145 mSystemThread = at;
2146 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08002147 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 m.mContext = context;
2149 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002150 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151
2152 m.mBatteryStatsService.publish(context);
2153 m.mUsageStatsService.publish(context);
2154
2155 synchronized (thr) {
2156 thr.mReady = true;
2157 thr.notifyAll();
2158 }
2159
2160 m.startRunning(null, null, null, null);
2161
2162 return context;
2163 }
2164
2165 public static ActivityManagerService self() {
2166 return mSelf;
2167 }
2168
2169 static class AThread extends Thread {
2170 ActivityManagerService mService;
2171 boolean mReady = false;
2172
2173 public AThread() {
2174 super("ActivityManager");
2175 }
2176
2177 public void run() {
2178 Looper.prepare();
2179
2180 android.os.Process.setThreadPriority(
2181 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07002182 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183
2184 ActivityManagerService m = new ActivityManagerService();
2185
2186 synchronized (this) {
2187 mService = m;
2188 notifyAll();
2189 }
2190
2191 synchronized (this) {
2192 while (!mReady) {
2193 try {
2194 wait();
2195 } catch (InterruptedException e) {
2196 }
2197 }
2198 }
2199
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07002200 // For debug builds, log event loop stalls to dropbox for analysis.
2201 if (StrictMode.conditionallyEnableDebugLogging()) {
2202 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
2203 }
2204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 Looper.loop();
2206 }
2207 }
2208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 static class MemBinder extends Binder {
2210 ActivityManagerService mActivityManagerService;
2211 MemBinder(ActivityManagerService activityManagerService) {
2212 mActivityManagerService = activityManagerService;
2213 }
2214
2215 @Override
2216 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002217 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2218 != PackageManager.PERMISSION_GRANTED) {
2219 pw.println("Permission Denial: can't dump meminfo from from pid="
2220 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2221 + " without permission " + android.Manifest.permission.DUMP);
2222 return;
2223 }
2224
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08002225 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08002226 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 }
2228 }
2229
Chet Haase9c1e23b2011-03-24 10:51:31 -07002230 static class GraphicsBinder extends Binder {
2231 ActivityManagerService mActivityManagerService;
2232 GraphicsBinder(ActivityManagerService activityManagerService) {
2233 mActivityManagerService = activityManagerService;
2234 }
2235
2236 @Override
2237 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002238 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2239 != PackageManager.PERMISSION_GRANTED) {
2240 pw.println("Permission Denial: can't dump gfxinfo from from pid="
2241 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2242 + " without permission " + android.Manifest.permission.DUMP);
2243 return;
2244 }
2245
Dianne Hackborne17aeb32011-04-07 15:11:57 -07002246 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07002247 }
2248 }
2249
Jeff Brown6754ba22011-12-14 20:20:01 -08002250 static class DbBinder extends Binder {
2251 ActivityManagerService mActivityManagerService;
2252 DbBinder(ActivityManagerService activityManagerService) {
2253 mActivityManagerService = activityManagerService;
2254 }
2255
2256 @Override
2257 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2258 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2259 != PackageManager.PERMISSION_GRANTED) {
2260 pw.println("Permission Denial: can't dump dbinfo from from pid="
2261 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2262 + " without permission " + android.Manifest.permission.DUMP);
2263 return;
2264 }
2265
2266 mActivityManagerService.dumpDbInfo(fd, pw, args);
2267 }
2268 }
2269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 static class CpuBinder extends Binder {
2271 ActivityManagerService mActivityManagerService;
2272 CpuBinder(ActivityManagerService activityManagerService) {
2273 mActivityManagerService = activityManagerService;
2274 }
2275
2276 @Override
2277 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002278 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2279 != PackageManager.PERMISSION_GRANTED) {
2280 pw.println("Permission Denial: can't dump cpuinfo from from pid="
2281 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2282 + " without permission " + android.Manifest.permission.DUMP);
2283 return;
2284 }
2285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002287 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
2288 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
2289 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 }
2291 }
2292 }
2293
2294 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002295 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07002296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 File dataDir = Environment.getDataDirectory();
2298 File systemDir = new File(dataDir, "system");
2299 systemDir.mkdirs();
2300 mBatteryStatsService = new BatteryStatsService(new File(
2301 systemDir, "batterystats.bin").toString());
2302 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07002303 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07002304 mOnBattery = DEBUG_POWER ? true
2305 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002306 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002308 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07002309 systemDir, "usagestats").toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310
Jack Palevichb90d28c2009-07-22 15:35:24 -07002311 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
2312 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
2313
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002314 mConfiguration.setToDefaults();
2315 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08002316 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 mProcessStats.init();
2318
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002319 mCompatModePackages = new CompatModePackages(this, systemDir);
2320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 // Add ourself to the Watchdog monitors.
2322 Watchdog.getInstance().addMonitor(this);
2323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 mProcessStatsThread = new Thread("ProcessStats") {
2325 public void run() {
2326 while (true) {
2327 try {
2328 try {
2329 synchronized(this) {
2330 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002331 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002333 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 // + ", write delay=" + nextWriteDelay);
2335 if (nextWriteDelay < nextCpuDelay) {
2336 nextCpuDelay = nextWriteDelay;
2337 }
2338 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002339 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 this.wait(nextCpuDelay);
2341 }
2342 }
2343 } catch (InterruptedException e) {
2344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 updateCpuStatsNow();
2346 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002347 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 }
2349 }
2350 }
2351 };
2352 mProcessStatsThread.start();
2353 }
2354
2355 @Override
2356 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2357 throws RemoteException {
2358 try {
2359 return super.onTransact(code, data, reply, flags);
2360 } catch (RuntimeException e) {
2361 // The activity manager only throws security exceptions, so let's
2362 // log all others.
2363 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002364 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 }
2366 throw e;
2367 }
2368 }
2369
2370 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002371 final long now = SystemClock.uptimeMillis();
2372 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
2373 return;
2374 }
2375 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
2376 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 mProcessStatsThread.notify();
2378 }
2379 }
2380 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 void updateCpuStatsNow() {
2383 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002384 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 final long now = SystemClock.uptimeMillis();
2386 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07002387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002389 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
2390 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 haveNewCpuStats = true;
2392 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002393 //Slog.i(TAG, mProcessStats.printCurrentState());
2394 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 // + mProcessStats.getTotalCpuPercent() + "%");
2396
Joe Onorato8a9b2202010-02-26 18:56:32 -08002397 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 if ("true".equals(SystemProperties.get("events.cpu"))) {
2399 int user = mProcessStats.getLastUserTime();
2400 int system = mProcessStats.getLastSystemTime();
2401 int iowait = mProcessStats.getLastIoWaitTime();
2402 int irq = mProcessStats.getLastIrqTime();
2403 int softIrq = mProcessStats.getLastSoftIrqTime();
2404 int idle = mProcessStats.getLastIdleTime();
2405
2406 int total = user + system + iowait + irq + softIrq + idle;
2407 if (total == 0) total = 1;
2408
Doug Zongker2bec3d42009-12-04 12:52:44 -08002409 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 ((user+system+iowait+irq+softIrq) * 100) / total,
2411 (user * 100) / total,
2412 (system * 100) / total,
2413 (iowait * 100) / total,
2414 (irq * 100) / total,
2415 (softIrq * 100) / total);
2416 }
2417 }
2418
Amith Yamasanie43530a2009-08-21 13:11:37 -07002419 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07002420 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002421 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 synchronized(mPidsSelfLocked) {
2423 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002424 if (mOnBattery) {
2425 int perc = bstats.startAddingCpuLocked();
2426 int totalUTime = 0;
2427 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07002428 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07002430 ProcessStats.Stats st = mProcessStats.getStats(i);
2431 if (!st.working) {
2432 continue;
2433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002435 int otherUTime = (st.rel_utime*perc)/100;
2436 int otherSTime = (st.rel_stime*perc)/100;
2437 totalUTime += otherUTime;
2438 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 if (pr != null) {
2440 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002441 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
2442 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07002443 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07002444 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002445 } else {
2446 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07002447 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002448 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002449 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
2450 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07002451 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 }
2454 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002455 bstats.finishAddingCpuLocked(perc, totalUTime,
2456 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 }
2458 }
2459 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
2462 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07002463 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 }
2465 }
2466 }
2467 }
2468
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002469 @Override
2470 public void batteryNeedsCpuUpdate() {
2471 updateCpuStatsNow();
2472 }
2473
2474 @Override
2475 public void batteryPowerChanged(boolean onBattery) {
2476 // When plugging in, update the CPU stats first before changing
2477 // the plug state.
2478 updateCpuStatsNow();
2479 synchronized (this) {
2480 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07002481 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002482 }
2483 }
2484 }
2485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 /**
2487 * Initialize the application bind args. These are passed to each
2488 * process when the bindApplication() IPC is sent to the process. They're
2489 * lazily setup to make sure the services are running when they're asked for.
2490 */
2491 private HashMap<String, IBinder> getCommonServicesLocked() {
2492 if (mAppBindArgs == null) {
2493 mAppBindArgs = new HashMap<String, IBinder>();
2494
2495 // Setup the application init args
2496 mAppBindArgs.put("package", ServiceManager.getService("package"));
2497 mAppBindArgs.put("window", ServiceManager.getService("window"));
2498 mAppBindArgs.put(Context.ALARM_SERVICE,
2499 ServiceManager.getService(Context.ALARM_SERVICE));
2500 }
2501 return mAppBindArgs;
2502 }
2503
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002504 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 if (mFocusedActivity != r) {
2506 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002507 if (r != null) {
2508 mWindowManager.setFocusedApp(r.appToken, true);
2509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 }
2511 }
2512
Dianne Hackborn906497c2010-05-10 15:57:38 -07002513 private final void updateLruProcessInternalLocked(ProcessRecord app,
2514 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002516 int lrui = mLruProcesses.indexOf(app);
2517 if (lrui >= 0) mLruProcesses.remove(lrui);
2518
2519 int i = mLruProcesses.size()-1;
2520 int skipTop = 0;
2521
Dianne Hackborn906497c2010-05-10 15:57:38 -07002522 app.lruSeq = mLruSeq;
2523
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002524 // compute the new weight for this process.
2525 if (updateActivityTime) {
2526 app.lastActivityTime = SystemClock.uptimeMillis();
2527 }
2528 if (app.activities.size() > 0) {
2529 // If this process has activities, we more strongly want to keep
2530 // it around.
2531 app.lruWeight = app.lastActivityTime;
2532 } else if (app.pubProviders.size() > 0) {
2533 // If this process contains content providers, we want to keep
2534 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002535 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002536 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002537 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002538 } else {
2539 // If this process doesn't have activities, we less strongly
2540 // want to keep it around, and generally want to avoid getting
2541 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002542 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002543 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002544 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002545 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07002546
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002547 while (i >= 0) {
2548 ProcessRecord p = mLruProcesses.get(i);
2549 // If this app shouldn't be in front of the first N background
2550 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002551 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002552 skipTop--;
2553 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07002554 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002555 mLruProcesses.add(i+1, app);
2556 break;
2557 }
2558 i--;
2559 }
2560 if (i < 0) {
2561 mLruProcesses.add(0, app);
2562 }
2563
Dianne Hackborn906497c2010-05-10 15:57:38 -07002564 // If the app is currently using a content provider or service,
2565 // bump those processes as well.
2566 if (app.connections.size() > 0) {
2567 for (ConnectionRecord cr : app.connections) {
2568 if (cr.binding != null && cr.binding.service != null
2569 && cr.binding.service.app != null
2570 && cr.binding.service.app.lruSeq != mLruSeq) {
2571 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
2572 updateActivityTime, i+1);
2573 }
2574 }
2575 }
2576 if (app.conProviders.size() > 0) {
2577 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07002578 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
2579 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07002580 updateActivityTime, i+1);
2581 }
2582 }
2583 }
2584
Joe Onorato8a9b2202010-02-26 18:56:32 -08002585 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 if (oomAdj) {
2587 updateOomAdjLocked();
2588 }
2589 }
2590
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002591 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07002592 boolean oomAdj, boolean updateActivityTime) {
2593 mLruSeq++;
2594 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
2595 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002596
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002597 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 String processName, int uid) {
2599 if (uid == Process.SYSTEM_UID) {
2600 // The system gets to run in any process. If there are multiple
2601 // processes with the same uid, just pick the first (this
2602 // should never happen).
2603 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
2604 processName);
2605 return procs != null ? procs.valueAt(0) : null;
2606 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002607 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 ProcessRecord proc = mProcessNames.get(processName, uid);
2609 return proc;
2610 }
2611
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002612 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002613 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002614 try {
2615 if (pm.performDexOpt(packageName)) {
2616 mDidDexOpt = true;
2617 }
2618 } catch (RemoteException e) {
2619 }
2620 }
2621
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002622 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 int transit = mWindowManager.getPendingAppTransition();
2624 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
2625 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
2626 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
2627 }
2628
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002629 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002631 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
2632 boolean isolated) {
2633 ProcessRecord app;
2634 if (!isolated) {
2635 app = getProcessRecordLocked(processName, info.uid);
2636 } else {
2637 // If this is an isolated process, it can't re-use an existing process.
2638 app = null;
2639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 // We don't have to do anything more if:
2641 // (1) There is an existing application record; and
2642 // (2) The caller doesn't think it is dead, OR there is no thread
2643 // object attached to it so we know it couldn't have crashed; and
2644 // (3) There is a pid assigned to it, so it is either starting or
2645 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002646 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 + " app=" + app + " knownToBeDead=" + knownToBeDead
2648 + " thread=" + (app != null ? app.thread : null)
2649 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01002650 if (app != null && app.pid > 0) {
2651 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002652 // We already have the app running, or are waiting for it to
2653 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002654 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002655 // If this is a new package in the process, add the package to the list
2656 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002657 return app;
2658 } else {
2659 // An application record is attached to a previous process,
2660 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002661 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002662 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 String hostingNameStr = hostingName != null
2667 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002668
2669 if (!isolated) {
2670 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2671 // If we are in the background, then check to see if this process
2672 // is bad. If so, we will just silently fail.
2673 if (mBadProcesses.get(info.processName, info.uid) != null) {
2674 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2675 + "/" + info.processName);
2676 return null;
2677 }
2678 } else {
2679 // When the user is explicitly starting a process, then clear its
2680 // crash count so that we won't make it bad until they see at
2681 // least one crash dialog again, and make the process good again
2682 // if it had been bad.
2683 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002684 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002685 mProcessCrashTimes.remove(info.processName, info.uid);
2686 if (mBadProcesses.get(info.processName, info.uid) != null) {
2687 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
2688 info.processName);
2689 mBadProcesses.remove(info.processName, info.uid);
2690 if (app != null) {
2691 app.bad = false;
2692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 }
2694 }
2695 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002698 app = newProcessRecordLocked(null, info, processName, isolated);
2699 if (app == null) {
2700 Slog.w(TAG, "Failed making new process record for "
2701 + processName + "/" + info.uid + " isolated=" + isolated);
2702 return null;
2703 }
2704 mProcessNames.put(processName, app.uid, app);
2705 if (isolated) {
2706 mIsolatedProcesses.put(app.uid, app);
2707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 } else {
2709 // If this is a new package in the process, add the package to the list
2710 app.addPackage(info.packageName);
2711 }
2712
2713 // If the system is not ready yet, then hold off on starting this
2714 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002715 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002716 && !isAllowedWhileBooting(info)
2717 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 if (!mProcessesOnHold.contains(app)) {
2719 mProcessesOnHold.add(app);
2720 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002721 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 return app;
2723 }
2724
2725 startProcessLocked(app, hostingType, hostingNameStr);
2726 return (app.pid != 0) ? app : null;
2727 }
2728
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002729 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2730 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2731 }
2732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 private final void startProcessLocked(ProcessRecord app,
2734 String hostingType, String hostingNameStr) {
2735 if (app.pid > 0 && app.pid != MY_PID) {
2736 synchronized (mPidsSelfLocked) {
2737 mPidsSelfLocked.remove(app.pid);
2738 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2739 }
2740 app.pid = 0;
2741 }
2742
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002743 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2744 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 mProcessesOnHold.remove(app);
2746
2747 updateCpuStats();
2748
2749 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2750 mProcDeaths[0] = 0;
2751
2752 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002753 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002756 if (!app.isolated) {
2757 try {
2758 gids = mContext.getPackageManager().getPackageGids(
2759 app.info.packageName);
2760 } catch (PackageManager.NameNotFoundException e) {
2761 Slog.w(TAG, "Unable to retrieve gids", e);
2762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 }
2764 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2765 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2766 && mTopComponent != null
2767 && app.processName.equals(mTopComponent.getPackageName())) {
2768 uid = 0;
2769 }
2770 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2771 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2772 uid = 0;
2773 }
2774 }
2775 int debugFlags = 0;
2776 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2777 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002778 // Also turn on CheckJNI for debuggable apps. It's quite
2779 // awkward to turn on otherwise.
2780 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002782 // Run the app in safe mode if its manifest requests so or the
2783 // system is booted in safe mode.
2784 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2785 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002786 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2789 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2790 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002791 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2792 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 if ("1".equals(SystemProperties.get("debug.assert"))) {
2795 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2796 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002797
2798 // Start the process. It will either succeed and return a result containing
2799 // the PID of the new process, or else throw a RuntimeException.
2800 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002801 app.processName, uid, uid, gids, debugFlags,
2802 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2805 synchronized (bs) {
2806 if (bs.isOnBattery()) {
2807 app.batteryStats.incStartsLocked();
2808 }
2809 }
2810
Jeff Brown3f9dd282011-07-08 20:02:19 -07002811 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 app.processName, hostingType,
2813 hostingNameStr != null ? hostingNameStr : "");
2814
2815 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002816 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 }
2818
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002819 StringBuilder buf = mStringBuilder;
2820 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 buf.append("Start proc ");
2822 buf.append(app.processName);
2823 buf.append(" for ");
2824 buf.append(hostingType);
2825 if (hostingNameStr != null) {
2826 buf.append(" ");
2827 buf.append(hostingNameStr);
2828 }
2829 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002830 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 buf.append(" uid=");
2832 buf.append(uid);
2833 buf.append(" gids={");
2834 if (gids != null) {
2835 for (int gi=0; gi<gids.length; gi++) {
2836 if (gi != 0) buf.append(", ");
2837 buf.append(gids[gi]);
2838
2839 }
2840 }
2841 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002842 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002843 app.pid = startResult.pid;
2844 app.usingWrapper = startResult.usingWrapper;
2845 app.removed = false;
2846 synchronized (mPidsSelfLocked) {
2847 this.mPidsSelfLocked.put(startResult.pid, app);
2848 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2849 msg.obj = app;
2850 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2851 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 }
2853 } catch (RuntimeException e) {
2854 // XXX do better error recovery.
2855 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002856 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 }
2858 }
2859
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002860 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 if (resumed) {
2862 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2863 } else {
2864 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2865 }
2866 }
2867
Amith Yamasani742a6712011-05-04 14:49:28 -07002868 boolean startHomeActivityLocked(int userId) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002869 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2870 && mTopAction == null) {
2871 // We are running in factory test mode, but unable to find
2872 // the factory test app, so just sit around displaying the
2873 // error message and don't try to start anything.
2874 return false;
2875 }
2876 Intent intent = new Intent(
2877 mTopAction,
2878 mTopData != null ? Uri.parse(mTopData) : null);
2879 intent.setComponent(mTopComponent);
2880 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2881 intent.addCategory(Intent.CATEGORY_HOME);
2882 }
2883 ActivityInfo aInfo =
2884 intent.resolveActivityInfo(mContext.getPackageManager(),
2885 STOCK_PM_FLAGS);
2886 if (aInfo != null) {
2887 intent.setComponent(new ComponentName(
2888 aInfo.applicationInfo.packageName, aInfo.name));
2889 // Don't do this if the home app is currently being
2890 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002891 aInfo = new ActivityInfo(aInfo);
2892 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002893 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2894 aInfo.applicationInfo.uid);
2895 if (app == null || app.instrumentationClass == null) {
2896 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002897 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002898 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002899 }
2900 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002901
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002902 return true;
2903 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002904
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002905 /**
2906 * Starts the "new version setup screen" if appropriate.
2907 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002908 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002909 // Only do this once per boot.
2910 if (mCheckedForSetup) {
2911 return;
2912 }
2913
2914 // We will show this screen if the current one is a different
2915 // version than the last one shown, and we are not running in
2916 // low-level factory test mode.
2917 final ContentResolver resolver = mContext.getContentResolver();
2918 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2919 Settings.Secure.getInt(resolver,
2920 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2921 mCheckedForSetup = true;
2922
2923 // See if we should be showing the platform update setup UI.
2924 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2925 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2926 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2927
2928 // We don't allow third party apps to replace this.
2929 ResolveInfo ri = null;
2930 for (int i=0; ris != null && i<ris.size(); i++) {
2931 if ((ris.get(i).activityInfo.applicationInfo.flags
2932 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2933 ri = ris.get(i);
2934 break;
2935 }
2936 }
2937
2938 if (ri != null) {
2939 String vers = ri.activityInfo.metaData != null
2940 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2941 : null;
2942 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2943 vers = ri.activityInfo.applicationInfo.metaData.getString(
2944 Intent.METADATA_SETUP_VERSION);
2945 }
2946 String lastVers = Settings.Secure.getString(
2947 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2948 if (vers != null && !vers.equals(lastVers)) {
2949 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2950 intent.setComponent(new ComponentName(
2951 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002952 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002953 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002954 }
2955 }
2956 }
2957 }
2958
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002959 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002960 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002961 }
2962
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002963 void enforceNotIsolatedCaller(String caller) {
2964 if (UserId.isIsolated(Binder.getCallingUid())) {
2965 throw new SecurityException("Isolated process not allowed to call " + caller);
2966 }
2967 }
2968
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002969 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002970 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002971 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002972 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2973 }
2974 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002975
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002976 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002977 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2978 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002979 synchronized (this) {
2980 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2981 }
2982 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002983
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002984 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002985 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002986 synchronized (this) {
2987 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2988 }
2989 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002990
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002991 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002992 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2993 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002994 synchronized (this) {
2995 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002996 }
2997 }
2998
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002999 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003000 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07003001 synchronized (this) {
3002 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
3003 }
3004 }
3005
3006 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003007 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3008 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07003009 synchronized (this) {
3010 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
3011 }
3012 }
3013
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003014 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003015 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003016
3017 final int identHash = System.identityHashCode(r);
3018 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020
Jeff Sharkeya4620792011-05-20 15:29:23 -07003021 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
3022 int i = mProcessObservers.beginBroadcast();
3023 while (i > 0) {
3024 i--;
3025 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3026 if (observer != null) {
3027 try {
3028 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
3029 } catch (RemoteException e) {
3030 }
3031 }
3032 }
3033 mProcessObservers.finishBroadcast();
3034 }
3035
3036 private void dispatchProcessDied(int pid, int uid) {
3037 int i = mProcessObservers.beginBroadcast();
3038 while (i > 0) {
3039 i--;
3040 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3041 if (observer != null) {
3042 try {
3043 observer.onProcessDied(pid, uid);
3044 } catch (RemoteException e) {
3045 }
3046 }
3047 }
3048 mProcessObservers.finishBroadcast();
3049 }
3050
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003051 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003052 final int N = mPendingActivityLaunches.size();
3053 if (N <= 0) {
3054 return;
3055 }
3056 for (int i=0; i<N; i++) {
3057 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003058 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003059 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
3060 doResume && i == (N-1));
3061 }
3062 mPendingActivityLaunches.clear();
3063 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003064
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003065 public final int startActivity(IApplicationThread caller,
3066 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3067 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003068 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
3069 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003070 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07003071 int userId = 0;
3072 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
3073 // Requesting home, set the identity to the current user
3074 // HACK!
3075 userId = mCurrentUserId;
3076 } else {
3077 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
3078 // the current user's userId
3079 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
3080 userId = 0;
3081 } else {
3082 userId = Binder.getOrigCallingUser();
3083 }
3084 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003085 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -07003086 grantedUriPermissions, grantedMode, resultTo, resultWho, requestCode, onlyIfNeeded,
3087 debug, profileFile, profileFd, autoStopProfiler, null, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003088 }
3089
3090 public final WaitResult startActivityAndWait(IApplicationThread caller,
3091 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3092 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003093 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
3094 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003095 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003096 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07003097 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003098 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003099 grantedUriPermissions, grantedMode, resultTo, resultWho,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003100 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
Amith Yamasani742a6712011-05-04 14:49:28 -07003101 res, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003102 return res;
3103 }
3104
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003105 public final int startActivityWithConfig(IApplicationThread caller,
3106 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3107 int grantedMode, IBinder resultTo,
3108 String resultWho, int requestCode, boolean onlyIfNeeded,
3109 boolean debug, Configuration config) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003110 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07003111 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003112 grantedUriPermissions, grantedMode, resultTo, resultWho,
Amith Yamasani742a6712011-05-04 14:49:28 -07003113 requestCode, onlyIfNeeded,
3114 debug, null, null, false, null, config, Binder.getOrigCallingUser());
3115 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003116 }
3117
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003118 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003119 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003120 IBinder resultTo, String resultWho, int requestCode,
3121 int flagsMask, int flagsValues) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003122 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003123 // Refuse possible leaked file descriptors
3124 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
3125 throw new IllegalArgumentException("File descriptors passed in Intent");
3126 }
3127
3128 IIntentSender sender = intent.getTarget();
3129 if (!(sender instanceof PendingIntentRecord)) {
3130 throw new IllegalArgumentException("Bad PendingIntent object");
3131 }
3132
3133 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003134
3135 synchronized (this) {
3136 // If this is coming from the currently resumed activity, it is
3137 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003138 if (mMainStack.mResumedActivity != null
3139 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003140 Binder.getCallingUid()) {
3141 mAppSwitchesAllowedTime = 0;
3142 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003143 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003144 int ret = pir.sendInner(0, fillInIntent, resolvedType, null,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003145 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
Amith Yamasani742a6712011-05-04 14:49:28 -07003146 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003147 }
3148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 public boolean startNextMatchingActivity(IBinder callingActivity,
3150 Intent intent) {
3151 // Refuse possible leaked file descriptors
3152 if (intent != null && intent.hasFileDescriptors() == true) {
3153 throw new IllegalArgumentException("File descriptors passed in Intent");
3154 }
3155
3156 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003157 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
3158 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 return false;
3160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 if (r.app == null || r.app.thread == null) {
3162 // The caller is not running... d'oh!
3163 return false;
3164 }
3165 intent = new Intent(intent);
3166 // The caller is not allowed to change the data.
3167 intent.setDataAndType(r.intent.getData(), r.intent.getType());
3168 // And we are resetting to find the next component...
3169 intent.setComponent(null);
3170
3171 ActivityInfo aInfo = null;
3172 try {
3173 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003174 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07003176 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177
3178 // Look for the original activity in the list...
3179 final int N = resolves != null ? resolves.size() : 0;
3180 for (int i=0; i<N; i++) {
3181 ResolveInfo rInfo = resolves.get(i);
3182 if (rInfo.activityInfo.packageName.equals(r.packageName)
3183 && rInfo.activityInfo.name.equals(r.info.name)) {
3184 // We found the current one... the next matching is
3185 // after it.
3186 i++;
3187 if (i<N) {
3188 aInfo = resolves.get(i).activityInfo;
3189 }
3190 break;
3191 }
3192 }
3193 } catch (RemoteException e) {
3194 }
3195
3196 if (aInfo == null) {
3197 // Nobody who is next!
3198 return false;
3199 }
3200
3201 intent.setComponent(new ComponentName(
3202 aInfo.applicationInfo.packageName, aInfo.name));
3203 intent.setFlags(intent.getFlags()&~(
3204 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
3205 Intent.FLAG_ACTIVITY_CLEAR_TOP|
3206 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
3207 Intent.FLAG_ACTIVITY_NEW_TASK));
3208
3209 // Okay now we need to start the new activity, replacing the
3210 // currently running activity. This is a little tricky because
3211 // we want to start the new one as if the current one is finished,
3212 // but not finish the current one first so that there is no flicker.
3213 // And thus...
3214 final boolean wasFinishing = r.finishing;
3215 r.finishing = true;
3216
3217 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003218 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 final String resultWho = r.resultWho;
3220 final int requestCode = r.requestCode;
3221 r.resultTo = null;
3222 if (resultTo != null) {
3223 resultTo.removeResultsLocked(r, resultWho, requestCode);
3224 }
3225
3226 final long origId = Binder.clearCallingIdentity();
3227 // XXX we are not dealing with propagating grantedUriPermissions...
3228 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003229 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackbornbe707852011-11-11 14:32:10 -08003230 r.resolvedType, null, 0, aInfo,
3231 resultTo != null ? resultTo.appToken : null, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003232 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 Binder.restoreCallingIdentity(origId);
3234
3235 r.finishing = wasFinishing;
3236 if (res != START_SUCCESS) {
3237 return false;
3238 }
3239 return true;
3240 }
3241 }
3242
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003243 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 Intent intent, String resolvedType, IBinder resultTo,
3245 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003246
3247 // This is so super not safe, that only the system (or okay root)
3248 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07003249 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003250 final int callingUid = Binder.getCallingUid();
3251 if (callingUid != 0 && callingUid != Process.myUid()) {
3252 throw new SecurityException(
3253 "startActivityInPackage only available to the system");
3254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255
Amith Yamasani742a6712011-05-04 14:49:28 -07003256 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003257 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false,
Amith Yamasani742a6712011-05-04 14:49:28 -07003258 null, null, false, null, null, userId);
3259 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003260 }
3261
3262 public final int startActivities(IApplicationThread caller,
3263 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003264 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07003265 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
3266 Binder.getOrigCallingUser());
3267 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003268 }
3269
3270 public final int startActivitiesInPackage(int uid,
3271 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
3272
3273 // This is so super not safe, that only the system (or okay root)
3274 // can do it.
3275 final int callingUid = Binder.getCallingUid();
3276 if (callingUid != 0 && callingUid != Process.myUid()) {
3277 throw new SecurityException(
3278 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003280 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
3281 UserId.getUserId(uid));
3282 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 }
3284
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003285 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08003287 // Quick case: check if the top-most recent task is the same.
3288 if (N > 0 && mRecentTasks.get(0) == task) {
3289 return;
3290 }
3291 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 for (int i=0; i<N; i++) {
3293 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07003294 if (task.userId == tr.userId
3295 && ((task.affinity != null && task.affinity.equals(tr.affinity))
3296 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 mRecentTasks.remove(i);
3298 i--;
3299 N--;
3300 if (task.intent == null) {
3301 // If the new recent task we are adding is not fully
3302 // specified, then replace it with the existing recent task.
3303 task = tr;
3304 }
3305 }
3306 }
3307 if (N >= MAX_RECENT_TASKS) {
3308 mRecentTasks.remove(N-1);
3309 }
3310 mRecentTasks.add(0, task);
3311 }
3312
3313 public void setRequestedOrientation(IBinder token,
3314 int requestedOrientation) {
3315 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003316 ActivityRecord r = mMainStack.isInStackLocked(token);
3317 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 return;
3319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08003321 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07003323 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08003324 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 if (config != null) {
3326 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08003327 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003328 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 }
3330 }
3331 Binder.restoreCallingIdentity(origId);
3332 }
3333 }
3334
3335 public int getRequestedOrientation(IBinder token) {
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 ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3340 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003341 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 }
3343 }
3344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 /**
3346 * This is the internal entry point for handling Activity.finish().
3347 *
3348 * @param token The Binder token referencing the Activity we want to finish.
3349 * @param resultCode Result code, if any, from this Activity.
3350 * @param resultData Result data (Intent), if any, from this Activity.
3351 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11003352 * @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 -08003353 */
3354 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
3355 // Refuse possible leaked file descriptors
3356 if (resultData != null && resultData.hasFileDescriptors() == true) {
3357 throw new IllegalArgumentException("File descriptors passed in Intent");
3358 }
3359
3360 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003361 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003362 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003363 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 if (next != null) {
3365 // ask watcher if this is allowed
3366 boolean resumeOK = true;
3367 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003368 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003370 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 }
3372
3373 if (!resumeOK) {
3374 return false;
3375 }
3376 }
3377 }
3378 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003379 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 resultData, "app-request");
3381 Binder.restoreCallingIdentity(origId);
3382 return res;
3383 }
3384 }
3385
Dianne Hackborn860755f2010-06-03 18:47:52 -07003386 public final void finishHeavyWeightApp() {
3387 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3388 != PackageManager.PERMISSION_GRANTED) {
3389 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
3390 + Binder.getCallingPid()
3391 + ", uid=" + Binder.getCallingUid()
3392 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3393 Slog.w(TAG, msg);
3394 throw new SecurityException(msg);
3395 }
3396
3397 synchronized(this) {
3398 if (mHeavyWeightProcess == null) {
3399 return;
3400 }
3401
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003402 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07003403 mHeavyWeightProcess.activities);
3404 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003405 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003406 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003407 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003408 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003409 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07003410 null, "finish-heavy");
3411 }
3412 }
3413 }
3414
3415 mHeavyWeightProcess = null;
3416 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3417 }
3418 }
3419
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003420 public void crashApplication(int uid, int initialPid, String packageName,
3421 String message) {
3422 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3423 != PackageManager.PERMISSION_GRANTED) {
3424 String msg = "Permission Denial: crashApplication() from pid="
3425 + Binder.getCallingPid()
3426 + ", uid=" + Binder.getCallingUid()
3427 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3428 Slog.w(TAG, msg);
3429 throw new SecurityException(msg);
3430 }
3431
3432 synchronized(this) {
3433 ProcessRecord proc = null;
3434
3435 // Figure out which process to kill. We don't trust that initialPid
3436 // still has any relation to current pids, so must scan through the
3437 // list.
3438 synchronized (mPidsSelfLocked) {
3439 for (int i=0; i<mPidsSelfLocked.size(); i++) {
3440 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003441 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003442 continue;
3443 }
3444 if (p.pid == initialPid) {
3445 proc = p;
3446 break;
3447 }
3448 for (String str : p.pkgList) {
3449 if (str.equals(packageName)) {
3450 proc = p;
3451 }
3452 }
3453 }
3454 }
3455
3456 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07003457 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003458 + " initialPid=" + initialPid
3459 + " packageName=" + packageName);
3460 return;
3461 }
3462
3463 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07003464 if (proc.pid == Process.myPid()) {
3465 Log.w(TAG, "crashApplication: trying to crash self!");
3466 return;
3467 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003468 long ident = Binder.clearCallingIdentity();
3469 try {
3470 proc.thread.scheduleCrash(message);
3471 } catch (RemoteException e) {
3472 }
3473 Binder.restoreCallingIdentity(ident);
3474 }
3475 }
3476 }
3477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 public final void finishSubActivity(IBinder token, String resultWho,
3479 int requestCode) {
3480 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003481 ActivityRecord self = mMainStack.isInStackLocked(token);
3482 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 return;
3484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485
3486 final long origId = Binder.clearCallingIdentity();
3487
3488 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003489 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3490 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 if (r.resultTo == self && r.requestCode == requestCode) {
3492 if ((r.resultWho == null && resultWho == null) ||
3493 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003494 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 Activity.RESULT_CANCELED, null, "request-sub");
3496 }
3497 }
3498 }
3499
3500 Binder.restoreCallingIdentity(origId);
3501 }
3502 }
3503
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003504 public boolean willActivityBeVisible(IBinder token) {
3505 synchronized(this) {
3506 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003507 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3508 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003509 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003510 return true;
3511 }
3512 if (r.fullscreen && !r.finishing) {
3513 return false;
3514 }
3515 }
3516 return true;
3517 }
3518 }
3519
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003520 public void overridePendingTransition(IBinder token, String packageName,
3521 int enterAnim, int exitAnim) {
3522 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003523 ActivityRecord self = mMainStack.isInStackLocked(token);
3524 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003525 return;
3526 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003527
3528 final long origId = Binder.clearCallingIdentity();
3529
3530 if (self.state == ActivityState.RESUMED
3531 || self.state == ActivityState.PAUSING) {
3532 mWindowManager.overridePendingAppTransition(packageName,
3533 enterAnim, exitAnim);
3534 }
3535
3536 Binder.restoreCallingIdentity(origId);
3537 }
3538 }
3539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 * Main function for removing an existing process from the activity manager
3542 * as a result of that process going away. Clears out all connections
3543 * to the process.
3544 */
3545 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003546 boolean restarting, boolean allowRestart) {
3547 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003549 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 }
3551
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003552 if (mProfileProc == app) {
3553 clearProfilerLocked();
3554 }
3555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 // Just in case...
Dianne Hackborncbb722e2012-02-07 18:33:49 -08003557 mMainStack.appDiedLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558
3559 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003560 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561
3562 boolean atTop = true;
3563 boolean hasVisibleActivities = false;
3564
3565 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003566 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003567 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 TAG, "Removing app " + app + " from history with " + i + " entries");
3569 while (i > 0) {
3570 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003571 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003572 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3574 if (r.app == app) {
3575 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003576 if (ActivityStack.DEBUG_ADD_REMOVE) {
3577 RuntimeException here = new RuntimeException("here");
3578 here.fillInStackTrace();
3579 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
3580 + ": haveState=" + r.haveState
3581 + " stateNotNeeded=" + r.stateNotNeeded
3582 + " finishing=" + r.finishing
3583 + " state=" + r.state, here);
3584 }
3585 if (!r.finishing) {
3586 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08003587 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3588 System.identityHashCode(r),
3589 r.task.taskId, r.shortComponentName,
3590 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003591 }
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003592 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003593 mMainStack.mHistory.remove(i);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003594 r.takeFromHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08003595 mWindowManager.removeAppToken(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003597 mMainStack.validateAppTokensLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003598 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003599 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600
3601 } else {
3602 // We have the current state for this activity, so
3603 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003604 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003605 TAG, "Keeping entry, setting app to null");
3606 if (r.visible) {
3607 hasVisibleActivities = true;
3608 }
3609 r.app = null;
3610 r.nowVisible = false;
3611 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003612 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
3613 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003614 r.icicle = null;
3615 }
3616 }
3617
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003618 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003619 }
3620 atTop = false;
3621 }
3622
3623 app.activities.clear();
3624
3625 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003626 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627 + " running instrumentation " + app.instrumentationClass);
3628 Bundle info = new Bundle();
3629 info.putString("shortMsg", "Process crashed.");
3630 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3631 }
3632
3633 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003634 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 // If there was nothing to resume, and we are not already
3636 // restarting this process, but there is a visible activity that
3637 // is hosted by the process... then make sure all visible
3638 // activities are running, taking care of restarting this
3639 // process.
3640 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003641 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 }
3643 }
3644 }
3645 }
3646
3647 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3648 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003650 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3651 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3653 return i;
3654 }
3655 }
3656 return -1;
3657 }
3658
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003659 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 IApplicationThread thread) {
3661 if (thread == null) {
3662 return null;
3663 }
3664
3665 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003666 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 }
3668
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003669 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 IApplicationThread thread) {
3671
3672 mProcDeaths[0]++;
3673
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003674 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3675 synchronized (stats) {
3676 stats.noteProcessDiedLocked(app.info.uid, pid);
3677 }
3678
Magnus Edlund7bb25812010-02-24 15:45:06 +01003679 // Clean up already done if the process has been re-started.
3680 if (app.pid == pid && app.thread != null &&
3681 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003682 if (!app.killedBackground) {
3683 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3684 + ") has died.");
3685 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08003686 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003687 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 TAG, "Dying app: " + app + ", pid: " + pid
3689 + ", thread: " + thread.asBinder());
3690 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003691 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692
3693 if (doLowMem) {
3694 // If there are no longer any background processes running,
3695 // and the app that died was not running instrumentation,
3696 // then tell everyone we are now low on memory.
3697 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003698 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3699 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003700 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 haveBg = true;
3702 break;
3703 }
3704 }
3705
3706 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003707 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003708 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003709 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3710 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003711 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003712 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3713 // The low memory report is overriding any current
3714 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003715 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003716 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003717 rec.lastRequestedGc = 0;
3718 } else {
3719 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003721 rec.reportLowMemory = true;
3722 rec.lastLowMemory = now;
3723 mProcessesToGc.remove(rec);
3724 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003725 }
3726 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003727 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003728 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 }
3730 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003731 } else if (app.pid != pid) {
3732 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003733 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003734 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003735 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003736 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003737 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 + thread.asBinder());
3739 }
3740 }
3741
Dan Egnor42471dd2010-01-07 17:25:22 -08003742 /**
3743 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003744 * @param clearTraces causes the dump file to be erased prior to the new
3745 * traces being written, if true; when false, the new traces will be
3746 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003747 * @param firstPids of dalvik VM processes to dump stack traces for first
3748 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08003749 * @return file containing stack traces, or null if no dump file is configured
3750 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003751 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
3752 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003753 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3754 if (tracesPath == null || tracesPath.length() == 0) {
3755 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003757
3758 File tracesFile = new File(tracesPath);
3759 try {
3760 File tracesDir = tracesFile.getParentFile();
3761 if (!tracesDir.exists()) tracesFile.mkdirs();
3762 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3763
Christopher Tate6ee412d2010-05-28 12:01:56 -07003764 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003765 tracesFile.createNewFile();
3766 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3767 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003768 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003769 return null;
3770 }
3771
3772 // Use a FileObserver to detect when traces finish writing.
3773 // The order of traces is considered important to maintain for legibility.
3774 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3775 public synchronized void onEvent(int event, String path) { notify(); }
3776 };
3777
3778 try {
3779 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003780
3781 // First collect all of the stacks of the most important pids.
3782 try {
3783 int num = firstPids.size();
3784 for (int i = 0; i < num; i++) {
3785 synchronized (observer) {
3786 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3787 observer.wait(200); // Wait for write-close, give up after 200msec
3788 }
3789 }
3790 } catch (InterruptedException e) {
3791 Log.wtf(TAG, e);
3792 }
3793
3794 // Next measure CPU usage.
3795 if (processStats != null) {
3796 processStats.init();
3797 System.gc();
3798 processStats.update();
3799 try {
3800 synchronized (processStats) {
3801 processStats.wait(500); // measure over 1/2 second.
3802 }
3803 } catch (InterruptedException e) {
3804 }
3805 processStats.update();
3806
3807 // We'll take the stack crawls of just the top apps using CPU.
3808 final int N = processStats.countWorkingStats();
3809 int numProcs = 0;
3810 for (int i=0; i<N && numProcs<5; i++) {
3811 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3812 if (lastPids.indexOfKey(stats.pid) >= 0) {
3813 numProcs++;
3814 try {
3815 synchronized (observer) {
3816 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3817 observer.wait(200); // Wait for write-close, give up after 200msec
3818 }
3819 } catch (InterruptedException e) {
3820 Log.wtf(TAG, e);
3821 }
3822
3823 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003824 }
3825 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003826
3827 return tracesFile;
3828
Dan Egnor42471dd2010-01-07 17:25:22 -08003829 } finally {
3830 observer.stopWatching();
3831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 }
3833
Jeff Brown4d94a762010-09-23 11:33:28 -07003834 private final class AppNotResponding implements Runnable {
3835 private final ProcessRecord mApp;
3836 private final String mAnnotation;
3837
3838 public AppNotResponding(ProcessRecord app, String annotation) {
3839 mApp = app;
3840 mAnnotation = annotation;
3841 }
3842
3843 @Override
3844 public void run() {
3845 appNotResponding(mApp, null, null, mAnnotation);
3846 }
3847 }
3848
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003849 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3850 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003851 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3852 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3853
Dianne Hackborn287952c2010-09-22 22:34:31 -07003854 if (mController != null) {
3855 try {
3856 // 0 == continue, -1 = kill process immediately
3857 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3858 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3859 } catch (RemoteException e) {
3860 mController = null;
3861 }
3862 }
3863
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003864 long anrTime = SystemClock.uptimeMillis();
3865 if (MONITOR_CPU_USAGE) {
3866 updateCpuStatsNow();
3867 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003868
3869 synchronized (this) {
3870 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3871 if (mShuttingDown) {
3872 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3873 return;
3874 } else if (app.notResponding) {
3875 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3876 return;
3877 } else if (app.crashing) {
3878 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3879 return;
3880 }
3881
3882 // In case we come through here for the same app before completing
3883 // this one, mark as anring now so we will bail out.
3884 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003885
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003886 // Log the ANR to the event log.
3887 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3888 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003889
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003890 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003891 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003892
3893 int parentPid = app.pid;
3894 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003895 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003896
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003897 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003898
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003899 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3900 ProcessRecord r = mLruProcesses.get(i);
3901 if (r != null && r.thread != null) {
3902 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003903 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3904 if (r.persistent) {
3905 firstPids.add(pid);
3906 } else {
3907 lastPids.put(pid, Boolean.TRUE);
3908 }
3909 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 }
3912 }
3913
Dan Egnor42471dd2010-01-07 17:25:22 -08003914 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003915 StringBuilder info = mStringBuilder;
3916 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003917 info.append("ANR in ").append(app.processName);
3918 if (activity != null && activity.shortComponentName != null) {
3919 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003920 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003921 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003923 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003925 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003926 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928
Dianne Hackborn287952c2010-09-22 22:34:31 -07003929 final ProcessStats processStats = new ProcessStats(true);
3930
3931 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3932
Dan Egnor42471dd2010-01-07 17:25:22 -08003933 String cpuInfo = null;
3934 if (MONITOR_CPU_USAGE) {
3935 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003936 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003937 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003938 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003939 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003940 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 }
3942
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003943 info.append(processStats.printCurrentState(anrTime));
3944
Joe Onorato8a9b2202010-02-26 18:56:32 -08003945 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003946 if (tracesFile == null) {
3947 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3948 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3949 }
3950
Jeff Sharkeya353d262011-10-28 11:12:06 -07003951 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3952 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003953
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003954 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003956 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3957 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003959 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3960 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 }
3962 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003963 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 }
3965 }
3966
Dan Egnor42471dd2010-01-07 17:25:22 -08003967 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3968 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3969 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003970
3971 synchronized (this) {
3972 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003973 Slog.w(TAG, "Killing " + app + ": background ANR");
3974 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3975 app.processName, app.setAdj, "background ANR");
3976 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003977 return;
3978 }
3979
3980 // Set the app's notResponding state, and look up the errorReportReceiver
3981 makeAppNotRespondingLocked(app,
3982 activity != null ? activity.shortComponentName : null,
3983 annotation != null ? "ANR " + annotation : "ANR",
3984 info.toString());
3985
3986 // Bring up the infamous App Not Responding dialog
3987 Message msg = Message.obtain();
3988 HashMap map = new HashMap();
3989 msg.what = SHOW_NOT_RESPONDING_MSG;
3990 msg.obj = map;
3991 map.put("app", app);
3992 if (activity != null) {
3993 map.put("activity", activity);
3994 }
3995
3996 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 }
3999
Dianne Hackborn0dad3642010-09-09 21:25:35 -07004000 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
4001 if (!mLaunchWarningShown) {
4002 mLaunchWarningShown = true;
4003 mHandler.post(new Runnable() {
4004 @Override
4005 public void run() {
4006 synchronized (ActivityManagerService.this) {
4007 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
4008 d.show();
4009 mHandler.postDelayed(new Runnable() {
4010 @Override
4011 public void run() {
4012 synchronized (ActivityManagerService.this) {
4013 d.dismiss();
4014 mLaunchWarningShown = false;
4015 }
4016 }
4017 }, 4000);
4018 }
4019 }
4020 });
4021 }
4022 }
4023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07004025 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004026 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 int uid = Binder.getCallingUid();
4028 int pid = Binder.getCallingPid();
4029 long callingId = Binder.clearCallingIdentity();
4030 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004031 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 int pkgUid = -1;
4033 synchronized(this) {
4034 try {
4035 pkgUid = pm.getPackageUid(packageName);
4036 } catch (RemoteException e) {
4037 }
4038 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004039 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 return false;
4041 }
4042 if (uid == pkgUid || checkComponentPermission(
4043 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004044 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08004046 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 } else {
4048 throw new SecurityException(pid+" does not have permission:"+
4049 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
4050 "for process:"+packageName);
4051 }
4052 }
4053
4054 try {
4055 //clear application user data
4056 pm.clearApplicationUserData(packageName, observer);
4057 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
4058 Uri.fromParts("package", packageName, null));
4059 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004060 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07004061 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062 } catch (RemoteException e) {
4063 }
4064 } finally {
4065 Binder.restoreCallingIdentity(callingId);
4066 }
4067 return true;
4068 }
4069
Dianne Hackborn03abb812010-01-04 18:43:19 -08004070 public void killBackgroundProcesses(final String packageName) {
4071 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4072 != PackageManager.PERMISSION_GRANTED &&
4073 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
4074 != PackageManager.PERMISSION_GRANTED) {
4075 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004076 + Binder.getCallingPid()
4077 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08004078 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004079 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 throw new SecurityException(msg);
4081 }
4082
4083 long callingId = Binder.clearCallingIdentity();
4084 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004085 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 int pkgUid = -1;
4087 synchronized(this) {
4088 try {
4089 pkgUid = pm.getPackageUid(packageName);
4090 } catch (RemoteException e) {
4091 }
4092 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004093 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004094 return;
4095 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004096 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004097 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
4098 }
4099 } finally {
4100 Binder.restoreCallingIdentity(callingId);
4101 }
4102 }
4103
4104 public void killAllBackgroundProcesses() {
4105 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4106 != PackageManager.PERMISSION_GRANTED) {
4107 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
4108 + Binder.getCallingPid()
4109 + ", uid=" + Binder.getCallingUid()
4110 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4111 Slog.w(TAG, msg);
4112 throw new SecurityException(msg);
4113 }
4114
4115 long callingId = Binder.clearCallingIdentity();
4116 try {
4117 synchronized(this) {
4118 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
4119 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
4120 final int NA = apps.size();
4121 for (int ia=0; ia<NA; ia++) {
4122 ProcessRecord app = apps.valueAt(ia);
4123 if (app.persistent) {
4124 // we don't kill persistent processes
4125 continue;
4126 }
4127 if (app.removed) {
4128 procs.add(app);
4129 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
4130 app.removed = true;
4131 procs.add(app);
4132 }
4133 }
4134 }
4135
4136 int N = procs.size();
4137 for (int i=0; i<N; i++) {
4138 removeProcessLocked(procs.get(i), false, true, "kill all background");
4139 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004140 }
4141 } finally {
4142 Binder.restoreCallingIdentity(callingId);
4143 }
4144 }
4145
4146 public void forceStopPackage(final String packageName) {
4147 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4148 != PackageManager.PERMISSION_GRANTED) {
4149 String msg = "Permission Denial: forceStopPackage() from pid="
4150 + Binder.getCallingPid()
4151 + ", uid=" + Binder.getCallingUid()
4152 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004153 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004154 throw new SecurityException(msg);
4155 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004156 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08004157 long callingId = Binder.clearCallingIdentity();
4158 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004159 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08004160 int pkgUid = -1;
4161 synchronized(this) {
4162 try {
4163 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004164 // Convert the uid to the one for the calling user
4165 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004166 } catch (RemoteException e) {
4167 }
4168 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004169 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004170 return;
4171 }
4172 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08004173 try {
4174 pm.setPackageStoppedState(packageName, true);
4175 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08004176 } catch (IllegalArgumentException e) {
4177 Slog.w(TAG, "Failed trying to unstop package "
4178 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08004179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 }
4181 } finally {
4182 Binder.restoreCallingIdentity(callingId);
4183 }
4184 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004185
4186 /*
4187 * The pkg name and uid have to be specified.
4188 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
4189 */
4190 public void killApplicationWithUid(String pkg, int uid) {
4191 if (pkg == null) {
4192 return;
4193 }
4194 // Make sure the uid is valid.
4195 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004196 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004197 return;
4198 }
4199 int callerUid = Binder.getCallingUid();
4200 // Only the system server can kill an application
4201 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07004202 // Post an aysnc message to kill the application
4203 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
4204 msg.arg1 = uid;
4205 msg.arg2 = 0;
4206 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07004207 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004208 } else {
4209 throw new SecurityException(callerUid + " cannot kill pkg: " +
4210 pkg);
4211 }
4212 }
4213
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004214 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004215 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004216 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004217 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004218 if (reason != null) {
4219 intent.putExtra("reason", reason);
4220 }
4221
4222 final int uid = Binder.getCallingUid();
4223 final long origId = Binder.clearCallingIdentity();
4224 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07004225 mWindowManager.closeSystemDialogs(reason);
4226
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08004227 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004228 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07004229 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004230 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07004231 Activity.RESULT_CANCELED, null, "close-sys");
4232 }
4233 }
4234
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004235 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07004236 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004237 }
4238 Binder.restoreCallingIdentity(origId);
4239 }
4240
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004241 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004242 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004243 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004244 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
4245 for (int i=pids.length-1; i>=0; i--) {
4246 infos[i] = new Debug.MemoryInfo();
4247 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004248 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004249 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004250 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07004251
Dianne Hackbornb437e092011-08-05 17:50:29 -07004252 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004253 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07004254 long[] pss = new long[pids.length];
4255 for (int i=pids.length-1; i>=0; i--) {
4256 pss[i] = Debug.getPss(pids[i]);
4257 }
4258 return pss;
4259 }
4260
Christopher Tate5e1ab332009-09-01 20:32:49 -07004261 public void killApplicationProcess(String processName, int uid) {
4262 if (processName == null) {
4263 return;
4264 }
4265
4266 int callerUid = Binder.getCallingUid();
4267 // Only the system server can kill an application
4268 if (callerUid == Process.SYSTEM_UID) {
4269 synchronized (this) {
4270 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07004271 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07004272 try {
4273 app.thread.scheduleSuicide();
4274 } catch (RemoteException e) {
4275 // If the other end already died, then our work here is done.
4276 }
4277 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004278 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07004279 + processName + " / " + uid);
4280 }
4281 }
4282 } else {
4283 throw new SecurityException(callerUid + " cannot kill app process: " +
4284 processName);
4285 }
4286 }
4287
Dianne Hackborn03abb812010-01-04 18:43:19 -08004288 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004289 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
4291 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004292 if (!mProcessesReady) {
4293 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 intent.putExtra(Intent.EXTRA_UID, uid);
4296 broadcastIntentLocked(null, null, intent,
4297 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07004298 false, false,
4299 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 }
4301
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004302 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07004303 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004304 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08004305 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306
Dianne Hackborn03abb812010-01-04 18:43:19 -08004307 // Remove all processes this package may have touched: all with the
4308 // same UID (except for the system or root user), and all whose name
4309 // matches the package name.
4310 final String procNamePrefix = packageName + ":";
4311 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
4312 final int NA = apps.size();
4313 for (int ia=0; ia<NA; ia++) {
4314 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07004315 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07004316 // we don't kill persistent processes
4317 continue;
4318 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004319 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004320 if (doit) {
4321 procs.add(app);
4322 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004323 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
4324 || app.processName.equals(packageName)
4325 || app.processName.startsWith(procNamePrefix)) {
4326 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004327 if (!doit) {
4328 return true;
4329 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004330 app.removed = true;
4331 procs.add(app);
4332 }
4333 }
4334 }
4335 }
4336
4337 int N = procs.size();
4338 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004339 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004340 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004341 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08004342 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004343
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004344 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07004345 boolean callerWillRestart, boolean purgeCache, boolean doit,
4346 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004347 int i;
4348 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 if (uid < 0) {
4351 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004352 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 } catch (RemoteException e) {
4354 }
4355 }
4356
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004357 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004358 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004359
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004360 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
4361 while (badApps.hasNext()) {
4362 SparseArray<Long> ba = badApps.next();
4363 if (ba.get(uid) != null) {
4364 badApps.remove();
4365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004366 }
4367 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004368
4369 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004370 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004372 TaskRecord lastTask = null;
4373 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004374 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004375 final boolean samePackage = r.packageName.equals(name);
4376 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07004377 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004378 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07004379 if (r.finishing) {
4380 // If this activity is just finishing, then it is not
4381 // interesting as far as something to stop.
4382 continue;
4383 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004384 return true;
4385 }
4386 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004387 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004388 if (samePackage) {
4389 if (r.app != null) {
4390 r.app.removed = true;
4391 }
4392 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004394 lastTask = r.task;
4395 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
4396 null, "force-stop")) {
4397 i--;
4398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 }
4400 }
4401
4402 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07004403 int userId = UserId.getUserId(uid);
4404 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07004405 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07004406 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004407 if (!doit) {
4408 return true;
4409 }
4410 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004411 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412 if (service.app != null) {
4413 service.app.removed = true;
4414 }
4415 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004416 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004417 services.add(service);
4418 }
4419 }
4420
4421 N = services.size();
4422 for (i=0; i<N; i++) {
4423 bringDownServiceLocked(services.get(i), true);
4424 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004425
4426 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
4427 for (ContentProviderRecord provider : mProvidersByClass.values()) {
4428 if (provider.info.packageName.equals(name)
4429 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
4430 if (!doit) {
4431 return true;
4432 }
4433 didSomething = true;
4434 providers.add(provider);
4435 }
4436 }
4437
4438 N = providers.size();
4439 for (i=0; i<N; i++) {
4440 removeDyingProviderLocked(null, providers.get(i));
4441 }
4442
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004443 if (doit) {
4444 if (purgeCache) {
4445 AttributeCache ac = AttributeCache.instance();
4446 if (ac != null) {
4447 ac.removePackage(name);
4448 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004449 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004450 if (mBooted) {
4451 mMainStack.resumeTopActivityLocked(null);
4452 mMainStack.scheduleIdleLocked();
4453 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004454 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004455
4456 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004457 }
4458
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004459 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004460 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004462 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004463 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004464 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004465 + "/" + uid + ")");
4466
4467 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004468 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004469 if (mHeavyWeightProcess == app) {
4470 mHeavyWeightProcess = null;
4471 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
4472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004473 boolean needRestart = false;
4474 if (app.pid > 0 && app.pid != MY_PID) {
4475 int pid = app.pid;
4476 synchronized (mPidsSelfLocked) {
4477 mPidsSelfLocked.remove(pid);
4478 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4479 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004480 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004481 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004482 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004483 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004485 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004486 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004487 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 } else {
4489 needRestart = true;
4490 }
4491 }
4492 } else {
4493 mRemovedProcesses.add(app);
4494 }
4495
4496 return needRestart;
4497 }
4498
4499 private final void processStartTimedOutLocked(ProcessRecord app) {
4500 final int pid = app.pid;
4501 boolean gone = false;
4502 synchronized (mPidsSelfLocked) {
4503 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4504 if (knownApp != null && knownApp.thread == null) {
4505 mPidsSelfLocked.remove(pid);
4506 gone = true;
4507 }
4508 }
4509
4510 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004511 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004512 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004513 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004514 mProcessNames.remove(app.processName, app.uid);
4515 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004516 if (mHeavyWeightProcess == app) {
4517 mHeavyWeightProcess = null;
4518 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
4519 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004520 // Take care of any launching providers waiting for this process.
4521 checkAppInLaunchingProvidersLocked(app, true);
4522 // Take care of any services that are waiting for the process.
4523 for (int i=0; i<mPendingServices.size(); i++) {
4524 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004525 if ((app.uid == sr.appInfo.uid
4526 && app.processName.equals(sr.processName))
4527 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004528 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004529 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004530 mPendingServices.remove(i);
4531 i--;
4532 bringDownServiceLocked(sr, true);
4533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004535 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
4536 app.processName, app.setAdj, "start timeout");
4537 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004538 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004539 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004540 try {
4541 IBackupManager bm = IBackupManager.Stub.asInterface(
4542 ServiceManager.getService(Context.BACKUP_SERVICE));
4543 bm.agentDisconnected(app.info.packageName);
4544 } catch (RemoteException e) {
4545 // Can't happen; the backup manager is local
4546 }
4547 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004548 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004549 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004550 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004553 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004554 }
4555 }
4556
4557 private final boolean attachApplicationLocked(IApplicationThread thread,
4558 int pid) {
4559
4560 // Find the application record that is being attached... either via
4561 // the pid if we are running in multiple processes, or just pull the
4562 // next app record if we are emulating process with anonymous threads.
4563 ProcessRecord app;
4564 if (pid != MY_PID && pid >= 0) {
4565 synchronized (mPidsSelfLocked) {
4566 app = mPidsSelfLocked.get(pid);
4567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 } else {
4569 app = null;
4570 }
4571
4572 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004573 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004574 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004575 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004577 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004578 } else {
4579 try {
4580 thread.scheduleExit();
4581 } catch (Exception e) {
4582 // Ignore exceptions.
4583 }
4584 }
4585 return false;
4586 }
4587
4588 // If this application record is still attached to a previous
4589 // process, clean it up now.
4590 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004591 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592 }
4593
4594 // Tell the process all about itself.
4595
Joe Onorato8a9b2202010-02-26 18:56:32 -08004596 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004597 TAG, "Binding process pid " + pid + " to record " + app);
4598
4599 String processName = app.processName;
4600 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004601 AppDeathRecipient adr = new AppDeathRecipient(
4602 app, pid, thread);
4603 thread.asBinder().linkToDeath(adr, 0);
4604 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 } catch (RemoteException e) {
4606 app.resetPackageList();
4607 startProcessLocked(app, "link fail", processName);
4608 return false;
4609 }
4610
Doug Zongker2bec3d42009-12-04 12:52:44 -08004611 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612
4613 app.thread = thread;
4614 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004615 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4616 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617 app.forcingToForeground = null;
4618 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004619 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 app.debugging = false;
4621
4622 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4623
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004624 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004625 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004627 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004628 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004629 }
4630
Joe Onorato8a9b2202010-02-26 18:56:32 -08004631 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 TAG, "New app record " + app
4633 + " thread=" + thread.asBinder() + " pid=" + pid);
4634 try {
4635 int testMode = IApplicationThread.DEBUG_OFF;
4636 if (mDebugApp != null && mDebugApp.equals(processName)) {
4637 testMode = mWaitForDebugger
4638 ? IApplicationThread.DEBUG_WAIT
4639 : IApplicationThread.DEBUG_ON;
4640 app.debugging = true;
4641 if (mDebugTransient) {
4642 mDebugApp = mOrigDebugApp;
4643 mWaitForDebugger = mOrigWaitForDebugger;
4644 }
4645 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004646 String profileFile = app.instrumentationProfileFile;
4647 ParcelFileDescriptor profileFd = null;
4648 boolean profileAutoStop = false;
4649 if (mProfileApp != null && mProfileApp.equals(processName)) {
4650 mProfileProc = app;
4651 profileFile = mProfileFile;
4652 profileFd = mProfileFd;
4653 profileAutoStop = mAutoStopProfiler;
4654 }
4655
Christopher Tate181fafa2009-05-14 11:12:14 -07004656 // If the app is being launched for restore or full backup, set it up specially
4657 boolean isRestrictedBackupMode = false;
4658 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4659 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004660 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004661 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4662 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004663
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004664 ensurePackageDexOpt(app.instrumentationInfo != null
4665 ? app.instrumentationInfo.packageName
4666 : app.info.packageName);
4667 if (app.instrumentationClass != null) {
4668 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004669 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004670 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004671 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004672 ApplicationInfo appInfo = app.instrumentationInfo != null
4673 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004674 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004675 if (profileFd != null) {
4676 profileFd = profileFd.dup();
4677 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004678 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004679 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004680 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn5d927c22011-09-02 12:22:18 -07004681 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004682 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004683 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004684 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004685 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686 } catch (Exception e) {
4687 // todo: Yikes! What should we do? For now we will try to
4688 // start another process, but that could easily get us in
4689 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004690 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004691
4692 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004693 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 startProcessLocked(app, "bind fail", processName);
4695 return false;
4696 }
4697
4698 // Remove this record from the list of starting applications.
4699 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004700 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4701 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004702 mProcessesOnHold.remove(app);
4703
4704 boolean badApp = false;
4705 boolean didSomething = false;
4706
4707 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004708 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004709 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004710 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004711 && processName.equals(hr.processName)) {
4712 try {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004713 if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004714 didSomething = true;
4715 }
4716 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004717 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004718 + hr.intent.getComponent().flattenToShortString(), e);
4719 badApp = true;
4720 }
4721 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004722 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004723 }
4724 }
4725
4726 // Find any services that should be running in this process...
4727 if (!badApp && mPendingServices.size() > 0) {
4728 ServiceRecord sr = null;
4729 try {
4730 for (int i=0; i<mPendingServices.size(); i++) {
4731 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004732 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4733 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004734 continue;
4735 }
4736
4737 mPendingServices.remove(i);
4738 i--;
4739 realStartServiceLocked(sr, app);
4740 didSomething = true;
4741 }
4742 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004743 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004744 + sr.shortName, e);
4745 badApp = true;
4746 }
4747 }
4748
Christopher Tatef46723b2012-01-26 14:19:24 -08004749 // Check if a next-broadcast receiver is in this process...
4750 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004751 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004752 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004754 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004755 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004756 }
4757 }
4758
Christopher Tate181fafa2009-05-14 11:12:14 -07004759 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004760 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004761 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004762 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004763 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004764 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4765 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4766 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004767 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004768 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004769 e.printStackTrace();
4770 }
4771 }
4772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004773 if (badApp) {
4774 // todo: Also need to kill application to deal with all
4775 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004776 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004777 return false;
4778 }
4779
4780 if (!didSomething) {
4781 updateOomAdjLocked();
4782 }
4783
4784 return true;
4785 }
4786
4787 public final void attachApplication(IApplicationThread thread) {
4788 synchronized (this) {
4789 int callingPid = Binder.getCallingPid();
4790 final long origId = Binder.clearCallingIdentity();
4791 attachApplicationLocked(thread, callingPid);
4792 Binder.restoreCallingIdentity(origId);
4793 }
4794 }
4795
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004796 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004797 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004798 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4799 if (stopProfiling) {
4800 synchronized (this) {
4801 if (mProfileProc == r.app) {
4802 if (mProfileFd != null) {
4803 try {
4804 mProfileFd.close();
4805 } catch (IOException e) {
4806 }
4807 clearProfilerLocked();
4808 }
4809 }
4810 }
4811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 Binder.restoreCallingIdentity(origId);
4813 }
4814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004815 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004816 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004817 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 mWindowManager.enableScreenAfterBoot();
4819 }
4820
Dianne Hackborn661cd522011-08-22 00:26:20 -07004821 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004822 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004823 mWindowManager.showBootMessage(msg, always);
4824 }
4825
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004826 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004827 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004828 synchronized (this) {
4829 mMainStack.dismissKeyguardOnNextActivityLocked();
4830 }
4831 }
4832
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004833 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004834 IntentFilter pkgFilter = new IntentFilter();
4835 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4836 pkgFilter.addDataScheme("package");
4837 mContext.registerReceiver(new BroadcastReceiver() {
4838 @Override
4839 public void onReceive(Context context, Intent intent) {
4840 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4841 if (pkgs != null) {
4842 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004843 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004844 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004845 setResultCode(Activity.RESULT_OK);
4846 return;
4847 }
4848 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004849 }
4850 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004851 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004852 }, pkgFilter);
4853
4854 synchronized (this) {
4855 // Ensure that any processes we had put on hold are now started
4856 // up.
4857 final int NP = mProcessesOnHold.size();
4858 if (NP > 0) {
4859 ArrayList<ProcessRecord> procs =
4860 new ArrayList<ProcessRecord>(mProcessesOnHold);
4861 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004862 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4863 + procs.get(ip));
4864 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004865 }
4866 }
4867
4868 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004869 // Start looking for apps that are abusing wake locks.
4870 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004871 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004872 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004873 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004874 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004875 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004876 broadcastIntentLocked(null, null,
4877 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4878 null, null, 0, null, null,
4879 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004880 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004881 }
4882 }
4883 }
4884
4885 final void ensureBootCompleted() {
4886 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004887 boolean enableScreen;
4888 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004889 booting = mBooting;
4890 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004891 enableScreen = !mBooted;
4892 mBooted = true;
4893 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004894
4895 if (booting) {
4896 finishBooting();
4897 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004898
4899 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004900 enableScreenAfterBoot();
4901 }
4902 }
4903
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004904 public final void activityPaused(IBinder token) {
4905 final long origId = Binder.clearCallingIdentity();
4906 mMainStack.activityPaused(token, false);
4907 Binder.restoreCallingIdentity(origId);
4908 }
4909
4910 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4911 CharSequence description) {
4912 if (localLOGV) Slog.v(
4913 TAG, "Activity stopped: token=" + token);
4914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004915 // Refuse possible leaked file descriptors
4916 if (icicle != null && icicle.hasFileDescriptors()) {
4917 throw new IllegalArgumentException("File descriptors passed in Bundle");
4918 }
4919
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004920 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004921
4922 final long origId = Binder.clearCallingIdentity();
4923
4924 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004925 r = mMainStack.isInStackLocked(token);
4926 if (r != null) {
4927 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004928 }
4929 }
4930
4931 if (r != null) {
4932 sendPendingThumbnail(r, null, null, null, false);
4933 }
4934
4935 trimApplications();
4936
4937 Binder.restoreCallingIdentity(origId);
4938 }
4939
4940 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004941 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004942 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943 }
4944
4945 public String getCallingPackage(IBinder token) {
4946 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004947 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004948 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004949 }
4950 }
4951
4952 public ComponentName getCallingActivity(IBinder token) {
4953 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004954 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004955 return r != null ? r.intent.getComponent() : null;
4956 }
4957 }
4958
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004959 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004960 ActivityRecord r = mMainStack.isInStackLocked(token);
4961 if (r == null) {
4962 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004964 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 }
4966
4967 public ComponentName getActivityClassForToken(IBinder token) {
4968 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004969 ActivityRecord r = mMainStack.isInStackLocked(token);
4970 if (r == null) {
4971 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004972 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004973 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004974 }
4975 }
4976
4977 public String getPackageForToken(IBinder token) {
4978 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004979 ActivityRecord r = mMainStack.isInStackLocked(token);
4980 if (r == null) {
4981 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004982 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004983 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984 }
4985 }
4986
4987 public IIntentSender getIntentSender(int type,
4988 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004989 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004990 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004991 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004992 if (intents != null) {
4993 if (intents.length < 1) {
4994 throw new IllegalArgumentException("Intents array length must be >= 1");
4995 }
4996 for (int i=0; i<intents.length; i++) {
4997 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004998 if (intent != null) {
4999 if (intent.hasFileDescriptors()) {
5000 throw new IllegalArgumentException("File descriptors passed in Intent");
5001 }
5002 if (type == INTENT_SENDER_BROADCAST &&
5003 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
5004 throw new IllegalArgumentException(
5005 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
5006 }
5007 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005008 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005009 }
5010 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005011 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005012 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005013 }
5014 }
5015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 synchronized(this) {
5017 int callingUid = Binder.getCallingUid();
5018 try {
Jeff Brown10e89712011-07-08 18:52:57 -07005019 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005020 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005021 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07005022 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 String msg = "Permission Denial: getIntentSender() from pid="
5024 + Binder.getCallingPid()
5025 + ", uid=" + Binder.getCallingUid()
5026 + ", (need uid=" + uid + ")"
5027 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005028 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005029 throw new SecurityException(msg);
5030 }
5031 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005032
Amith Yamasani742a6712011-05-04 14:49:28 -07005033 if (DEBUG_MU)
5034 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
5035 + Binder.getOrigCallingUid());
5036 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005037 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07005038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005039 } catch (RemoteException e) {
5040 throw new SecurityException(e);
5041 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005042 }
5043 }
5044
5045 IIntentSender getIntentSenderLocked(int type,
5046 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005047 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005048 if (DEBUG_MU)
5049 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005050 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07005051 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005052 activity = mMainStack.isInStackLocked(token);
5053 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005054 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005055 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005056 if (activity.finishing) {
5057 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005058 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005059 }
5060
5061 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
5062 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
5063 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
5064 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
5065 |PendingIntent.FLAG_UPDATE_CURRENT);
5066
5067 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
5068 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005069 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07005070 WeakReference<PendingIntentRecord> ref;
5071 ref = mIntentSenderRecords.get(key);
5072 PendingIntentRecord rec = ref != null ? ref.get() : null;
5073 if (rec != null) {
5074 if (!cancelCurrent) {
5075 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005076 if (rec.key.requestIntent != null) {
5077 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
5078 }
5079 if (intents != null) {
5080 intents[intents.length-1] = rec.key.requestIntent;
5081 rec.key.allIntents = intents;
5082 rec.key.allResolvedTypes = resolvedTypes;
5083 } else {
5084 rec.key.allIntents = null;
5085 rec.key.allResolvedTypes = null;
5086 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088 return rec;
5089 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005090 rec.canceled = true;
5091 mIntentSenderRecords.remove(key);
5092 }
5093 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 return rec;
5095 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005096 rec = new PendingIntentRecord(this, key, callingUid);
5097 mIntentSenderRecords.put(key, rec.ref);
5098 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
5099 if (activity.pendingResults == null) {
5100 activity.pendingResults
5101 = new HashSet<WeakReference<PendingIntentRecord>>();
5102 }
5103 activity.pendingResults.add(rec.ref);
5104 }
5105 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 }
5107
5108 public void cancelIntentSender(IIntentSender sender) {
5109 if (!(sender instanceof PendingIntentRecord)) {
5110 return;
5111 }
5112 synchronized(this) {
5113 PendingIntentRecord rec = (PendingIntentRecord)sender;
5114 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005115 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 .getPackageUid(rec.key.packageName);
5117 if (uid != Binder.getCallingUid()) {
5118 String msg = "Permission Denial: cancelIntentSender() from pid="
5119 + Binder.getCallingPid()
5120 + ", uid=" + Binder.getCallingUid()
5121 + " is not allowed to cancel packges "
5122 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005123 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 throw new SecurityException(msg);
5125 }
5126 } catch (RemoteException e) {
5127 throw new SecurityException(e);
5128 }
5129 cancelIntentSenderLocked(rec, true);
5130 }
5131 }
5132
5133 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
5134 rec.canceled = true;
5135 mIntentSenderRecords.remove(rec.key);
5136 if (cleanActivity && rec.key.activity != null) {
5137 rec.key.activity.pendingResults.remove(rec.ref);
5138 }
5139 }
5140
5141 public String getPackageForIntentSender(IIntentSender pendingResult) {
5142 if (!(pendingResult instanceof PendingIntentRecord)) {
5143 return null;
5144 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07005145 try {
5146 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5147 return res.key.packageName;
5148 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005149 }
5150 return null;
5151 }
5152
Dianne Hackborn6c418d52011-06-29 14:05:33 -07005153 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
5154 if (!(pendingResult instanceof PendingIntentRecord)) {
5155 return false;
5156 }
5157 try {
5158 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5159 if (res.key.allIntents == null) {
5160 return false;
5161 }
5162 for (int i=0; i<res.key.allIntents.length; i++) {
5163 Intent intent = res.key.allIntents[i];
5164 if (intent.getPackage() != null && intent.getComponent() != null) {
5165 return false;
5166 }
5167 }
5168 return true;
5169 } catch (ClassCastException e) {
5170 }
5171 return false;
5172 }
5173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005174 public void setProcessLimit(int max) {
5175 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5176 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005177 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005178 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005179 mProcessLimitOverride = max;
5180 }
5181 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005182 }
5183
5184 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005185 synchronized (this) {
5186 return mProcessLimitOverride;
5187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005188 }
5189
5190 void foregroundTokenDied(ForegroundToken token) {
5191 synchronized (ActivityManagerService.this) {
5192 synchronized (mPidsSelfLocked) {
5193 ForegroundToken cur
5194 = mForegroundProcesses.get(token.pid);
5195 if (cur != token) {
5196 return;
5197 }
5198 mForegroundProcesses.remove(token.pid);
5199 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
5200 if (pr == null) {
5201 return;
5202 }
5203 pr.forcingToForeground = null;
5204 pr.foregroundServices = false;
5205 }
5206 updateOomAdjLocked();
5207 }
5208 }
5209
5210 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
5211 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5212 "setProcessForeground()");
5213 synchronized(this) {
5214 boolean changed = false;
5215
5216 synchronized (mPidsSelfLocked) {
5217 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005218 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005219 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 return;
5221 }
5222 ForegroundToken oldToken = mForegroundProcesses.get(pid);
5223 if (oldToken != null) {
5224 oldToken.token.unlinkToDeath(oldToken, 0);
5225 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005226 if (pr != null) {
5227 pr.forcingToForeground = null;
5228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 changed = true;
5230 }
5231 if (isForeground && token != null) {
5232 ForegroundToken newToken = new ForegroundToken() {
5233 public void binderDied() {
5234 foregroundTokenDied(this);
5235 }
5236 };
5237 newToken.pid = pid;
5238 newToken.token = token;
5239 try {
5240 token.linkToDeath(newToken, 0);
5241 mForegroundProcesses.put(pid, newToken);
5242 pr.forcingToForeground = token;
5243 changed = true;
5244 } catch (RemoteException e) {
5245 // If the process died while doing this, we will later
5246 // do the cleanup with the process death link.
5247 }
5248 }
5249 }
5250
5251 if (changed) {
5252 updateOomAdjLocked();
5253 }
5254 }
5255 }
5256
5257 // =========================================================
5258 // PERMISSIONS
5259 // =========================================================
5260
5261 static class PermissionController extends IPermissionController.Stub {
5262 ActivityManagerService mActivityManagerService;
5263 PermissionController(ActivityManagerService activityManagerService) {
5264 mActivityManagerService = activityManagerService;
5265 }
5266
5267 public boolean checkPermission(String permission, int pid, int uid) {
5268 return mActivityManagerService.checkPermission(permission, pid,
5269 uid) == PackageManager.PERMISSION_GRANTED;
5270 }
5271 }
5272
5273 /**
5274 * This can be called with or without the global lock held.
5275 */
5276 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005277 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005278 // We might be performing an operation on behalf of an indirect binder
5279 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
5280 // client identity accordingly before proceeding.
5281 Identity tlsIdentity = sCallerIdentity.get();
5282 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005283 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005284 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
5285 uid = tlsIdentity.uid;
5286 pid = tlsIdentity.pid;
5287 }
5288
5289 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005290 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 return PackageManager.PERMISSION_GRANTED;
5292 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005293 // Isolated processes don't get any permissions.
5294 if (UserId.isIsolated(uid)) {
5295 return PackageManager.PERMISSION_DENIED;
5296 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005297 // If there is a uid that owns whatever is being accessed, it has
5298 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07005299 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005300 return PackageManager.PERMISSION_GRANTED;
5301 }
5302 // If the target is not exported, then nobody else can get to it.
5303 if (!exported) {
5304 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005305 return PackageManager.PERMISSION_DENIED;
5306 }
5307 if (permission == null) {
5308 return PackageManager.PERMISSION_GRANTED;
5309 }
5310 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005311 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 .checkUidPermission(permission, uid);
5313 } catch (RemoteException e) {
5314 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08005315 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005316 }
5317 return PackageManager.PERMISSION_DENIED;
5318 }
5319
5320 /**
5321 * As the only public entry point for permissions checking, this method
5322 * can enforce the semantic that requesting a check on a null global
5323 * permission is automatically denied. (Internally a null permission
5324 * string is used when calling {@link #checkComponentPermission} in cases
5325 * when only uid-based security is needed.)
5326 *
5327 * This can be called with or without the global lock held.
5328 */
5329 public int checkPermission(String permission, int pid, int uid) {
5330 if (permission == null) {
5331 return PackageManager.PERMISSION_DENIED;
5332 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005333 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005334 }
5335
5336 /**
5337 * Binder IPC calls go through the public entry point.
5338 * This can be called with or without the global lock held.
5339 */
5340 int checkCallingPermission(String permission) {
5341 return checkPermission(permission,
5342 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07005343 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005344 }
5345
5346 /**
5347 * This can be called with or without the global lock held.
5348 */
5349 void enforceCallingPermission(String permission, String func) {
5350 if (checkCallingPermission(permission)
5351 == PackageManager.PERMISSION_GRANTED) {
5352 return;
5353 }
5354
5355 String msg = "Permission Denial: " + func + " from pid="
5356 + Binder.getCallingPid()
5357 + ", uid=" + Binder.getCallingUid()
5358 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005359 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005360 throw new SecurityException(msg);
5361 }
5362
5363 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07005364 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
5365 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
5366 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
5367 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5368 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005369 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005370 // Is the component private from the target uid?
5371 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
5372
5373 // Acceptable if the there is no read permission needed from the
5374 // target or the target is holding the read permission.
5375 if (!readPerm) {
5376 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005377 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07005378 == PackageManager.PERMISSION_GRANTED)) {
5379 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 }
5381 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005382
5383 // Acceptable if the there is no write permission needed from the
5384 // target or the target is holding the read permission.
5385 if (!writePerm) {
5386 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07005388 == PackageManager.PERMISSION_GRANTED)) {
5389 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005390 }
5391 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005392
5393 // Acceptable if there is a path permission matching the URI that
5394 // the target holds the permission on.
5395 PathPermission[] pps = pi.pathPermissions;
5396 if (pps != null && (!readPerm || !writePerm)) {
5397 final String path = uri.getPath();
5398 int i = pps.length;
5399 while (i > 0 && (!readPerm || !writePerm)) {
5400 i--;
5401 PathPermission pp = pps[i];
5402 if (!readPerm) {
5403 final String pprperm = pp.getReadPermission();
5404 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5405 + pprperm + " for " + pp.getPath()
5406 + ": match=" + pp.match(path)
5407 + " check=" + pm.checkUidPermission(pprperm, uid));
5408 if (pprperm != null && pp.match(path) &&
5409 (pm.checkUidPermission(pprperm, uid)
5410 == PackageManager.PERMISSION_GRANTED)) {
5411 readPerm = true;
5412 }
5413 }
5414 if (!writePerm) {
5415 final String ppwperm = pp.getWritePermission();
5416 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5417 + ppwperm + " for " + pp.getPath()
5418 + ": match=" + pp.match(path)
5419 + " check=" + pm.checkUidPermission(ppwperm, uid));
5420 if (ppwperm != null && pp.match(path) &&
5421 (pm.checkUidPermission(ppwperm, uid)
5422 == PackageManager.PERMISSION_GRANTED)) {
5423 writePerm = true;
5424 }
5425 }
5426 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005428 } catch (RemoteException e) {
5429 return false;
5430 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005431
5432 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005433 }
5434
5435 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5436 int modeFlags) {
5437 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005438 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 return true;
5440 }
5441 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5442 if (perms == null) return false;
5443 UriPermission perm = perms.get(uri);
5444 if (perm == null) return false;
5445 return (modeFlags&perm.modeFlags) == modeFlags;
5446 }
5447
5448 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005449 enforceNotIsolatedCaller("checkUriPermission");
5450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 // Another redirected-binder-call permissions check as in
5452 // {@link checkComponentPermission}.
5453 Identity tlsIdentity = sCallerIdentity.get();
5454 if (tlsIdentity != null) {
5455 uid = tlsIdentity.uid;
5456 pid = tlsIdentity.pid;
5457 }
5458
Amith Yamasani742a6712011-05-04 14:49:28 -07005459 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460 // Our own process gets to do everything.
5461 if (pid == MY_PID) {
5462 return PackageManager.PERMISSION_GRANTED;
5463 }
5464 synchronized(this) {
5465 return checkUriPermissionLocked(uri, uid, modeFlags)
5466 ? PackageManager.PERMISSION_GRANTED
5467 : PackageManager.PERMISSION_DENIED;
5468 }
5469 }
5470
Dianne Hackborn39792d22010-08-19 18:01:52 -07005471 /**
5472 * Check if the targetPkg can be granted permission to access uri by
5473 * the callingUid using the given modeFlags. Throws a security exception
5474 * if callingUid is not allowed to do this. Returns the uid of the target
5475 * if the URI permission grant should be performed; returns -1 if it is not
5476 * needed (for example targetPkg already has permission to access the URI).
5477 */
5478 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
5479 Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005480 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5481 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5482 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005483 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 }
5485
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005486 if (targetPkg != null) {
5487 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5488 "Checking grant " + targetPkg + " permission to " + uri);
5489 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005490
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005491 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005492
5493 // If this is not a content: uri, we can't do anything with it.
5494 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005495 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005496 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005497 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 }
5499
5500 String name = uri.getAuthority();
5501 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005502 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
5503 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 if (cpr != null) {
5505 pi = cpr.info;
5506 } else {
5507 try {
5508 pi = pm.resolveContentProvider(name,
5509 PackageManager.GET_URI_PERMISSION_PATTERNS);
5510 } catch (RemoteException ex) {
5511 }
5512 }
5513 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005514 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005515 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 }
5517
5518 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005519 if (targetPkg != null) {
5520 try {
5521 targetUid = pm.getPackageUid(targetPkg);
5522 if (targetUid < 0) {
5523 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5524 "Can't grant URI permission no uid for: " + targetPkg);
5525 return -1;
5526 }
5527 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005528 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005530 } else {
5531 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 }
5533
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005534 if (targetUid >= 0) {
5535 // First... does the target actually need this permission?
5536 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5537 // No need to grant the target this permission.
5538 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5539 "Target " + targetPkg + " already has full permission to " + uri);
5540 return -1;
5541 }
5542 } else {
5543 // First... there is no target package, so can anyone access it?
5544 boolean allowed = pi.exported;
5545 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5546 if (pi.readPermission != null) {
5547 allowed = false;
5548 }
5549 }
5550 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5551 if (pi.writePermission != null) {
5552 allowed = false;
5553 }
5554 }
5555 if (allowed) {
5556 return -1;
5557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 }
5559
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005560 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 if (!pi.grantUriPermissions) {
5562 throw new SecurityException("Provider " + pi.packageName
5563 + "/" + pi.name
5564 + " does not allow granting of Uri permissions (uri "
5565 + uri + ")");
5566 }
5567 if (pi.uriPermissionPatterns != null) {
5568 final int N = pi.uriPermissionPatterns.length;
5569 boolean allowed = false;
5570 for (int i=0; i<N; i++) {
5571 if (pi.uriPermissionPatterns[i] != null
5572 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5573 allowed = true;
5574 break;
5575 }
5576 }
5577 if (!allowed) {
5578 throw new SecurityException("Provider " + pi.packageName
5579 + "/" + pi.name
5580 + " does not allow granting of permission to path of Uri "
5581 + uri);
5582 }
5583 }
5584
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005585 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005587 if (callingUid != Process.myUid()) {
5588 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5589 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5590 throw new SecurityException("Uid " + callingUid
5591 + " does not have permission to uri " + uri);
5592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005593 }
5594 }
5595
Dianne Hackborn39792d22010-08-19 18:01:52 -07005596 return targetUid;
5597 }
5598
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005599 public int checkGrantUriPermission(int callingUid, String targetPkg,
5600 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005601 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005602 synchronized(this) {
5603 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
5604 }
5605 }
5606
Dianne Hackborn39792d22010-08-19 18:01:52 -07005607 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5608 Uri uri, int modeFlags, UriPermissionOwner owner) {
5609 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5610 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5611 if (modeFlags == 0) {
5612 return;
5613 }
5614
5615 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 // to the uri, and the target doesn't. Let's now give this to
5617 // the target.
5618
Joe Onorato8a9b2202010-02-26 18:56:32 -08005619 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005620 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005622 HashMap<Uri, UriPermission> targetUris
5623 = mGrantedUriPermissions.get(targetUid);
5624 if (targetUris == null) {
5625 targetUris = new HashMap<Uri, UriPermission>();
5626 mGrantedUriPermissions.put(targetUid, targetUris);
5627 }
5628
5629 UriPermission perm = targetUris.get(uri);
5630 if (perm == null) {
5631 perm = new UriPermission(targetUid, uri);
5632 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005636 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005638 } else {
5639 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5640 perm.readOwners.add(owner);
5641 owner.addReadPermission(perm);
5642 }
5643 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5644 perm.writeOwners.add(owner);
5645 owner.addWritePermission(perm);
5646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 }
5648 }
5649
Dianne Hackborn39792d22010-08-19 18:01:52 -07005650 void grantUriPermissionLocked(int callingUid,
5651 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005652 if (targetPkg == null) {
5653 throw new NullPointerException("targetPkg");
5654 }
5655
Dianne Hackborn39792d22010-08-19 18:01:52 -07005656 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
5657 if (targetUid < 0) {
5658 return;
5659 }
5660
5661 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5662 }
5663
5664 /**
5665 * Like checkGrantUriPermissionLocked, but takes an Intent.
5666 */
5667 int checkGrantUriPermissionFromIntentLocked(int callingUid,
5668 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005669 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005670 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005671 + " from " + intent + "; flags=0x"
5672 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5673
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005674 if (targetPkg == null) {
5675 throw new NullPointerException("targetPkg");
5676 }
5677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005679 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 }
5681 Uri data = intent.getData();
5682 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005683 return -1;
5684 }
5685 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5686 intent.getFlags());
5687 }
5688
5689 /**
5690 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5691 */
5692 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
5693 String targetPkg, Intent intent, UriPermissionOwner owner) {
5694 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
5695 intent.getFlags(), owner);
5696 }
5697
5698 void grantUriPermissionFromIntentLocked(int callingUid,
5699 String targetPkg, Intent intent, UriPermissionOwner owner) {
5700 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
5701 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 return;
5703 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005704
5705 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 }
5707
5708 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5709 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005710 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 synchronized(this) {
5712 final ProcessRecord r = getRecordForAppLocked(caller);
5713 if (r == null) {
5714 throw new SecurityException("Unable to find app for caller "
5715 + caller
5716 + " when granting permission to uri " + uri);
5717 }
5718 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005719 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 }
5721 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005722 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 }
5724
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005725 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 null);
5727 }
5728 }
5729
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005730 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5732 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5733 HashMap<Uri, UriPermission> perms
5734 = mGrantedUriPermissions.get(perm.uid);
5735 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005736 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005737 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 perms.remove(perm.uri);
5739 if (perms.size() == 0) {
5740 mGrantedUriPermissions.remove(perm.uid);
5741 }
5742 }
5743 }
5744 }
5745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005746 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5747 int modeFlags) {
5748 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5749 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5750 if (modeFlags == 0) {
5751 return;
5752 }
5753
Joe Onorato8a9b2202010-02-26 18:56:32 -08005754 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005755 "Revoking all granted permissions to " + uri);
5756
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005757 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758
5759 final String authority = uri.getAuthority();
5760 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005761 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
5762 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 if (cpr != null) {
5764 pi = cpr.info;
5765 } else {
5766 try {
5767 pi = pm.resolveContentProvider(authority,
5768 PackageManager.GET_URI_PERMISSION_PATTERNS);
5769 } catch (RemoteException ex) {
5770 }
5771 }
5772 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005773 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774 return;
5775 }
5776
5777 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005778 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 // Right now, if you are not the original owner of the permission,
5780 // you are not allowed to revoke it.
5781 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5782 throw new SecurityException("Uid " + callingUid
5783 + " does not have permission to uri " + uri);
5784 //}
5785 }
5786
5787 // Go through all of the permissions and remove any that match.
5788 final List<String> SEGMENTS = uri.getPathSegments();
5789 if (SEGMENTS != null) {
5790 final int NS = SEGMENTS.size();
5791 int N = mGrantedUriPermissions.size();
5792 for (int i=0; i<N; i++) {
5793 HashMap<Uri, UriPermission> perms
5794 = mGrantedUriPermissions.valueAt(i);
5795 Iterator<UriPermission> it = perms.values().iterator();
5796 toploop:
5797 while (it.hasNext()) {
5798 UriPermission perm = it.next();
5799 Uri targetUri = perm.uri;
5800 if (!authority.equals(targetUri.getAuthority())) {
5801 continue;
5802 }
5803 List<String> targetSegments = targetUri.getPathSegments();
5804 if (targetSegments == null) {
5805 continue;
5806 }
5807 if (targetSegments.size() < NS) {
5808 continue;
5809 }
5810 for (int j=0; j<NS; j++) {
5811 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5812 continue toploop;
5813 }
5814 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005815 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005816 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 perm.clearModes(modeFlags);
5818 if (perm.modeFlags == 0) {
5819 it.remove();
5820 }
5821 }
5822 if (perms.size() == 0) {
5823 mGrantedUriPermissions.remove(
5824 mGrantedUriPermissions.keyAt(i));
5825 N--;
5826 i--;
5827 }
5828 }
5829 }
5830 }
5831
5832 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5833 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005834 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 synchronized(this) {
5836 final ProcessRecord r = getRecordForAppLocked(caller);
5837 if (r == null) {
5838 throw new SecurityException("Unable to find app for caller "
5839 + caller
5840 + " when revoking permission to uri " + uri);
5841 }
5842 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005843 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 return;
5845 }
5846
5847 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5848 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5849 if (modeFlags == 0) {
5850 return;
5851 }
5852
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005853 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005854
5855 final String authority = uri.getAuthority();
5856 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005857 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858 if (cpr != null) {
5859 pi = cpr.info;
5860 } else {
5861 try {
5862 pi = pm.resolveContentProvider(authority,
5863 PackageManager.GET_URI_PERMISSION_PATTERNS);
5864 } catch (RemoteException ex) {
5865 }
5866 }
5867 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005868 Slog.w(TAG, "No content provider found for permission revoke: "
5869 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005870 return;
5871 }
5872
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005873 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 }
5875 }
5876
Dianne Hackborn7e269642010-08-25 19:50:20 -07005877 @Override
5878 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005879 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005880 synchronized(this) {
5881 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5882 return owner.getExternalTokenLocked();
5883 }
5884 }
5885
5886 @Override
5887 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5888 Uri uri, int modeFlags) {
5889 synchronized(this) {
5890 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5891 if (owner == null) {
5892 throw new IllegalArgumentException("Unknown owner: " + token);
5893 }
5894 if (fromUid != Binder.getCallingUid()) {
5895 if (Binder.getCallingUid() != Process.myUid()) {
5896 // Only system code can grant URI permissions on behalf
5897 // of other users.
5898 throw new SecurityException("nice try");
5899 }
5900 }
5901 if (targetPkg == null) {
5902 throw new IllegalArgumentException("null target");
5903 }
5904 if (uri == null) {
5905 throw new IllegalArgumentException("null uri");
5906 }
5907
5908 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5909 }
5910 }
5911
5912 @Override
5913 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5914 synchronized(this) {
5915 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5916 if (owner == null) {
5917 throw new IllegalArgumentException("Unknown owner: " + token);
5918 }
5919
5920 if (uri == null) {
5921 owner.removeUriPermissionsLocked(mode);
5922 } else {
5923 owner.removeUriPermissionLocked(uri, mode);
5924 }
5925 }
5926 }
5927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005928 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5929 synchronized (this) {
5930 ProcessRecord app =
5931 who != null ? getRecordForAppLocked(who) : null;
5932 if (app == null) return;
5933
5934 Message msg = Message.obtain();
5935 msg.what = WAIT_FOR_DEBUGGER_MSG;
5936 msg.obj = app;
5937 msg.arg1 = waiting ? 1 : 0;
5938 mHandler.sendMessage(msg);
5939 }
5940 }
5941
5942 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005943 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5944 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005946 outInfo.threshold = homeAppMem;
5947 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5948 outInfo.hiddenAppThreshold = hiddenAppMem;
5949 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005950 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005951 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5952 ProcessList.VISIBLE_APP_ADJ);
5953 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5954 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005955 }
5956
5957 // =========================================================
5958 // TASK MANAGEMENT
5959 // =========================================================
5960
5961 public List getTasks(int maxNum, int flags,
5962 IThumbnailReceiver receiver) {
5963 ArrayList list = new ArrayList();
5964
5965 PendingThumbnailsRecord pending = null;
5966 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005967 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968
5969 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005970 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005971 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5972 + ", receiver=" + receiver);
5973
5974 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5975 != PackageManager.PERMISSION_GRANTED) {
5976 if (receiver != null) {
5977 // If the caller wants to wait for pending thumbnails,
5978 // it ain't gonna get them.
5979 try {
5980 receiver.finished();
5981 } catch (RemoteException ex) {
5982 }
5983 }
5984 String msg = "Permission Denial: getTasks() from pid="
5985 + Binder.getCallingPid()
5986 + ", uid=" + Binder.getCallingUid()
5987 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005988 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005989 throw new SecurityException(msg);
5990 }
5991
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005992 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005993 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005994 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005995 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 TaskRecord curTask = null;
5997 int numActivities = 0;
5998 int numRunning = 0;
5999 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006000 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006002 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006003
6004 // Initialize state for next task if needed.
6005 if (top == null ||
6006 (top.state == ActivityState.INITIALIZING
6007 && top.task == r.task)) {
6008 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 curTask = r.task;
6010 numActivities = numRunning = 0;
6011 }
6012
6013 // Add 'r' into the current task.
6014 numActivities++;
6015 if (r.app != null && r.app.thread != null) {
6016 numRunning++;
6017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006018
Joe Onorato8a9b2202010-02-26 18:56:32 -08006019 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006020 TAG, r.intent.getComponent().flattenToShortString()
6021 + ": task=" + r.task);
6022
6023 // If the next one is a different task, generate a new
6024 // TaskInfo entry for what we have.
6025 if (next == null || next.task != curTask) {
6026 ActivityManager.RunningTaskInfo ci
6027 = new ActivityManager.RunningTaskInfo();
6028 ci.id = curTask.taskId;
6029 ci.baseActivity = r.intent.getComponent();
6030 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006031 if (top.thumbHolder != null) {
6032 ci.description = top.thumbHolder.lastDescription;
6033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006034 ci.numActivities = numActivities;
6035 ci.numRunning = numRunning;
6036 //System.out.println(
6037 // "#" + maxNum + ": " + " descr=" + ci.description);
6038 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006039 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 TAG, "State=" + top.state + "Idle=" + top.idle
6041 + " app=" + top.app
6042 + " thr=" + (top.app != null ? top.app.thread : null));
6043 if (top.state == ActivityState.RESUMED
6044 || top.state == ActivityState.PAUSING) {
6045 if (top.idle && top.app != null
6046 && top.app.thread != null) {
6047 topRecord = top;
6048 topThumbnail = top.app.thread;
6049 } else {
6050 top.thumbnailNeeded = true;
6051 }
6052 }
6053 if (pending == null) {
6054 pending = new PendingThumbnailsRecord(receiver);
6055 }
6056 pending.pendingRecords.add(top);
6057 }
6058 list.add(ci);
6059 maxNum--;
6060 top = null;
6061 }
6062 }
6063
6064 if (pending != null) {
6065 mPendingThumbnails.add(pending);
6066 }
6067 }
6068
Joe Onorato8a9b2202010-02-26 18:56:32 -08006069 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070
6071 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006072 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006073 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08006074 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006075 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006076 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006077 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 }
6079 }
6080
6081 if (pending == null && receiver != null) {
6082 // In this case all thumbnails were available and the client
6083 // is being asked to be told when the remaining ones come in...
6084 // which is unusually, since the top-most currently running
6085 // activity should never have a canned thumbnail! Oh well.
6086 try {
6087 receiver.finished();
6088 } catch (RemoteException ex) {
6089 }
6090 }
6091
6092 return list;
6093 }
6094
6095 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
6096 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006097 final int callingUid = Binder.getCallingUid();
6098 // If it's the system uid asking, then use the current user id.
6099 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
6100 // require the entire list.
6101 final int callingUserId = callingUid == Process.SYSTEM_UID
6102 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 synchronized (this) {
6104 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
6105 "getRecentTasks()");
6106
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006107 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07006108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 final int N = mRecentTasks.size();
6110 ArrayList<ActivityManager.RecentTaskInfo> res
6111 = new ArrayList<ActivityManager.RecentTaskInfo>(
6112 maxNum < N ? maxNum : N);
6113 for (int i=0; i<N && maxNum > 0; i++) {
6114 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07006115 // Only add calling user's recent tasks
6116 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07006117 // Return the entry if desired by the caller. We always return
6118 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07006119 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07006120 // not supplied RECENT_WITH_EXCLUDED and there is some reason
6121 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07006122
Dianne Hackborn905577f2011-09-07 18:31:28 -07006123 if (i == 0
6124 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 || (tr.intent == null)
6126 || ((tr.intent.getFlags()
6127 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
6128 ActivityManager.RecentTaskInfo rti
6129 = new ActivityManager.RecentTaskInfo();
6130 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08006131 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132 rti.baseIntent = new Intent(
6133 tr.intent != null ? tr.intent : tr.affinityIntent);
6134 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08006135 rti.description = tr.lastDescription;
6136
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07006137 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
6138 // Check whether this activity is currently available.
6139 try {
6140 if (rti.origActivity != null) {
6141 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
6142 continue;
6143 }
6144 } else if (rti.baseIntent != null) {
6145 if (pm.queryIntentActivities(rti.baseIntent,
6146 null, 0) == null) {
6147 continue;
6148 }
6149 }
6150 } catch (RemoteException e) {
6151 // Will never happen.
6152 }
6153 }
6154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 res.add(rti);
6156 maxNum--;
6157 }
6158 }
6159 return res;
6160 }
6161 }
6162
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006163 private TaskRecord taskForIdLocked(int id) {
6164 final int N = mRecentTasks.size();
6165 for (int i=0; i<N; i++) {
6166 TaskRecord tr = mRecentTasks.get(i);
6167 if (tr.taskId == id) {
6168 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08006169 }
6170 }
6171 return null;
6172 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006173
6174 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
6175 synchronized (this) {
6176 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
6177 "getTaskThumbnails()");
6178 TaskRecord tr = taskForIdLocked(id);
6179 if (tr != null) {
6180 return mMainStack.getTaskThumbnailsLocked(tr);
6181 }
6182 }
6183 return null;
6184 }
6185
6186 public boolean removeSubTask(int taskId, int subTaskIndex) {
6187 synchronized (this) {
6188 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
6189 "removeSubTask()");
6190 long ident = Binder.clearCallingIdentity();
6191 try {
6192 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
6193 } finally {
6194 Binder.restoreCallingIdentity(ident);
6195 }
6196 }
6197 }
6198
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006199 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006200 TaskRecord tr = root.task;
6201 Intent baseIntent = new Intent(
6202 tr.intent != null ? tr.intent : tr.affinityIntent);
6203 ComponentName component = baseIntent.getComponent();
6204 if (component == null) {
6205 Slog.w(TAG, "Now component for base intent of task: " + tr);
6206 return;
6207 }
6208
6209 // Find any running services associated with this app.
6210 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07006211 for (ServiceRecord sr : mServiceMap.getAllServices(root.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006212 if (sr.packageName.equals(component.getPackageName())) {
6213 services.add(sr);
6214 }
6215 }
6216
6217 // Take care of any running services associated with the app.
6218 for (int i=0; i<services.size(); i++) {
6219 ServiceRecord sr = services.get(i);
6220 if (sr.startRequested) {
6221 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006222 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006223 stopServiceLocked(sr);
6224 } else {
6225 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
6226 sr.makeNextStartId(), baseIntent, -1));
6227 if (sr.app != null && sr.app.thread != null) {
6228 sendServiceArgsLocked(sr, false);
6229 }
6230 }
6231 }
6232 }
6233
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006234 if (killProcesses) {
6235 // Find any running processes associated with this app.
6236 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
6237 SparseArray<ProcessRecord> appProcs
6238 = mProcessNames.getMap().get(component.getPackageName());
6239 if (appProcs != null) {
6240 for (int i=0; i<appProcs.size(); i++) {
6241 procs.add(appProcs.valueAt(i));
6242 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006243 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006244
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006245 // Kill the running processes.
6246 for (int i=0; i<procs.size(); i++) {
6247 ProcessRecord pr = procs.get(i);
6248 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
6249 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
6250 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
6251 pr.processName, pr.setAdj, "remove task");
6252 Process.killProcessQuiet(pr.pid);
6253 } else {
6254 pr.waitingToKill = "remove task";
6255 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006256 }
6257 }
6258 }
6259
6260 public boolean removeTask(int taskId, int flags) {
6261 synchronized (this) {
6262 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
6263 "removeTask()");
6264 long ident = Binder.clearCallingIdentity();
6265 try {
6266 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
6267 if (r != null) {
6268 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006269 cleanUpRemovedTaskLocked(r,
6270 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006271 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07006272 } else {
6273 TaskRecord tr = null;
6274 int i=0;
6275 while (i < mRecentTasks.size()) {
6276 TaskRecord t = mRecentTasks.get(i);
6277 if (t.taskId == taskId) {
6278 tr = t;
6279 break;
6280 }
6281 i++;
6282 }
6283 if (tr != null) {
6284 if (tr.numActivities <= 0) {
6285 // Caller is just removing a recent task that is
6286 // not actively running. That is easy!
6287 mRecentTasks.remove(i);
6288 } else {
6289 Slog.w(TAG, "removeTask: task " + taskId
6290 + " does not have activities to remove, "
6291 + " but numActivities=" + tr.numActivities
6292 + ": " + tr);
6293 }
6294 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006295 }
6296 } finally {
6297 Binder.restoreCallingIdentity(ident);
6298 }
6299 }
6300 return false;
6301 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08006302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006303 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
6304 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006305 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 TaskRecord jt = startTask;
6307
6308 // First look backwards
6309 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006310 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 if (r.task != jt) {
6312 jt = r.task;
6313 if (affinity.equals(jt.affinity)) {
6314 return j;
6315 }
6316 }
6317 }
6318
6319 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006320 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 jt = startTask;
6322 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006323 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 if (r.task != jt) {
6325 if (affinity.equals(jt.affinity)) {
6326 return j;
6327 }
6328 jt = r.task;
6329 }
6330 }
6331
6332 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006333 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 return N-1;
6335 }
6336
6337 return -1;
6338 }
6339
6340 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006341 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006343 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6345 "moveTaskToFront()");
6346
6347 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006348 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6349 Binder.getCallingUid(), "Task to front")) {
6350 return;
6351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 final long origId = Binder.clearCallingIdentity();
6353 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006354 TaskRecord tr = taskForIdLocked(task);
6355 if (tr != null) {
6356 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6357 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006359 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6360 // Caller wants the home activity moved with it. To accomplish this,
6361 // we'll just move the home task to the top first.
6362 mMainStack.moveHomeToFrontLocked();
6363 }
6364 mMainStack.moveTaskToFrontLocked(tr, null);
6365 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006367 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6368 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006370 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6371 mMainStack.mUserLeaving = true;
6372 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006373 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6374 // Caller wants the home activity moved with it. To accomplish this,
6375 // we'll just move the home task to the top first.
6376 mMainStack.moveHomeToFrontLocked();
6377 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006378 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006379 return;
6380 }
6381 }
6382 } finally {
6383 Binder.restoreCallingIdentity(origId);
6384 }
6385 }
6386 }
6387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 public void moveTaskToBack(int task) {
6389 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6390 "moveTaskToBack()");
6391
6392 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006393 if (mMainStack.mResumedActivity != null
6394 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006395 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6396 Binder.getCallingUid(), "Task to back")) {
6397 return;
6398 }
6399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006401 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 Binder.restoreCallingIdentity(origId);
6403 }
6404 }
6405
6406 /**
6407 * Moves an activity, and all of the other activities within the same task, to the bottom
6408 * of the history stack. The activity's order within the task is unchanged.
6409 *
6410 * @param token A reference to the activity we wish to move
6411 * @param nonRoot If false then this only works if the activity is the root
6412 * of a task; if true it will work for any activity in a task.
6413 * @return Returns true if the move completed, false if not.
6414 */
6415 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006416 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 synchronized(this) {
6418 final long origId = Binder.clearCallingIdentity();
6419 int taskId = getTaskForActivityLocked(token, !nonRoot);
6420 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006421 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 }
6423 Binder.restoreCallingIdentity(origId);
6424 }
6425 return false;
6426 }
6427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 public void moveTaskBackwards(int task) {
6429 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6430 "moveTaskBackwards()");
6431
6432 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006433 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6434 Binder.getCallingUid(), "Task backwards")) {
6435 return;
6436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437 final long origId = Binder.clearCallingIdentity();
6438 moveTaskBackwardsLocked(task);
6439 Binder.restoreCallingIdentity(origId);
6440 }
6441 }
6442
6443 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006444 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 }
6446
6447 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6448 synchronized(this) {
6449 return getTaskForActivityLocked(token, onlyRoot);
6450 }
6451 }
6452
6453 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006454 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 TaskRecord lastTask = null;
6456 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006457 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006458 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 if (!onlyRoot || lastTask != r.task) {
6460 return r.task.taskId;
6461 }
6462 return -1;
6463 }
6464 lastTask = r.task;
6465 }
6466
6467 return -1;
6468 }
6469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 // =========================================================
6471 // THUMBNAILS
6472 // =========================================================
6473
6474 public void reportThumbnail(IBinder token,
6475 Bitmap thumbnail, CharSequence description) {
6476 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6477 final long origId = Binder.clearCallingIdentity();
6478 sendPendingThumbnail(null, token, thumbnail, description, true);
6479 Binder.restoreCallingIdentity(origId);
6480 }
6481
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006482 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 Bitmap thumbnail, CharSequence description, boolean always) {
6484 TaskRecord task = null;
6485 ArrayList receivers = null;
6486
6487 //System.out.println("Send pending thumbnail: " + r);
6488
6489 synchronized(this) {
6490 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006491 r = mMainStack.isInStackLocked(token);
6492 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 return;
6494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006496 if (thumbnail == null && r.thumbHolder != null) {
6497 thumbnail = r.thumbHolder.lastThumbnail;
6498 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 }
6500 if (thumbnail == null && !always) {
6501 // If there is no thumbnail, and this entry is not actually
6502 // going away, then abort for now and pick up the next
6503 // thumbnail we get.
6504 return;
6505 }
6506 task = r.task;
6507
6508 int N = mPendingThumbnails.size();
6509 int i=0;
6510 while (i<N) {
6511 PendingThumbnailsRecord pr =
6512 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6513 //System.out.println("Looking in " + pr.pendingRecords);
6514 if (pr.pendingRecords.remove(r)) {
6515 if (receivers == null) {
6516 receivers = new ArrayList();
6517 }
6518 receivers.add(pr);
6519 if (pr.pendingRecords.size() == 0) {
6520 pr.finished = true;
6521 mPendingThumbnails.remove(i);
6522 N--;
6523 continue;
6524 }
6525 }
6526 i++;
6527 }
6528 }
6529
6530 if (receivers != null) {
6531 final int N = receivers.size();
6532 for (int i=0; i<N; i++) {
6533 try {
6534 PendingThumbnailsRecord pr =
6535 (PendingThumbnailsRecord)receivers.get(i);
6536 pr.receiver.newThumbnail(
6537 task != null ? task.taskId : -1, thumbnail, description);
6538 if (pr.finished) {
6539 pr.receiver.finished();
6540 }
6541 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006542 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 }
6544 }
6545 }
6546 }
6547
6548 // =========================================================
6549 // CONTENT PROVIDERS
6550 // =========================================================
6551
Jeff Brown10e89712011-07-08 18:52:57 -07006552 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6553 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006554 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006555 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006556 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006557 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006558 } catch (RemoteException ex) {
6559 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006560 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006561 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6562 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006563 if (providers != null) {
6564 final int N = providers.size();
6565 for (int i=0; i<N; i++) {
6566 ProviderInfo cpi =
6567 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07006568
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006569 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006570 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 if (cpr == null) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006572 cpr = new ContentProviderRecord(cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07006573 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006574 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006575 if (DEBUG_MU)
6576 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 app.pubProviders.put(cpi.name, cpr);
6578 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006579 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 }
6581 }
6582 return providers;
6583 }
6584
6585 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006586 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006587 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006588 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006590 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006591 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 return null;
6593 }
6594 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006595 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 == PackageManager.PERMISSION_GRANTED) {
6597 return null;
6598 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006599
6600 PathPermission[] pps = cpi.pathPermissions;
6601 if (pps != null) {
6602 int i = pps.length;
6603 while (i > 0) {
6604 i--;
6605 PathPermission pp = pps[i];
6606 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006607 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006608 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006609 return null;
6610 }
6611 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006612 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006613 == PackageManager.PERMISSION_GRANTED) {
6614 return null;
6615 }
6616 }
6617 }
6618
Dianne Hackbornb424b632010-08-18 15:59:05 -07006619 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6620 if (perms != null) {
6621 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6622 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6623 return null;
6624 }
6625 }
6626 }
6627
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006628 String msg;
6629 if (!cpi.exported) {
6630 msg = "Permission Denial: opening provider " + cpi.name
6631 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6632 + ", uid=" + callingUid + ") that is not exported from uid "
6633 + cpi.applicationInfo.uid;
6634 } else {
6635 msg = "Permission Denial: opening provider " + cpi.name
6636 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6637 + ", uid=" + callingUid + ") requires "
6638 + cpi.readPermission + " or " + cpi.writePermission;
6639 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006640 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 return msg;
6642 }
6643
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006644 boolean incProviderCount(ProcessRecord r, ContentProviderRecord cpr) {
6645 if (r != null) {
6646 Integer cnt = r.conProviders.get(cpr);
6647 if (DEBUG_PROVIDER) Slog.v(TAG,
6648 "Adding provider requested by "
6649 + r.processName + " from process "
6650 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6651 + " cnt=" + (cnt == null ? 1 : cnt));
6652 if (cnt == null) {
6653 cpr.clients.add(r);
6654 r.conProviders.put(cpr, new Integer(1));
6655 return true;
6656 } else {
6657 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6658 }
6659 } else {
6660 cpr.externals++;
6661 }
6662 return false;
6663 }
6664
6665 boolean decProviderCount(ProcessRecord r, ContentProviderRecord cpr) {
6666 if (r != null) {
6667 Integer cnt = r.conProviders.get(cpr);
6668 if (DEBUG_PROVIDER) Slog.v(TAG,
6669 "Removing provider requested by "
6670 + r.processName + " from process "
6671 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6672 + " cnt=" + cnt);
6673 if (cnt == null || cnt.intValue() <= 1) {
6674 cpr.clients.remove(r);
6675 r.conProviders.remove(cpr);
6676 return true;
6677 } else {
6678 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6679 }
6680 } else {
6681 cpr.externals++;
6682 }
6683 return false;
6684 }
6685
Amith Yamasani742a6712011-05-04 14:49:28 -07006686 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
6687 String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006688 ContentProviderRecord cpr;
6689 ProviderInfo cpi = null;
6690
6691 synchronized(this) {
6692 ProcessRecord r = null;
6693 if (caller != null) {
6694 r = getRecordForAppLocked(caller);
6695 if (r == null) {
6696 throw new SecurityException(
6697 "Unable to find app for caller " + caller
6698 + " (pid=" + Binder.getCallingPid()
6699 + ") when getting content provider " + name);
6700 }
6701 }
6702
6703 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006704 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006705 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006706 boolean providerRunning = cpr != null;
6707 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006709 String msg;
6710 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6711 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 }
6713
6714 if (r != null && cpr.canRunHere(r)) {
6715 // This provider has been published or is in the process
6716 // of being published... but it is also allowed to run
6717 // in the caller's process, so don't make a connection
6718 // and just let the caller instantiate its own instance.
6719 if (cpr.provider != null) {
6720 // don't give caller the provider object, it needs
6721 // to make its own.
6722 cpr = new ContentProviderRecord(cpr);
6723 }
6724 return cpr;
6725 }
6726
6727 final long origId = Binder.clearCallingIdentity();
6728
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006729 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 // return it right away.
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006731 final boolean countChanged = incProviderCount(r, cpr);
6732 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006733 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006734 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006735 // make sure to count it as being accessed and thus
6736 // back up on the LRU list. This is good because
6737 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006738 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006739 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006740 }
6741
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006742 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006743 if (false) {
6744 if (cpr.name.flattenToShortString().equals(
6745 "com.android.providers.calendar/.CalendarProvider2")) {
6746 Slog.v(TAG, "****************** KILLING "
6747 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006748 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006749 }
6750 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006751 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006752 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6753 // NOTE: there is still a race here where a signal could be
6754 // pending on the process even though we managed to update its
6755 // adj level. Not sure what to do about this, but at least
6756 // the race is now smaller.
6757 if (!success) {
6758 // Uh oh... it looks like the provider's process
6759 // has been killed on us. We need to wait for a new
6760 // process to be started, and make sure its death
6761 // doesn't kill our process.
6762 Slog.i(TAG,
6763 "Existing provider " + cpr.name.flattenToShortString()
6764 + " is crashing; detaching " + r);
6765 boolean lastRef = decProviderCount(r, cpr);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006766 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006767 if (!lastRef) {
6768 // This wasn't the last ref our process had on
6769 // the provider... we have now been killed, bail.
6770 return null;
6771 }
6772 providerRunning = false;
6773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 }
6775
6776 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006779 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006780 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006781 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006782 resolveContentProvider(name,
6783 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006784 } catch (RemoteException ex) {
6785 }
6786 if (cpi == null) {
6787 return null;
6788 }
6789
Amith Yamasani742a6712011-05-04 14:49:28 -07006790 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
6791 Binder.getOrigCallingUser());
6792
Dianne Hackbornb424b632010-08-18 15:59:05 -07006793 String msg;
6794 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6795 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 }
6797
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006798 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006799 && !cpi.processName.equals("system")) {
6800 // If this content provider does not run in the system
6801 // process, and the system is not yet ready to run other
6802 // processes, then fail fast instead of hanging.
6803 throw new IllegalArgumentException(
6804 "Attempt to launch content provider before system ready");
6805 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006806
6807 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006808 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 final boolean firstClass = cpr == null;
6810 if (firstClass) {
6811 try {
6812 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006813 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006814 getApplicationInfo(
6815 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006816 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006817 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006818 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006819 + cpi.name);
6820 return null;
6821 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006822 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006823 cpr = new ContentProviderRecord(cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006824 } catch (RemoteException ex) {
6825 // pm is in same process, this will never happen.
6826 }
6827 }
6828
6829 if (r != null && cpr.canRunHere(r)) {
6830 // If this is a multiprocess provider, then just return its
6831 // info and allow the caller to instantiate it. Only do
6832 // this if the provider is the same user as the caller's
6833 // process, or can run as root (so can be in any process).
6834 return cpr;
6835 }
6836
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006837 if (DEBUG_PROVIDER) {
6838 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006839 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006840 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006841 }
6842
6843 // This is single process, and our app is now connecting to it.
6844 // See if we are already in the process of launching this
6845 // provider.
6846 final int N = mLaunchingProviders.size();
6847 int i;
6848 for (i=0; i<N; i++) {
6849 if (mLaunchingProviders.get(i) == cpr) {
6850 break;
6851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006852 }
6853
6854 // If the provider is not already being launched, then get it
6855 // started.
6856 if (i >= N) {
6857 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006858
6859 try {
6860 // Content provider is now in use, its package can't be stopped.
6861 try {
6862 AppGlobals.getPackageManager().setPackageStoppedState(
6863 cpr.appInfo.packageName, false);
6864 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006865 } catch (IllegalArgumentException e) {
6866 Slog.w(TAG, "Failed trying to unstop package "
6867 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006868 }
6869
6870 ProcessRecord proc = startProcessLocked(cpi.processName,
6871 cpr.appInfo, false, 0, "content provider",
6872 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006873 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006874 if (proc == null) {
6875 Slog.w(TAG, "Unable to launch app "
6876 + cpi.applicationInfo.packageName + "/"
6877 + cpi.applicationInfo.uid + " for provider "
6878 + name + ": process is bad");
6879 return null;
6880 }
6881 cpr.launchingApp = proc;
6882 mLaunchingProviders.add(cpr);
6883 } finally {
6884 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 }
6887
6888 // Make sure the provider is published (the same provider class
6889 // may be published under multiple names).
6890 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006891 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006892 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006893 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006894 incProviderCount(r, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006895 }
6896 }
6897
6898 // Wait for the provider to be published...
6899 synchronized (cpr) {
6900 while (cpr.provider == null) {
6901 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006902 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 + cpi.applicationInfo.packageName + "/"
6904 + cpi.applicationInfo.uid + " for provider "
6905 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006906 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006907 cpi.applicationInfo.packageName,
6908 cpi.applicationInfo.uid, name);
6909 return null;
6910 }
6911 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006912 if (DEBUG_MU) {
6913 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6914 + cpr.launchingApp);
6915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006916 cpr.wait();
6917 } catch (InterruptedException ex) {
6918 }
6919 }
6920 }
6921 return cpr;
6922 }
6923
6924 public final ContentProviderHolder getContentProvider(
6925 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006926 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 if (caller == null) {
6928 String msg = "null IApplicationThread when getting content provider "
6929 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006930 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006931 throw new SecurityException(msg);
6932 }
6933
Amith Yamasani742a6712011-05-04 14:49:28 -07006934 ContentProviderHolder contentProvider = getContentProviderImpl(caller, name);
6935 return contentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006936 }
6937
6938 private ContentProviderHolder getContentProviderExternal(String name) {
6939 return getContentProviderImpl(null, name);
6940 }
6941
6942 /**
6943 * Drop a content provider from a ProcessRecord's bookkeeping
6944 * @param cpr
6945 */
6946 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006947 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006949 int userId = UserId.getUserId(Binder.getCallingUid());
6950 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006952 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006953 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006954 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006955 return;
6956 }
6957 final ProcessRecord r = getRecordForAppLocked(caller);
6958 if (r == null) {
6959 throw new SecurityException(
6960 "Unable to find app for caller " + caller +
6961 " when removing content provider " + name);
6962 }
6963 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006964 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006965 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6966 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6967 + r.info.processName + " from process "
6968 + localCpr.appInfo.processName);
6969 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006970 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006971 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006972 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973 return;
6974 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006975 if (decProviderCount(r, localCpr)) {
6976 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006979 }
6980 }
6981
6982 private void removeContentProviderExternal(String name) {
6983 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006984 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6985 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006986 if(cpr == null) {
6987 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006988 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006989 return;
6990 }
6991
6992 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006993 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006994 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6995 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006996 localCpr.externals--;
6997 if (localCpr.externals < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006998 Slog.e(TAG, "Externals < 0 for content provider " + localCpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006999 }
7000 updateOomAdjLocked();
7001 }
7002 }
7003
7004 public final void publishContentProviders(IApplicationThread caller,
7005 List<ContentProviderHolder> providers) {
7006 if (providers == null) {
7007 return;
7008 }
7009
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007010 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 synchronized(this) {
7012 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07007013 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007014 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 if (r == null) {
7016 throw new SecurityException(
7017 "Unable to find app for caller " + caller
7018 + " (pid=" + Binder.getCallingPid()
7019 + ") when publishing content providers");
7020 }
7021
7022 final long origId = Binder.clearCallingIdentity();
7023
7024 final int N = providers.size();
7025 for (int i=0; i<N; i++) {
7026 ContentProviderHolder src = providers.get(i);
7027 if (src == null || src.info == null || src.provider == null) {
7028 continue;
7029 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07007030 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07007031 if (DEBUG_MU)
7032 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007033 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07007034 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07007035 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007036 String names[] = dst.info.authority.split(";");
7037 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07007038 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007039 }
7040
7041 int NL = mLaunchingProviders.size();
7042 int j;
7043 for (j=0; j<NL; j++) {
7044 if (mLaunchingProviders.get(j) == dst) {
7045 mLaunchingProviders.remove(j);
7046 j--;
7047 NL--;
7048 }
7049 }
7050 synchronized (dst) {
7051 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07007052 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 dst.notifyAll();
7054 }
7055 updateOomAdjLocked(r);
7056 }
7057 }
7058
7059 Binder.restoreCallingIdentity(origId);
7060 }
7061 }
7062
7063 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07007064 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06007065 synchronized (mSelf) {
7066 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
7067 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08007068 if (providers != null) {
7069 for (int i=providers.size()-1; i>=0; i--) {
7070 ProviderInfo pi = (ProviderInfo)providers.get(i);
7071 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7072 Slog.w(TAG, "Not installing system proc provider " + pi.name
7073 + ": not system .apk");
7074 providers.remove(i);
7075 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08007076 }
7077 }
7078 }
Josh Bartel2ecce342010-02-25 10:55:48 -06007079 if (providers != null) {
7080 mSystemThread.installSystemProviders(providers);
7081 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007082
7083 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01007084
7085 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007086 }
7087
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007088 /**
7089 * Allows app to retrieve the MIME type of a URI without having permission
7090 * to access its content provider.
7091 *
7092 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
7093 *
7094 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
7095 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
7096 */
7097 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007098 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007099 final String name = uri.getAuthority();
7100 final long ident = Binder.clearCallingIdentity();
7101 ContentProviderHolder holder = null;
7102
7103 try {
7104 holder = getContentProviderExternal(name);
7105 if (holder != null) {
7106 return holder.provider.getType(uri);
7107 }
7108 } catch (RemoteException e) {
7109 Log.w(TAG, "Content provider dead retrieving " + uri, e);
7110 return null;
7111 } finally {
7112 if (holder != null) {
7113 removeContentProviderExternal(name);
7114 }
7115 Binder.restoreCallingIdentity(ident);
7116 }
7117
7118 return null;
7119 }
7120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007121 // =========================================================
7122 // GLOBAL MANAGEMENT
7123 // =========================================================
7124
7125 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007126 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007127 String proc = customProcess != null ? customProcess : info.processName;
7128 BatteryStatsImpl.Uid.Proc ps = null;
7129 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007130 int uid = info.uid;
7131 if (isolated) {
7132 int userId = UserId.getUserId(uid);
7133 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
7134 uid = 0;
7135 while (true) {
7136 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
7137 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
7138 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
7139 }
7140 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
7141 mNextIsolatedProcessUid++;
7142 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
7143 // No process for this uid, use it.
7144 break;
7145 }
7146 stepsLeft--;
7147 if (stepsLeft <= 0) {
7148 return null;
7149 }
7150 }
7151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007152 synchronized (stats) {
7153 ps = stats.getProcessStatsLocked(info.uid, proc);
7154 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007155 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007156 }
7157
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007158 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
7159 ProcessRecord app;
7160 if (!isolated) {
7161 app = getProcessRecordLocked(info.processName, info.uid);
7162 } else {
7163 app = null;
7164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007165
7166 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007167 app = newProcessRecordLocked(null, info, null, isolated);
7168 mProcessNames.put(info.processName, app.uid, app);
7169 if (isolated) {
7170 mIsolatedProcesses.put(app.uid, app);
7171 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007172 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007173 }
7174
Dianne Hackborne7f97212011-02-24 14:40:20 -08007175 // This package really, really can not be stopped.
7176 try {
7177 AppGlobals.getPackageManager().setPackageStoppedState(
7178 info.packageName, false);
7179 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007180 } catch (IllegalArgumentException e) {
7181 Slog.w(TAG, "Failed trying to unstop package "
7182 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007183 }
7184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007185 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7186 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7187 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007188 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007189 }
7190 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7191 mPersistentStartingProcesses.add(app);
7192 startProcessLocked(app, "added application", app.processName);
7193 }
7194
7195 return app;
7196 }
7197
7198 public void unhandledBack() {
7199 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7200 "unhandledBack()");
7201
7202 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007203 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007204 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 TAG, "Performing unhandledBack(): stack size = " + count);
7206 if (count > 1) {
7207 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007208 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007209 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
7210 Binder.restoreCallingIdentity(origId);
7211 }
7212 }
7213 }
7214
7215 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007216 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007217 String name = uri.getAuthority();
7218 ContentProviderHolder cph = getContentProviderExternal(name);
7219 ParcelFileDescriptor pfd = null;
7220 if (cph != null) {
7221 // We record the binder invoker's uid in thread-local storage before
7222 // going to the content provider to open the file. Later, in the code
7223 // that handles all permissions checks, we look for this uid and use
7224 // that rather than the Activity Manager's own uid. The effect is that
7225 // we do the check against the caller's permissions even though it looks
7226 // to the content provider like the Activity Manager itself is making
7227 // the request.
7228 sCallerIdentity.set(new Identity(
7229 Binder.getCallingPid(), Binder.getCallingUid()));
7230 try {
7231 pfd = cph.provider.openFile(uri, "r");
7232 } catch (FileNotFoundException e) {
7233 // do nothing; pfd will be returned null
7234 } finally {
7235 // Ensure that whatever happens, we clean up the identity state
7236 sCallerIdentity.remove();
7237 }
7238
7239 // We've got the fd now, so we're done with the provider.
7240 removeContentProviderExternal(name);
7241 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007242 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007243 }
7244 return pfd;
7245 }
7246
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007247 // Actually is sleeping or shutting down or whatever else in the future
7248 // is an inactive state.
7249 public boolean isSleeping() {
7250 return mSleeping || mShuttingDown;
7251 }
7252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007253 public void goingToSleep() {
7254 synchronized(this) {
7255 mSleeping = true;
7256 mWindowManager.setEventDispatching(false);
7257
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007258 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007259
7260 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07007261 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007262 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7263 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07007264 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 }
7266 }
7267
Dianne Hackborn55280a92009-05-07 15:53:46 -07007268 public boolean shutdown(int timeout) {
7269 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7270 != PackageManager.PERMISSION_GRANTED) {
7271 throw new SecurityException("Requires permission "
7272 + android.Manifest.permission.SHUTDOWN);
7273 }
7274
7275 boolean timedout = false;
7276
7277 synchronized(this) {
7278 mShuttingDown = true;
7279 mWindowManager.setEventDispatching(false);
7280
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007281 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007282 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007283 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007284 while (mMainStack.mResumedActivity != null
Dianne Hackborncbb722e2012-02-07 18:33:49 -08007285 || mMainStack.mPausingActivities.size() > 0) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007286 long delay = endTime - System.currentTimeMillis();
7287 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007288 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007289 timedout = true;
7290 break;
7291 }
7292 try {
7293 this.wait();
7294 } catch (InterruptedException e) {
7295 }
7296 }
7297 }
7298 }
7299
7300 mUsageStatsService.shutdown();
7301 mBatteryStatsService.shutdown();
7302
7303 return timedout;
7304 }
7305
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007306 public final void activitySlept(IBinder token) {
7307 if (localLOGV) Slog.v(
7308 TAG, "Activity slept: token=" + token);
7309
7310 ActivityRecord r = null;
7311
7312 final long origId = Binder.clearCallingIdentity();
7313
7314 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007315 r = mMainStack.isInStackLocked(token);
7316 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007317 mMainStack.activitySleptLocked(r);
7318 }
7319 }
7320
7321 Binder.restoreCallingIdentity(origId);
7322 }
7323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007324 public void wakingUp() {
7325 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 mWindowManager.setEventDispatching(true);
7327 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007328 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007329 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 }
7331 }
7332
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007333 public void stopAppSwitches() {
7334 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7335 != PackageManager.PERMISSION_GRANTED) {
7336 throw new SecurityException("Requires permission "
7337 + android.Manifest.permission.STOP_APP_SWITCHES);
7338 }
7339
7340 synchronized(this) {
7341 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7342 + APP_SWITCH_DELAY_TIME;
7343 mDidAppSwitch = false;
7344 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7345 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7346 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7347 }
7348 }
7349
7350 public void resumeAppSwitches() {
7351 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7352 != PackageManager.PERMISSION_GRANTED) {
7353 throw new SecurityException("Requires permission "
7354 + android.Manifest.permission.STOP_APP_SWITCHES);
7355 }
7356
7357 synchronized(this) {
7358 // Note that we don't execute any pending app switches... we will
7359 // let those wait until either the timeout, or the next start
7360 // activity request.
7361 mAppSwitchesAllowedTime = 0;
7362 }
7363 }
7364
7365 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7366 String name) {
7367 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7368 return true;
7369 }
7370
7371 final int perm = checkComponentPermission(
7372 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007373 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007374 if (perm == PackageManager.PERMISSION_GRANTED) {
7375 return true;
7376 }
7377
Joe Onorato8a9b2202010-02-26 18:56:32 -08007378 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007379 return false;
7380 }
7381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007382 public void setDebugApp(String packageName, boolean waitForDebugger,
7383 boolean persistent) {
7384 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7385 "setDebugApp()");
7386
7387 // Note that this is not really thread safe if there are multiple
7388 // callers into it at the same time, but that's not a situation we
7389 // care about.
7390 if (persistent) {
7391 final ContentResolver resolver = mContext.getContentResolver();
7392 Settings.System.putString(
7393 resolver, Settings.System.DEBUG_APP,
7394 packageName);
7395 Settings.System.putInt(
7396 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7397 waitForDebugger ? 1 : 0);
7398 }
7399
7400 synchronized (this) {
7401 if (!persistent) {
7402 mOrigDebugApp = mDebugApp;
7403 mOrigWaitForDebugger = mWaitForDebugger;
7404 }
7405 mDebugApp = packageName;
7406 mWaitForDebugger = waitForDebugger;
7407 mDebugTransient = !persistent;
7408 if (packageName != null) {
7409 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07007410 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007411 Binder.restoreCallingIdentity(origId);
7412 }
7413 }
7414 }
7415
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007416 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7417 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7418 synchronized (this) {
7419 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7420 if (!isDebuggable) {
7421 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7422 throw new SecurityException("Process not debuggable: " + app.packageName);
7423 }
7424 }
7425 mProfileApp = processName;
7426 mProfileFile = profileFile;
7427 if (mProfileFd != null) {
7428 try {
7429 mProfileFd.close();
7430 } catch (IOException e) {
7431 }
7432 mProfileFd = null;
7433 }
7434 mProfileFd = profileFd;
7435 mProfileType = 0;
7436 mAutoStopProfiler = autoStopProfiler;
7437 }
7438 }
7439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007440 public void setAlwaysFinish(boolean enabled) {
7441 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7442 "setAlwaysFinish()");
7443
7444 Settings.System.putInt(
7445 mContext.getContentResolver(),
7446 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7447
7448 synchronized (this) {
7449 mAlwaysFinishActivities = enabled;
7450 }
7451 }
7452
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007453 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007454 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007455 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007456 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007457 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007458 }
7459 }
7460
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007461 public boolean isUserAMonkey() {
7462 // For now the fact that there is a controller implies
7463 // we have a monkey.
7464 synchronized (this) {
7465 return mController != null;
7466 }
7467 }
7468
Jeff Sharkeya4620792011-05-20 15:29:23 -07007469 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007470 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7471 "registerProcessObserver()");
7472 synchronized (this) {
7473 mProcessObservers.register(observer);
7474 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007475 }
7476
7477 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007478 synchronized (this) {
7479 mProcessObservers.unregister(observer);
7480 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007481 }
7482
Daniel Sandler69a48172010-06-23 16:29:36 -04007483 public void setImmersive(IBinder token, boolean immersive) {
7484 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007485 ActivityRecord r = mMainStack.isInStackLocked(token);
7486 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007487 throw new IllegalArgumentException();
7488 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007489 r.immersive = immersive;
7490 }
7491 }
7492
7493 public boolean isImmersive(IBinder token) {
7494 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007495 ActivityRecord r = mMainStack.isInStackLocked(token);
7496 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007497 throw new IllegalArgumentException();
7498 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007499 return r.immersive;
7500 }
7501 }
7502
7503 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007504 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007505 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007506 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007507 return (r != null) ? r.immersive : false;
7508 }
7509 }
7510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007511 public final void enterSafeMode() {
7512 synchronized(this) {
7513 // It only makes sense to do this before the system is ready
7514 // and started launching other packages.
7515 if (!mSystemReady) {
7516 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007517 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007518 } catch (RemoteException e) {
7519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 }
7521 }
7522 }
7523
Jeff Brownb09abc12011-01-13 21:08:27 -08007524 public final void showSafeModeOverlay() {
7525 View v = LayoutInflater.from(mContext).inflate(
7526 com.android.internal.R.layout.safe_mode, null);
7527 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7528 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7529 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7530 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7531 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7532 lp.format = v.getBackground().getOpacity();
7533 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7534 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7535 ((WindowManager)mContext.getSystemService(
7536 Context.WINDOW_SERVICE)).addView(v, lp);
7537 }
7538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 public void noteWakeupAlarm(IIntentSender sender) {
7540 if (!(sender instanceof PendingIntentRecord)) {
7541 return;
7542 }
7543 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7544 synchronized (stats) {
7545 if (mBatteryStatsService.isOnBattery()) {
7546 mBatteryStatsService.enforceCallingPermission();
7547 PendingIntentRecord rec = (PendingIntentRecord)sender;
7548 int MY_UID = Binder.getCallingUid();
7549 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7550 BatteryStatsImpl.Uid.Pkg pkg =
7551 stats.getPackageStatsLocked(uid, rec.key.packageName);
7552 pkg.incWakeupsLocked();
7553 }
7554 }
7555 }
7556
Dianne Hackborn64825172011-03-02 21:32:58 -08007557 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007558 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007559 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007561 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 // XXX Note: don't acquire main activity lock here, because the window
7563 // manager calls in with its locks held.
7564
7565 boolean killed = false;
7566 synchronized (mPidsSelfLocked) {
7567 int[] types = new int[pids.length];
7568 int worstType = 0;
7569 for (int i=0; i<pids.length; i++) {
7570 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7571 if (proc != null) {
7572 int type = proc.setAdj;
7573 types[i] = type;
7574 if (type > worstType) {
7575 worstType = type;
7576 }
7577 }
7578 }
7579
Dianne Hackborn64825172011-03-02 21:32:58 -08007580 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007582 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7583 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007584 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007586
7587 // If this is not a secure call, don't let it kill processes that
7588 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007589 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7590 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007591 }
7592
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007593 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 for (int i=0; i<pids.length; i++) {
7595 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7596 if (proc == null) {
7597 continue;
7598 }
7599 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007600 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007601 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007602 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7603 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007604 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007605 proc.killedBackground = true;
7606 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007607 }
7608 }
7609 }
7610 return killed;
7611 }
7612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613 public final void startRunning(String pkg, String cls, String action,
7614 String data) {
7615 synchronized(this) {
7616 if (mStartRunning) {
7617 return;
7618 }
7619 mStartRunning = true;
7620 mTopComponent = pkg != null && cls != null
7621 ? new ComponentName(pkg, cls) : null;
7622 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7623 mTopData = data;
7624 if (!mSystemReady) {
7625 return;
7626 }
7627 }
7628
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007629 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007630 }
7631
7632 private void retrieveSettings() {
7633 final ContentResolver resolver = mContext.getContentResolver();
7634 String debugApp = Settings.System.getString(
7635 resolver, Settings.System.DEBUG_APP);
7636 boolean waitForDebugger = Settings.System.getInt(
7637 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7638 boolean alwaysFinishActivities = Settings.System.getInt(
7639 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7640
7641 Configuration configuration = new Configuration();
7642 Settings.System.getConfiguration(resolver, configuration);
7643
7644 synchronized (this) {
7645 mDebugApp = mOrigDebugApp = debugApp;
7646 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7647 mAlwaysFinishActivities = alwaysFinishActivities;
7648 // This happens before any activities are started, so we can
7649 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007650 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007651 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 }
7653 }
7654
7655 public boolean testIsSystemReady() {
7656 // no need to synchronize(this) just to read & return the value
7657 return mSystemReady;
7658 }
7659
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007660 private static File getCalledPreBootReceiversFile() {
7661 File dataDir = Environment.getDataDirectory();
7662 File systemDir = new File(dataDir, "system");
7663 File fname = new File(systemDir, "called_pre_boots.dat");
7664 return fname;
7665 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007666
7667 static final int LAST_DONE_VERSION = 10000;
7668
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007669 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7670 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7671 File file = getCalledPreBootReceiversFile();
7672 FileInputStream fis = null;
7673 try {
7674 fis = new FileInputStream(file);
7675 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007676 int fvers = dis.readInt();
7677 if (fvers == LAST_DONE_VERSION) {
7678 String vers = dis.readUTF();
7679 String codename = dis.readUTF();
7680 String build = dis.readUTF();
7681 if (android.os.Build.VERSION.RELEASE.equals(vers)
7682 && android.os.Build.VERSION.CODENAME.equals(codename)
7683 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7684 int num = dis.readInt();
7685 while (num > 0) {
7686 num--;
7687 String pkg = dis.readUTF();
7688 String cls = dis.readUTF();
7689 lastDoneReceivers.add(new ComponentName(pkg, cls));
7690 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007691 }
7692 }
7693 } catch (FileNotFoundException e) {
7694 } catch (IOException e) {
7695 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7696 } finally {
7697 if (fis != null) {
7698 try {
7699 fis.close();
7700 } catch (IOException e) {
7701 }
7702 }
7703 }
7704 return lastDoneReceivers;
7705 }
7706
7707 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7708 File file = getCalledPreBootReceiversFile();
7709 FileOutputStream fos = null;
7710 DataOutputStream dos = null;
7711 try {
7712 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7713 fos = new FileOutputStream(file);
7714 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007715 dos.writeInt(LAST_DONE_VERSION);
7716 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007717 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007718 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007719 dos.writeInt(list.size());
7720 for (int i=0; i<list.size(); i++) {
7721 dos.writeUTF(list.get(i).getPackageName());
7722 dos.writeUTF(list.get(i).getClassName());
7723 }
7724 } catch (IOException e) {
7725 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7726 file.delete();
7727 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007728 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007729 if (dos != null) {
7730 try {
7731 dos.close();
7732 } catch (IOException e) {
7733 // TODO Auto-generated catch block
7734 e.printStackTrace();
7735 }
7736 }
7737 }
7738 }
7739
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007740 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 synchronized(this) {
7742 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007743 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007744 return;
7745 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007746
7747 // Check to see if there are any update receivers to run.
7748 if (!mDidUpdate) {
7749 if (mWaitingUpdate) {
7750 return;
7751 }
7752 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7753 List<ResolveInfo> ris = null;
7754 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007755 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007756 intent, null, 0);
7757 } catch (RemoteException e) {
7758 }
7759 if (ris != null) {
7760 for (int i=ris.size()-1; i>=0; i--) {
7761 if ((ris.get(i).activityInfo.applicationInfo.flags
7762 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7763 ris.remove(i);
7764 }
7765 }
7766 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007767
7768 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7769
7770 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007771 for (int i=0; i<ris.size(); i++) {
7772 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007773 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7774 if (lastDoneReceivers.contains(comp)) {
7775 ris.remove(i);
7776 i--;
7777 }
7778 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007779
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007780 for (int i=0; i<ris.size(); i++) {
7781 ActivityInfo ai = ris.get(i).activityInfo;
7782 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7783 doneReceivers.add(comp);
7784 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007785 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007786 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007787 finisher = new IIntentReceiver.Stub() {
7788 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007789 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007790 boolean sticky) {
7791 // The raw IIntentReceiver interface is called
7792 // with the AM lock held, so redispatch to
7793 // execute our code without the lock.
7794 mHandler.post(new Runnable() {
7795 public void run() {
7796 synchronized (ActivityManagerService.this) {
7797 mDidUpdate = true;
7798 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007799 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007800 showBootMessage(mContext.getText(
7801 R.string.android_upgrading_complete),
7802 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007803 systemReady(goingCallback);
7804 }
7805 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007806 }
7807 };
7808 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007809 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007810 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007811 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007812 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7813 Process.SYSTEM_UID);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007814 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007815 mWaitingUpdate = true;
7816 }
7817 }
7818 }
7819 if (mWaitingUpdate) {
7820 return;
7821 }
7822 mDidUpdate = true;
7823 }
7824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007825 mSystemReady = true;
7826 if (!mStartRunning) {
7827 return;
7828 }
7829 }
7830
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007831 ArrayList<ProcessRecord> procsToKill = null;
7832 synchronized(mPidsSelfLocked) {
7833 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7834 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7835 if (!isAllowedWhileBooting(proc.info)){
7836 if (procsToKill == null) {
7837 procsToKill = new ArrayList<ProcessRecord>();
7838 }
7839 procsToKill.add(proc);
7840 }
7841 }
7842 }
7843
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007844 synchronized(this) {
7845 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007846 for (int i=procsToKill.size()-1; i>=0; i--) {
7847 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007848 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007849 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007850 }
7851 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007852
7853 // Now that we have cleaned up any update processes, we
7854 // are ready to start launching real processes and know that
7855 // we won't trample on them any more.
7856 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007857 }
7858
Joe Onorato8a9b2202010-02-26 18:56:32 -08007859 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007860 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 SystemClock.uptimeMillis());
7862
7863 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007864 // Make sure we have no pre-ready processes sitting around.
7865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007866 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7867 ResolveInfo ri = mContext.getPackageManager()
7868 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007869 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007870 CharSequence errorMsg = null;
7871 if (ri != null) {
7872 ActivityInfo ai = ri.activityInfo;
7873 ApplicationInfo app = ai.applicationInfo;
7874 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7875 mTopAction = Intent.ACTION_FACTORY_TEST;
7876 mTopData = null;
7877 mTopComponent = new ComponentName(app.packageName,
7878 ai.name);
7879 } else {
7880 errorMsg = mContext.getResources().getText(
7881 com.android.internal.R.string.factorytest_not_system);
7882 }
7883 } else {
7884 errorMsg = mContext.getResources().getText(
7885 com.android.internal.R.string.factorytest_no_action);
7886 }
7887 if (errorMsg != null) {
7888 mTopAction = null;
7889 mTopData = null;
7890 mTopComponent = null;
7891 Message msg = Message.obtain();
7892 msg.what = SHOW_FACTORY_ERROR_MSG;
7893 msg.getData().putCharSequence("msg", errorMsg);
7894 mHandler.sendMessage(msg);
7895 }
7896 }
7897 }
7898
7899 retrieveSettings();
7900
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007901 if (goingCallback != null) goingCallback.run();
7902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 synchronized (this) {
7904 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7905 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007906 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007907 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007908 if (apps != null) {
7909 int N = apps.size();
7910 int i;
7911 for (i=0; i<N; i++) {
7912 ApplicationInfo info
7913 = (ApplicationInfo)apps.get(i);
7914 if (info != null &&
7915 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007916 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 }
7918 }
7919 }
7920 } catch (RemoteException ex) {
7921 // pm is in same process, this will never happen.
7922 }
7923 }
7924
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007925 // Start up initial activity.
7926 mBooting = true;
7927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007928 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007929 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007930 Message msg = Message.obtain();
7931 msg.what = SHOW_UID_ERROR_MSG;
7932 mHandler.sendMessage(msg);
7933 }
7934 } catch (RemoteException e) {
7935 }
7936
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007937 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007938 }
7939 }
7940
Dan Egnorb7f03672009-12-09 16:22:32 -08007941 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007942 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007943 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007944 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007945 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007946 startAppProblemLocked(app);
7947 app.stopFreezingAllLocked();
7948 return handleAppCrashLocked(app);
7949 }
7950
Dan Egnorb7f03672009-12-09 16:22:32 -08007951 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007952 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007954 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007955 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7956 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 startAppProblemLocked(app);
7958 app.stopFreezingAllLocked();
7959 }
7960
7961 /**
7962 * Generate a process error record, suitable for attachment to a ProcessRecord.
7963 *
7964 * @param app The ProcessRecord in which the error occurred.
7965 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7966 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007967 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 * @param shortMsg Short message describing the crash.
7969 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007970 * @param stackTrace Full crash stack trace, may be null.
7971 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 * @return Returns a fully-formed AppErrorStateInfo record.
7973 */
7974 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007975 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007976 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007978 report.condition = condition;
7979 report.processName = app.processName;
7980 report.pid = app.pid;
7981 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007982 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 report.shortMsg = shortMsg;
7984 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007985 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986
7987 return report;
7988 }
7989
Dan Egnor42471dd2010-01-07 17:25:22 -08007990 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 synchronized (this) {
7992 app.crashing = false;
7993 app.crashingReport = null;
7994 app.notResponding = false;
7995 app.notRespondingReport = null;
7996 if (app.anrDialog == fromDialog) {
7997 app.anrDialog = null;
7998 }
7999 if (app.waitDialog == fromDialog) {
8000 app.waitDialog = null;
8001 }
8002 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008003 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008004 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07008005 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
8006 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008007 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009 }
8010 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008011
Dan Egnorb7f03672009-12-09 16:22:32 -08008012 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008013 long now = SystemClock.uptimeMillis();
8014
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008015 Long crashTime;
8016 if (!app.isolated) {
8017 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
8018 } else {
8019 crashTime = null;
8020 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07008021 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008022 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008023 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008025 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008026 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008027 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
8028 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008029 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008030 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008032 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 }
8034 }
8035 if (!app.persistent) {
8036 // We don't want to start this process again until the user
8037 // explicitly does so... but for persistent process, we really
8038 // need to keep it running. If a persistent process is actually
8039 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008040 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008041 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008042 if (!app.isolated) {
8043 // XXX We don't have a way to mark isolated processes
8044 // as bad, since they don't have a peristent identity.
8045 mBadProcesses.put(app.info.processName, app.uid, now);
8046 mProcessCrashTimes.remove(app.info.processName, app.uid);
8047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008048 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008050 // Don't let services in this process be restarted and potentially
8051 // annoy the user repeatedly. Unless it is persistent, since those
8052 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008053 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008054 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008055 return false;
8056 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008057 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008058 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008059 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008060 if (r.app == app) {
8061 // If the top running activity is from this crashing
8062 // process, then terminate it to avoid getting in a loop.
8063 Slog.w(TAG, " Force finishing activity "
8064 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008065 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008066 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008067 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08008068 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008069 // stopped, to avoid a situation where one will get
8070 // re-start our crashing activity once it gets resumed again.
8071 index--;
8072 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008073 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008074 if (r.state == ActivityState.RESUMED
8075 || r.state == ActivityState.PAUSING
8076 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008077 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008078 Slog.w(TAG, " Force finishing activity "
8079 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008080 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008081 Activity.RESULT_CANCELED, null, "crashed");
8082 }
8083 }
8084 }
8085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008086 }
8087
8088 // Bump up the crash count of any services currently running in the proc.
8089 if (app.services.size() != 0) {
8090 // Any services running in the application need to be placed
8091 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008092 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008093 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008094 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 sr.crashCount++;
8096 }
8097 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008098
8099 // If the crashing process is what we consider to be the "home process" and it has been
8100 // replaced by a third-party app, clear the package preferred activities from packages
8101 // with a home activity running in the process to prevent a repeatedly crashing app
8102 // from blocking the user to manually clear the list.
8103 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8104 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8105 Iterator it = mHomeProcess.activities.iterator();
8106 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008107 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008108 if (r.isHomeActivity) {
8109 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8110 try {
8111 ActivityThread.getPackageManager()
8112 .clearPackagePreferredActivities(r.packageName);
8113 } catch (RemoteException c) {
8114 // pm is in same process, this will never happen.
8115 }
8116 }
8117 }
8118 }
8119
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008120 if (!app.isolated) {
8121 // XXX Can't keep track of crash times for isolated processes,
8122 // because they don't have a perisistent identity.
8123 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8124 }
8125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008126 return true;
8127 }
8128
8129 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008130 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8131 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008132 skipCurrentReceiverLocked(app);
8133 }
8134
8135 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008136 for (BroadcastQueue queue : mBroadcastQueues) {
8137 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 }
8139 }
8140
Dan Egnor60d87622009-12-16 16:32:58 -08008141 /**
8142 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8143 * The application process will exit immediately after this call returns.
8144 * @param app object of the crashing app, null for the system server
8145 * @param crashInfo describing the exception
8146 */
8147 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008148 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008149 final String processName = app == null ? "system_server"
8150 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008151
8152 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008153 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008154 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008155 crashInfo.exceptionClassName,
8156 crashInfo.exceptionMessage,
8157 crashInfo.throwFileName,
8158 crashInfo.throwLineNumber);
8159
Jeff Sharkeya353d262011-10-28 11:12:06 -07008160 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008161
8162 crashApplication(r, crashInfo);
8163 }
8164
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008165 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008166 IBinder app,
8167 int violationMask,
8168 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008169 ProcessRecord r = findAppProcess(app, "StrictMode");
8170 if (r == null) {
8171 return;
8172 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008173
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008174 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008175 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008176 boolean logIt = true;
8177 synchronized (mAlreadyLoggedViolatedStacks) {
8178 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8179 logIt = false;
8180 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008181 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008182 // the relative pain numbers, without logging all
8183 // the stack traces repeatedly. We'd want to do
8184 // likewise in the client code, which also does
8185 // dup suppression, before the Binder call.
8186 } else {
8187 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8188 mAlreadyLoggedViolatedStacks.clear();
8189 }
8190 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8191 }
8192 }
8193 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008194 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008195 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008196 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008197
8198 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8199 AppErrorResult result = new AppErrorResult();
8200 synchronized (this) {
8201 final long origId = Binder.clearCallingIdentity();
8202
8203 Message msg = Message.obtain();
8204 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8205 HashMap<String, Object> data = new HashMap<String, Object>();
8206 data.put("result", result);
8207 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008208 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008209 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008210 msg.obj = data;
8211 mHandler.sendMessage(msg);
8212
8213 Binder.restoreCallingIdentity(origId);
8214 }
8215 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008216 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008217 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008218 }
8219
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008220 // Depending on the policy in effect, there could be a bunch of
8221 // these in quick succession so we try to batch these together to
8222 // minimize disk writes, number of dropbox entries, and maximize
8223 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008224 private void logStrictModeViolationToDropBox(
8225 ProcessRecord process,
8226 StrictMode.ViolationInfo info) {
8227 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008228 return;
8229 }
8230 final boolean isSystemApp = process == null ||
8231 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8232 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008233 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008234 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8235 final DropBoxManager dbox = (DropBoxManager)
8236 mContext.getSystemService(Context.DROPBOX_SERVICE);
8237
8238 // Exit early if the dropbox isn't configured to accept this report type.
8239 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8240
8241 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008242 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008243 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8244 synchronized (sb) {
8245 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008246 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008247 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8248 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008249 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8250 if (info.violationNumThisLoop != 0) {
8251 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8252 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008253 if (info.numAnimationsRunning != 0) {
8254 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8255 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008256 if (info.broadcastIntentAction != null) {
8257 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8258 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008259 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008260 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008261 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008262 if (info.numInstances != -1) {
8263 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8264 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008265 if (info.tags != null) {
8266 for (String tag : info.tags) {
8267 sb.append("Span-Tag: ").append(tag).append("\n");
8268 }
8269 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008270 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008271 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8272 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008273 }
8274 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008275
8276 // Only buffer up to ~64k. Various logging bits truncate
8277 // things at 128k.
8278 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008279 }
8280
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008281 // Flush immediately if the buffer's grown too large, or this
8282 // is a non-system app. Non-system apps are isolated with a
8283 // different tag & policy and not batched.
8284 //
8285 // Batching is useful during internal testing with
8286 // StrictMode settings turned up high. Without batching,
8287 // thousands of separate files could be created on boot.
8288 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008289 new Thread("Error dump: " + dropboxTag) {
8290 @Override
8291 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008292 String report;
8293 synchronized (sb) {
8294 report = sb.toString();
8295 sb.delete(0, sb.length());
8296 sb.trimToSize();
8297 }
8298 if (report.length() != 0) {
8299 dbox.addText(dropboxTag, report);
8300 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008301 }
8302 }.start();
8303 return;
8304 }
8305
8306 // System app batching:
8307 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008308 // An existing dropbox-writing thread is outstanding, so
8309 // we don't need to start it up. The existing thread will
8310 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008311 return;
8312 }
8313
8314 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8315 // (After this point, we shouldn't access AMS internal data structures.)
8316 new Thread("Error dump: " + dropboxTag) {
8317 @Override
8318 public void run() {
8319 // 5 second sleep to let stacks arrive and be batched together
8320 try {
8321 Thread.sleep(5000); // 5 seconds
8322 } catch (InterruptedException e) {}
8323
8324 String errorReport;
8325 synchronized (mStrictModeBuffer) {
8326 errorReport = mStrictModeBuffer.toString();
8327 if (errorReport.length() == 0) {
8328 return;
8329 }
8330 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8331 mStrictModeBuffer.trimToSize();
8332 }
8333 dbox.addText(dropboxTag, errorReport);
8334 }
8335 }.start();
8336 }
8337
Dan Egnor60d87622009-12-16 16:32:58 -08008338 /**
8339 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8340 * @param app object of the crashing app, null for the system server
8341 * @param tag reported by the caller
8342 * @param crashInfo describing the context of the error
8343 * @return true if the process should exit immediately (WTF is fatal)
8344 */
8345 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008346 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008347 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008348 final String processName = app == null ? "system_server"
8349 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008350
8351 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008352 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008353 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008354 tag, crashInfo.exceptionMessage);
8355
Jeff Sharkeya353d262011-10-28 11:12:06 -07008356 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008357
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008358 if (r != null && r.pid != Process.myPid() &&
8359 Settings.Secure.getInt(mContext.getContentResolver(),
8360 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008361 crashApplication(r, crashInfo);
8362 return true;
8363 } else {
8364 return false;
8365 }
8366 }
8367
8368 /**
8369 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8370 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8371 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008372 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008373 if (app == null) {
8374 return null;
8375 }
8376
8377 synchronized (this) {
8378 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8379 final int NA = apps.size();
8380 for (int ia=0; ia<NA; ia++) {
8381 ProcessRecord p = apps.valueAt(ia);
8382 if (p.thread != null && p.thread.asBinder() == app) {
8383 return p;
8384 }
8385 }
8386 }
8387
Dianne Hackborncb44d962011-03-10 17:02:27 -08008388 Slog.w(TAG, "Can't find mystery application for " + reason
8389 + " from pid=" + Binder.getCallingPid()
8390 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008391 return null;
8392 }
8393 }
8394
8395 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008396 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8397 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008398 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008399 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8400 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008401 // Watchdog thread ends up invoking this function (with
8402 // a null ProcessRecord) to add the stack file to dropbox.
8403 // Do not acquire a lock on this (am) in such cases, as it
8404 // could cause a potential deadlock, if and when watchdog
8405 // is invoked due to unavailability of lock on am and it
8406 // would prevent watchdog from killing system_server.
8407 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008408 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008409 return;
8410 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008411 // Note: ProcessRecord 'process' is guarded by the service
8412 // instance. (notably process.pkgList, which could otherwise change
8413 // concurrently during execution of this method)
8414 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008415 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008416 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008417 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008418 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8419 for (String pkg : process.pkgList) {
8420 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008421 try {
Dan Egnora455d192010-03-12 08:52:28 -08008422 PackageInfo pi = pm.getPackageInfo(pkg, 0);
8423 if (pi != null) {
8424 sb.append(" v").append(pi.versionCode);
8425 if (pi.versionName != null) {
8426 sb.append(" (").append(pi.versionName).append(")");
8427 }
8428 }
8429 } catch (RemoteException e) {
8430 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008431 }
Dan Egnora455d192010-03-12 08:52:28 -08008432 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008433 }
Dan Egnora455d192010-03-12 08:52:28 -08008434 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008435 }
8436
8437 private static String processClass(ProcessRecord process) {
8438 if (process == null || process.pid == MY_PID) {
8439 return "system_server";
8440 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8441 return "system_app";
8442 } else {
8443 return "data_app";
8444 }
8445 }
8446
8447 /**
8448 * Write a description of an error (crash, WTF, ANR) to the drop box.
8449 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8450 * @param process which caused the error, null means the system server
8451 * @param activity which triggered the error, null if unknown
8452 * @param parent activity related to the error, null if unknown
8453 * @param subject line related to the error, null if absent
8454 * @param report in long form describing the error, null if absent
8455 * @param logFile to include in the report, null if none
8456 * @param crashInfo giving an application stack trace, null if absent
8457 */
8458 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008459 ProcessRecord process, String processName, ActivityRecord activity,
8460 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008461 final String report, final File logFile,
8462 final ApplicationErrorReport.CrashInfo crashInfo) {
8463 // NOTE -- this must never acquire the ActivityManagerService lock,
8464 // otherwise the watchdog may be prevented from resetting the system.
8465
8466 final String dropboxTag = processClass(process) + "_" + eventType;
8467 final DropBoxManager dbox = (DropBoxManager)
8468 mContext.getSystemService(Context.DROPBOX_SERVICE);
8469
8470 // Exit early if the dropbox isn't configured to accept this report type.
8471 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8472
8473 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008474 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008475 if (activity != null) {
8476 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8477 }
8478 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8479 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8480 }
8481 if (parent != null && parent != activity) {
8482 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8483 }
8484 if (subject != null) {
8485 sb.append("Subject: ").append(subject).append("\n");
8486 }
8487 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008488 if (Debug.isDebuggerConnected()) {
8489 sb.append("Debugger: Connected\n");
8490 }
Dan Egnora455d192010-03-12 08:52:28 -08008491 sb.append("\n");
8492
8493 // Do the rest in a worker thread to avoid blocking the caller on I/O
8494 // (After this point, we shouldn't access AMS internal data structures.)
8495 Thread worker = new Thread("Error dump: " + dropboxTag) {
8496 @Override
8497 public void run() {
8498 if (report != null) {
8499 sb.append(report);
8500 }
8501 if (logFile != null) {
8502 try {
8503 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8504 } catch (IOException e) {
8505 Slog.e(TAG, "Error reading " + logFile, e);
8506 }
8507 }
8508 if (crashInfo != null && crashInfo.stackTrace != null) {
8509 sb.append(crashInfo.stackTrace);
8510 }
8511
8512 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8513 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8514 if (lines > 0) {
8515 sb.append("\n");
8516
8517 // Merge several logcat streams, and take the last N lines
8518 InputStreamReader input = null;
8519 try {
8520 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8521 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8522 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8523
8524 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8525 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8526 input = new InputStreamReader(logcat.getInputStream());
8527
8528 int num;
8529 char[] buf = new char[8192];
8530 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8531 } catch (IOException e) {
8532 Slog.e(TAG, "Error running logcat", e);
8533 } finally {
8534 if (input != null) try { input.close(); } catch (IOException e) {}
8535 }
8536 }
8537
8538 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008539 }
Dan Egnora455d192010-03-12 08:52:28 -08008540 };
8541
8542 if (process == null || process.pid == MY_PID) {
8543 worker.run(); // We may be about to die -- need to run this synchronously
8544 } else {
8545 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008546 }
8547 }
8548
8549 /**
8550 * Bring up the "unexpected error" dialog box for a crashing app.
8551 * Deal with edge cases (intercepts from instrumented applications,
8552 * ActivityController, error intent receivers, that sort of thing).
8553 * @param r the application crashing
8554 * @param crashInfo describing the failure
8555 */
8556 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008557 long timeMillis = System.currentTimeMillis();
8558 String shortMsg = crashInfo.exceptionClassName;
8559 String longMsg = crashInfo.exceptionMessage;
8560 String stackTrace = crashInfo.stackTrace;
8561 if (shortMsg != null && longMsg != null) {
8562 longMsg = shortMsg + ": " + longMsg;
8563 } else if (shortMsg != null) {
8564 longMsg = shortMsg;
8565 }
8566
Dan Egnor60d87622009-12-16 16:32:58 -08008567 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008568 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008569 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008570 try {
8571 String name = r != null ? r.processName : null;
8572 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008573 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008574 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008575 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008576 + " at watcher's request");
8577 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008578 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 }
8580 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008581 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 }
8583 }
8584
8585 final long origId = Binder.clearCallingIdentity();
8586
8587 // If this process is running instrumentation, finish it.
8588 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008589 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008591 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8592 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 Bundle info = new Bundle();
8594 info.putString("shortMsg", shortMsg);
8595 info.putString("longMsg", longMsg);
8596 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8597 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008598 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008599 }
8600
Dan Egnor60d87622009-12-16 16:32:58 -08008601 // If we can't identify the process or it's already exceeded its crash quota,
8602 // quit right away without showing a crash dialog.
8603 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008604 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008605 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008606 }
8607
8608 Message msg = Message.obtain();
8609 msg.what = SHOW_ERROR_MSG;
8610 HashMap data = new HashMap();
8611 data.put("result", result);
8612 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613 msg.obj = data;
8614 mHandler.sendMessage(msg);
8615
8616 Binder.restoreCallingIdentity(origId);
8617 }
8618
8619 int res = result.get();
8620
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008621 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008623 if (r != null && !r.isolated) {
8624 // XXX Can't keep track of crash time for isolated processes,
8625 // since they don't have a persistent identity.
8626 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008627 SystemClock.uptimeMillis());
8628 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008629 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008630 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008631 }
8632 }
8633
8634 if (appErrorIntent != null) {
8635 try {
8636 mContext.startActivity(appErrorIntent);
8637 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008638 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008642
8643 Intent createAppErrorIntentLocked(ProcessRecord r,
8644 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8645 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008646 if (report == null) {
8647 return null;
8648 }
8649 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8650 result.setComponent(r.errorReportReceiver);
8651 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8652 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8653 return result;
8654 }
8655
Dan Egnorb7f03672009-12-09 16:22:32 -08008656 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8657 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008658 if (r.errorReportReceiver == null) {
8659 return null;
8660 }
8661
8662 if (!r.crashing && !r.notResponding) {
8663 return null;
8664 }
8665
Dan Egnorb7f03672009-12-09 16:22:32 -08008666 ApplicationErrorReport report = new ApplicationErrorReport();
8667 report.packageName = r.info.packageName;
8668 report.installerPackageName = r.errorReportReceiver.getPackageName();
8669 report.processName = r.processName;
8670 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008671 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008672
Dan Egnorb7f03672009-12-09 16:22:32 -08008673 if (r.crashing) {
8674 report.type = ApplicationErrorReport.TYPE_CRASH;
8675 report.crashInfo = crashInfo;
8676 } else if (r.notResponding) {
8677 report.type = ApplicationErrorReport.TYPE_ANR;
8678 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008679
Dan Egnorb7f03672009-12-09 16:22:32 -08008680 report.anrInfo.activity = r.notRespondingReport.tag;
8681 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8682 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008683 }
8684
Dan Egnorb7f03672009-12-09 16:22:32 -08008685 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008686 }
8687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008689 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690 // assume our apps are happy - lazy create the list
8691 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8692
8693 synchronized (this) {
8694
8695 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008696 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8697 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008698 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8699 // This one's in trouble, so we'll generate a report for it
8700 // crashes are higher priority (in case there's a crash *and* an anr)
8701 ActivityManager.ProcessErrorStateInfo report = null;
8702 if (app.crashing) {
8703 report = app.crashingReport;
8704 } else if (app.notResponding) {
8705 report = app.notRespondingReport;
8706 }
8707
8708 if (report != null) {
8709 if (errList == null) {
8710 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8711 }
8712 errList.add(report);
8713 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008714 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008715 " crashing = " + app.crashing +
8716 " notResponding = " + app.notResponding);
8717 }
8718 }
8719 }
8720 }
8721
8722 return errList;
8723 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008724
8725 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008726 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008727 if (currApp != null) {
8728 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8729 }
8730 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008731 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8732 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008733 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8734 if (currApp != null) {
8735 currApp.lru = 0;
8736 }
8737 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008738 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008739 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8740 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8741 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8742 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8743 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8744 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8745 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8746 } else {
8747 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8748 }
8749 }
8750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008751 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008752 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008753 // Lazy instantiation of list
8754 List<ActivityManager.RunningAppProcessInfo> runList = null;
8755 synchronized (this) {
8756 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008757 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8758 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008759 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8760 // Generate process state info for running application
8761 ActivityManager.RunningAppProcessInfo currApp =
8762 new ActivityManager.RunningAppProcessInfo(app.processName,
8763 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07008764 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07008765 if (mHeavyWeightProcess == app) {
Dianne Hackborn482566e2010-09-03 12:51:28 -07008766 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07008767 }
Dianne Hackborn42499172010-10-15 18:45:07 -07008768 if (app.persistent) {
8769 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771 int adj = app.curAdj;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008772 currApp.importance = oomAdjToImportance(adj, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008773 currApp.importanceReasonCode = app.adjTypeCode;
8774 if (app.adjSource instanceof ProcessRecord) {
8775 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008776 currApp.importanceReasonImportance = oomAdjToImportance(
8777 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008778 } else if (app.adjSource instanceof ActivityRecord) {
8779 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008780 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8781 }
8782 if (app.adjTarget instanceof ComponentName) {
8783 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8784 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008785 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008786 // + " lru=" + currApp.lru);
8787 if (runList == null) {
8788 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8789 }
8790 runList.add(currApp);
8791 }
8792 }
8793 }
8794 return runList;
8795 }
8796
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008797 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008798 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008799 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8800 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8801 if (runningApps != null && runningApps.size() > 0) {
8802 Set<String> extList = new HashSet<String>();
8803 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8804 if (app.pkgList != null) {
8805 for (String pkg : app.pkgList) {
8806 extList.add(pkg);
8807 }
8808 }
8809 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008810 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008811 for (String pkg : extList) {
8812 try {
8813 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8814 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8815 retList.add(info);
8816 }
8817 } catch (RemoteException e) {
8818 }
8819 }
8820 }
8821 return retList;
8822 }
8823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008824 @Override
8825 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008826 if (checkCallingPermission(android.Manifest.permission.DUMP)
8827 != PackageManager.PERMISSION_GRANTED) {
8828 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8829 + Binder.getCallingPid()
8830 + ", uid=" + Binder.getCallingUid()
8831 + " without permission "
8832 + android.Manifest.permission.DUMP);
8833 return;
8834 }
8835
8836 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008837 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008838 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008839
8840 int opti = 0;
8841 while (opti < args.length) {
8842 String opt = args[opti];
8843 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8844 break;
8845 }
8846 opti++;
8847 if ("-a".equals(opt)) {
8848 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008849 } else if ("-c".equals(opt)) {
8850 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008851 } else if ("-h".equals(opt)) {
8852 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008853 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008854 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008855 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008856 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8857 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8858 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008859 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008860 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008861 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008862 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008863 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008864 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008865 pw.println(" all: dump all activities");
8866 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008867 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008868 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8869 pw.println(" a partial substring in a component name, a");
8870 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008871 pw.println(" -a: include all available server state.");
8872 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008873 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008874 } else {
8875 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008876 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008877 }
8878
8879 // Is the caller requesting to dump a particular piece of data?
8880 if (opti < args.length) {
8881 String cmd = args[opti];
8882 opti++;
8883 if ("activities".equals(cmd) || "a".equals(cmd)) {
8884 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008885 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008886 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008887 return;
8888 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008889 String[] newArgs;
8890 String name;
8891 if (opti >= args.length) {
8892 name = null;
8893 newArgs = EMPTY_STRING_ARRAY;
8894 } else {
8895 name = args[opti];
8896 opti++;
8897 newArgs = new String[args.length - opti];
8898 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8899 args.length - opti);
8900 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008901 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008902 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008903 }
8904 return;
8905 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008906 String[] newArgs;
8907 String name;
8908 if (opti >= args.length) {
8909 name = null;
8910 newArgs = EMPTY_STRING_ARRAY;
8911 } else {
8912 name = args[opti];
8913 opti++;
8914 newArgs = new String[args.length - opti];
8915 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8916 args.length - opti);
8917 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008918 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008919 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008920 }
8921 return;
8922 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008923 String[] newArgs;
8924 String name;
8925 if (opti >= args.length) {
8926 name = null;
8927 newArgs = EMPTY_STRING_ARRAY;
8928 } else {
8929 name = args[opti];
8930 opti++;
8931 newArgs = new String[args.length - opti];
8932 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8933 args.length - opti);
8934 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008935 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008936 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008937 }
8938 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008939 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8940 synchronized (this) {
8941 dumpOomLocked(fd, pw, args, opti, true);
8942 }
8943 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008944 } else if ("provider".equals(cmd)) {
8945 String[] newArgs;
8946 String name;
8947 if (opti >= args.length) {
8948 name = null;
8949 newArgs = EMPTY_STRING_ARRAY;
8950 } else {
8951 name = args[opti];
8952 opti++;
8953 newArgs = new String[args.length - opti];
8954 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8955 }
8956 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8957 pw.println("No providers match: " + name);
8958 pw.println("Use -h for help.");
8959 }
8960 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008961 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8962 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008963 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008964 }
8965 return;
8966 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008967 String[] newArgs;
8968 String name;
8969 if (opti >= args.length) {
8970 name = null;
8971 newArgs = EMPTY_STRING_ARRAY;
8972 } else {
8973 name = args[opti];
8974 opti++;
8975 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008976 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8977 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008978 }
8979 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8980 pw.println("No services match: " + name);
8981 pw.println("Use -h for help.");
8982 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008983 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008984 } else if ("package".equals(cmd)) {
8985 String[] newArgs;
8986 if (opti >= args.length) {
8987 pw.println("package: no package name specified");
8988 pw.println("Use -h for help.");
8989 return;
8990 } else {
8991 dumpPackage = args[opti];
8992 opti++;
8993 newArgs = new String[args.length - opti];
8994 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8995 args.length - opti);
8996 args = newArgs;
8997 opti = 0;
8998 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008999 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9000 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009001 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009002 }
9003 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07009004 } else {
9005 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009006 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
9007 pw.println("Bad activity command, or no activities match: " + cmd);
9008 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009009 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009010 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009011 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009012 }
9013
9014 // No piece of data specified, dump everything.
9015 synchronized (this) {
9016 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009017 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018 if (needSep) {
9019 pw.println(" ");
9020 }
9021 if (dumpAll) {
9022 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009023 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009024 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009025 if (needSep) {
9026 pw.println(" ");
9027 }
9028 if (dumpAll) {
9029 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009030 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009031 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009032 if (needSep) {
9033 pw.println(" ");
9034 }
9035 if (dumpAll) {
9036 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009037 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009038 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009039 if (needSep) {
9040 pw.println(" ");
9041 }
9042 if (dumpAll) {
9043 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009044 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009045 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009046 if (needSep) {
9047 pw.println(" ");
9048 }
9049 if (dumpAll) {
9050 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009051 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009052 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009053 }
9054 }
9055
9056 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009057 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009058 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9059 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009060 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9061 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009062 pw.println(" ");
9063 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009064 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9065 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009066 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009067 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009068 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009069 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009070 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009071 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009072 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009073 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009074 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009075 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009076 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009077 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009078 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9079 pw.println(" ");
9080 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009081 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009082 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009083 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009084 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009085 pw.println(" ");
9086 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009087 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009088 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009090
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009091 pw.println(" ");
Dianne Hackborncbb722e2012-02-07 18:33:49 -08009092 if (mMainStack.mPausingActivities.size() > 0) {
9093 pw.println(" mPausingActivities: " + Arrays.toString(
9094 mMainStack.mPausingActivities.toArray()));
9095 }
9096 if (mMainStack.mInputPausedActivities.size() > 0) {
9097 pw.println(" mInputPausedActivities: " + Arrays.toString(
9098 mMainStack.mInputPausedActivities.toArray()));
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009099 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009100 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009101 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009102 if (dumpAll) {
9103 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9104 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009105 pw.println(" mDismissKeyguardOnNextActivity: "
9106 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009109 if (mRecentTasks.size() > 0) {
9110 pw.println();
9111 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009112
9113 final int N = mRecentTasks.size();
9114 for (int i=0; i<N; i++) {
9115 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009116 if (dumpPackage != null) {
9117 if (tr.realActivity == null ||
9118 !dumpPackage.equals(tr.realActivity)) {
9119 continue;
9120 }
9121 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009122 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9123 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009124 if (dumpAll) {
9125 mRecentTasks.get(i).dump(pw, " ");
9126 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009127 }
9128 }
9129
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009130 if (dumpAll) {
9131 pw.println(" ");
9132 pw.println(" mCurTask: " + mCurTask);
9133 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009134
9135 return true;
9136 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009137
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009138 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009139 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009140 boolean needSep = false;
9141 int numPers = 0;
9142
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009143 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9144
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009145 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009146 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9147 final int NA = procs.size();
9148 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009149 ProcessRecord r = procs.valueAt(ia);
9150 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9151 continue;
9152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009153 if (!needSep) {
9154 pw.println(" All known processes:");
9155 needSep = true;
9156 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009157 pw.print(r.persistent ? " *PERS*" : " *APP*");
9158 pw.print(" UID "); pw.print(procs.keyAt(ia));
9159 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009160 r.dump(pw, " ");
9161 if (r.persistent) {
9162 numPers++;
9163 }
9164 }
9165 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009166 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009167
9168 if (mIsolatedProcesses.size() > 0) {
9169 if (needSep) pw.println(" ");
9170 needSep = true;
9171 pw.println(" Isolated process list (sorted by uid):");
9172 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9173 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9174 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9175 continue;
9176 }
9177 pw.println(String.format("%sIsolated #%2d: %s",
9178 " ", i, r.toString()));
9179 }
9180 }
9181
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009182 if (mLruProcesses.size() > 0) {
9183 if (needSep) pw.println(" ");
9184 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009185 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009186 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009187 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009188 needSep = true;
9189 }
9190
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009191 if (dumpAll) {
9192 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009193 boolean printed = false;
9194 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9195 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9196 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9197 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009198 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009199 if (!printed) {
9200 if (needSep) pw.println(" ");
9201 needSep = true;
9202 pw.println(" PID mappings:");
9203 printed = true;
9204 }
9205 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9206 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009207 }
9208 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009209 }
9210
9211 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009212 synchronized (mPidsSelfLocked) {
9213 boolean printed = false;
9214 for (int i=0; i<mForegroundProcesses.size(); i++) {
9215 ProcessRecord r = mPidsSelfLocked.get(
9216 mForegroundProcesses.valueAt(i).pid);
9217 if (dumpPackage != null && (r == null
9218 || !dumpPackage.equals(r.info.packageName))) {
9219 continue;
9220 }
9221 if (!printed) {
9222 if (needSep) pw.println(" ");
9223 needSep = true;
9224 pw.println(" Foreground Processes:");
9225 printed = true;
9226 }
9227 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9228 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009230 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009231 }
9232
9233 if (mPersistentStartingProcesses.size() > 0) {
9234 if (needSep) pw.println(" ");
9235 needSep = true;
9236 pw.println(" Persisent processes that are starting:");
9237 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009238 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009240
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009241 if (mRemovedProcesses.size() > 0) {
9242 if (needSep) pw.println(" ");
9243 needSep = true;
9244 pw.println(" Processes that are being removed:");
9245 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009246 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009247 }
9248
9249 if (mProcessesOnHold.size() > 0) {
9250 if (needSep) pw.println(" ");
9251 needSep = true;
9252 pw.println(" Processes that are on old until the system is ready:");
9253 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009254 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009256
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009257 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009258
9259 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009260 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009261 long now = SystemClock.uptimeMillis();
9262 for (Map.Entry<String, SparseArray<Long>> procs
9263 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009264 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009265 SparseArray<Long> uids = procs.getValue();
9266 final int N = uids.size();
9267 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009268 int puid = uids.keyAt(i);
9269 ProcessRecord r = mProcessNames.get(pname, puid);
9270 if (dumpPackage != null && (r == null
9271 || !dumpPackage.equals(r.info.packageName))) {
9272 continue;
9273 }
9274 if (!printed) {
9275 if (needSep) pw.println(" ");
9276 needSep = true;
9277 pw.println(" Time since processes crashed:");
9278 printed = true;
9279 }
9280 pw.print(" Process "); pw.print(pname);
9281 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009282 pw.print(": last crashed ");
9283 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009284 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009285 }
9286 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009288
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009289 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009290 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009291 for (Map.Entry<String, SparseArray<Long>> procs
9292 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009293 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009294 SparseArray<Long> uids = procs.getValue();
9295 final int N = uids.size();
9296 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009297 int puid = uids.keyAt(i);
9298 ProcessRecord r = mProcessNames.get(pname, puid);
9299 if (dumpPackage != null && (r == null
9300 || !dumpPackage.equals(r.info.packageName))) {
9301 continue;
9302 }
9303 if (!printed) {
9304 if (needSep) pw.println(" ");
9305 needSep = true;
9306 pw.println(" Bad processes:");
9307 }
9308 pw.print(" Bad process "); pw.print(pname);
9309 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009310 pw.print(": crashed at time ");
9311 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009312 }
9313 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009315
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009316 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009317 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009318 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009319 if (dumpAll) {
9320 StringBuilder sb = new StringBuilder(128);
9321 sb.append(" mPreviousProcessVisibleTime: ");
9322 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9323 pw.println(sb);
9324 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009325 if (mHeavyWeightProcess != null) {
9326 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9327 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009328 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009329 if (dumpAll) {
9330 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009331 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009332 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009333 for (Map.Entry<String, Integer> entry
9334 : mCompatModePackages.getPackages().entrySet()) {
9335 String pkg = entry.getKey();
9336 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009337 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9338 continue;
9339 }
9340 if (!printed) {
9341 pw.println(" mScreenCompatPackages:");
9342 printed = true;
9343 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009344 pw.print(" "); pw.print(pkg); pw.print(": ");
9345 pw.print(mode); pw.println();
9346 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009347 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009348 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009349 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
9350 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9351 || mOrigWaitForDebugger) {
9352 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9353 + " mDebugTransient=" + mDebugTransient
9354 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9355 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009356 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9357 || mProfileFd != null) {
9358 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9359 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9360 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9361 + mAutoStopProfiler);
9362 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009363 if (mAlwaysFinishActivities || mController != null) {
9364 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9365 + " mController=" + mController);
9366 }
9367 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009368 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009369 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009370 + " mProcessesReady=" + mProcessesReady
9371 + " mSystemReady=" + mSystemReady);
9372 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009373 + " mBooted=" + mBooted
9374 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009375 pw.print(" mLastPowerCheckRealtime=");
9376 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9377 pw.println("");
9378 pw.print(" mLastPowerCheckUptime=");
9379 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9380 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009381 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9382 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009383 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009384 pw.println(" mNumServiceProcs=" + mNumServiceProcs
9385 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009386 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009387
9388 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009389 }
9390
Dianne Hackborn287952c2010-09-22 22:34:31 -07009391 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009392 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009393 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009394 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009395 long now = SystemClock.uptimeMillis();
9396 for (int i=0; i<mProcessesToGc.size(); i++) {
9397 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009398 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9399 continue;
9400 }
9401 if (!printed) {
9402 if (needSep) pw.println(" ");
9403 needSep = true;
9404 pw.println(" Processes that are waiting to GC:");
9405 printed = true;
9406 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009407 pw.print(" Process "); pw.println(proc);
9408 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9409 pw.print(", last gced=");
9410 pw.print(now-proc.lastRequestedGc);
9411 pw.print(" ms ago, last lowMem=");
9412 pw.print(now-proc.lastLowMemory);
9413 pw.println(" ms ago");
9414
9415 }
9416 }
9417 return needSep;
9418 }
9419
9420 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9421 int opti, boolean dumpAll) {
9422 boolean needSep = false;
9423
9424 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009425 if (needSep) pw.println(" ");
9426 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009427 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009428 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009429 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009430 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9431 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9432 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9433 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9434 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009435 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009436 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009437 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009438 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009439 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009440 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009441
9442 if (needSep) pw.println(" ");
9443 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009444 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009445 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009446 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009447 needSep = true;
9448 }
9449
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009450 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009451
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009452 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009453 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009454 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009455 if (mHeavyWeightProcess != null) {
9456 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9457 }
9458
9459 return true;
9460 }
9461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009462 /**
9463 * There are three ways to call this:
9464 * - no service specified: dump all the services
9465 * - a flattened component name that matched an existing service was specified as the
9466 * first arg: dump that one service
9467 * - the first arg isn't the flattened component name of an existing service:
9468 * dump all services whose component contains the first arg as a substring
9469 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009470 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9471 int opti, boolean dumpAll) {
9472 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009473
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009474 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009475 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009476 try {
9477 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9478 for (UserInfo user : users) {
9479 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9480 services.add(r1);
9481 }
9482 }
9483 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009484 }
9485 }
9486 } else {
9487 ComponentName componentName = name != null
9488 ? ComponentName.unflattenFromString(name) : null;
9489 int objectId = 0;
9490 if (componentName == null) {
9491 // Not a '/' separated full component name; maybe an object ID?
9492 try {
9493 objectId = Integer.parseInt(name, 16);
9494 name = null;
9495 componentName = null;
9496 } catch (RuntimeException e) {
9497 }
9498 }
9499
9500 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009501 try {
9502 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9503 for (UserInfo user : users) {
9504 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9505 if (componentName != null) {
9506 if (r1.name.equals(componentName)) {
9507 services.add(r1);
9508 }
9509 } else if (name != null) {
9510 if (r1.name.flattenToString().contains(name)) {
9511 services.add(r1);
9512 }
9513 } else if (System.identityHashCode(r1) == objectId) {
9514 services.add(r1);
9515 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009516 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009517 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009518 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009519 }
9520 }
9521 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009522
9523 if (services.size() <= 0) {
9524 return false;
9525 }
9526
9527 boolean needSep = false;
9528 for (int i=0; i<services.size(); i++) {
9529 if (needSep) {
9530 pw.println();
9531 }
9532 needSep = true;
9533 dumpService("", fd, pw, services.get(i), args, dumpAll);
9534 }
9535 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009536 }
9537
9538 /**
9539 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9540 * there is a thread associated with the service.
9541 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009542 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9543 final ServiceRecord r, String[] args, boolean dumpAll) {
9544 String innerPrefix = prefix + " ";
9545 synchronized (this) {
9546 pw.print(prefix); pw.print("SERVICE ");
9547 pw.print(r.shortName); pw.print(" ");
9548 pw.print(Integer.toHexString(System.identityHashCode(r)));
9549 pw.print(" pid=");
9550 if (r.app != null) pw.println(r.app.pid);
9551 else pw.println("(not running)");
9552 if (dumpAll) {
9553 r.dump(pw, innerPrefix);
9554 }
9555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009556 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009557 pw.print(prefix); pw.println(" Client:");
9558 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009559 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009560 TransferPipe tp = new TransferPipe();
9561 try {
9562 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9563 tp.setBufferPrefix(prefix + " ");
9564 tp.go(fd);
9565 } finally {
9566 tp.kill();
9567 }
9568 } catch (IOException e) {
9569 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009570 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009571 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009572 }
9573 }
9574 }
9575
Marco Nelissen18cb2872011-11-15 11:19:53 -08009576 /**
9577 * There are three ways to call this:
9578 * - no provider specified: dump all the providers
9579 * - a flattened component name that matched an existing provider was specified as the
9580 * first arg: dump that one provider
9581 * - the first arg isn't the flattened component name of an existing provider:
9582 * dump all providers whose component contains the first arg as a substring
9583 */
9584 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9585 int opti, boolean dumpAll) {
9586 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
9587
9588 if ("all".equals(name)) {
9589 synchronized (this) {
9590 for (ContentProviderRecord r1 : mProvidersByClass.values()) {
9591 providers.add(r1);
9592 }
9593 }
9594 } else {
9595 ComponentName componentName = name != null
9596 ? ComponentName.unflattenFromString(name) : null;
9597 int objectId = 0;
9598 if (componentName == null) {
9599 // Not a '/' separated full component name; maybe an object ID?
9600 try {
9601 objectId = Integer.parseInt(name, 16);
9602 name = null;
9603 componentName = null;
9604 } catch (RuntimeException e) {
9605 }
9606 }
9607
9608 synchronized (this) {
9609 for (ContentProviderRecord r1 : mProvidersByClass.values()) {
9610 if (componentName != null) {
9611 if (r1.name.equals(componentName)) {
9612 providers.add(r1);
9613 }
9614 } else if (name != null) {
9615 if (r1.name.flattenToString().contains(name)) {
9616 providers.add(r1);
9617 }
9618 } else if (System.identityHashCode(r1) == objectId) {
9619 providers.add(r1);
9620 }
9621 }
9622 }
9623 }
9624
9625 if (providers.size() <= 0) {
9626 return false;
9627 }
9628
9629 boolean needSep = false;
9630 for (int i=0; i<providers.size(); i++) {
9631 if (needSep) {
9632 pw.println();
9633 }
9634 needSep = true;
9635 dumpProvider("", fd, pw, providers.get(i), args, dumpAll);
9636 }
9637 return true;
9638 }
9639
9640 /**
9641 * Invokes IApplicationThread.dumpProvider() on the thread of the specified provider if
9642 * there is a thread associated with the provider.
9643 */
9644 private void dumpProvider(String prefix, FileDescriptor fd, PrintWriter pw,
9645 final ContentProviderRecord r, String[] args, boolean dumpAll) {
9646 String innerPrefix = prefix + " ";
9647 synchronized (this) {
9648 pw.print(prefix); pw.print("PROVIDER ");
9649 pw.print(r);
9650 pw.print(" pid=");
9651 if (r.proc != null) pw.println(r.proc.pid);
9652 else pw.println("(not running)");
9653 if (dumpAll) {
9654 r.dump(pw, innerPrefix);
9655 }
9656 }
9657 if (r.proc != null && r.proc.thread != null) {
9658 pw.println(" Client:");
9659 pw.flush();
9660 try {
9661 TransferPipe tp = new TransferPipe();
9662 try {
9663 r.proc.thread.dumpProvider(
9664 tp.getWriteFd().getFileDescriptor(), r.provider.asBinder(), args);
9665 tp.setBufferPrefix(" ");
9666 // Short timeout, since blocking here can
9667 // deadlock with the application.
9668 tp.go(fd, 2000);
9669 } finally {
9670 tp.kill();
9671 }
9672 } catch (IOException ex) {
9673 pw.println(" Failure while dumping the provider: " + ex);
9674 } catch (RemoteException ex) {
9675 pw.println(" Got a RemoteException while dumping the service");
9676 }
9677 }
9678 }
9679
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009680 static class ItemMatcher {
9681 ArrayList<ComponentName> components;
9682 ArrayList<String> strings;
9683 ArrayList<Integer> objects;
9684 boolean all;
9685
9686 ItemMatcher() {
9687 all = true;
9688 }
9689
9690 void build(String name) {
9691 ComponentName componentName = ComponentName.unflattenFromString(name);
9692 if (componentName != null) {
9693 if (components == null) {
9694 components = new ArrayList<ComponentName>();
9695 }
9696 components.add(componentName);
9697 all = false;
9698 } else {
9699 int objectId = 0;
9700 // Not a '/' separated full component name; maybe an object ID?
9701 try {
9702 objectId = Integer.parseInt(name, 16);
9703 if (objects == null) {
9704 objects = new ArrayList<Integer>();
9705 }
9706 objects.add(objectId);
9707 all = false;
9708 } catch (RuntimeException e) {
9709 // Not an integer; just do string match.
9710 if (strings == null) {
9711 strings = new ArrayList<String>();
9712 }
9713 strings.add(name);
9714 all = false;
9715 }
9716 }
9717 }
9718
9719 int build(String[] args, int opti) {
9720 for (; opti<args.length; opti++) {
9721 String name = args[opti];
9722 if ("--".equals(name)) {
9723 return opti+1;
9724 }
9725 build(name);
9726 }
9727 return opti;
9728 }
9729
9730 boolean match(Object object, ComponentName comp) {
9731 if (all) {
9732 return true;
9733 }
9734 if (components != null) {
9735 for (int i=0; i<components.size(); i++) {
9736 if (components.get(i).equals(comp)) {
9737 return true;
9738 }
9739 }
9740 }
9741 if (objects != null) {
9742 for (int i=0; i<objects.size(); i++) {
9743 if (System.identityHashCode(object) == objects.get(i)) {
9744 return true;
9745 }
9746 }
9747 }
9748 if (strings != null) {
9749 String flat = comp.flattenToString();
9750 for (int i=0; i<strings.size(); i++) {
9751 if (flat.contains(strings.get(i))) {
9752 return true;
9753 }
9754 }
9755 }
9756 return false;
9757 }
9758 }
9759
Dianne Hackborn625ac272010-09-17 18:29:22 -07009760 /**
9761 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009762 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009763 * - the cmd arg isn't the flattened component name of an existing activity:
9764 * dump all activity whose component contains the cmd as a substring
9765 * - A hex number of the ActivityRecord object instance.
9766 */
9767 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9768 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009769 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009770
9771 if ("all".equals(name)) {
9772 synchronized (this) {
9773 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009774 activities.add(r1);
9775 }
9776 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009777 } else if ("top".equals(name)) {
9778 synchronized (this) {
9779 final int N = mMainStack.mHistory.size();
9780 if (N > 0) {
9781 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9782 }
9783 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009784 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009785 ItemMatcher matcher = new ItemMatcher();
9786 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009787
9788 synchronized (this) {
9789 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009790 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009791 activities.add(r1);
9792 }
9793 }
9794 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009795 }
9796
9797 if (activities.size() <= 0) {
9798 return false;
9799 }
9800
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009801 String[] newArgs = new String[args.length - opti];
9802 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9803
Dianne Hackborn30d71892010-12-11 10:37:55 -08009804 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009805 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009806 for (int i=activities.size()-1; i>=0; i--) {
9807 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009808 if (needSep) {
9809 pw.println();
9810 }
9811 needSep = true;
9812 synchronized (this) {
9813 if (lastTask != r.task) {
9814 lastTask = r.task;
9815 pw.print("TASK "); pw.print(lastTask.affinity);
9816 pw.print(" id="); pw.println(lastTask.taskId);
9817 if (dumpAll) {
9818 lastTask.dump(pw, " ");
9819 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009820 }
9821 }
9822 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009823 }
9824 return true;
9825 }
9826
9827 /**
9828 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9829 * there is a thread associated with the activity.
9830 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009831 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009832 final ActivityRecord r, String[] args, boolean dumpAll) {
9833 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009834 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009835 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9836 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9837 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009838 if (r.app != null) pw.println(r.app.pid);
9839 else pw.println("(not running)");
9840 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009841 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009842 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009843 }
9844 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009845 // flush anything that is already in the PrintWriter since the thread is going
9846 // to write to the file descriptor directly
9847 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009848 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009849 TransferPipe tp = new TransferPipe();
9850 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009851 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9852 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009853 tp.go(fd);
9854 } finally {
9855 tp.kill();
9856 }
9857 } catch (IOException e) {
9858 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009859 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009860 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009861 }
9862 }
9863 }
9864
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009865 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009866 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009867 boolean needSep = false;
9868
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009869 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009870 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009871 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009872 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009873 Iterator it = mRegisteredReceivers.values().iterator();
9874 while (it.hasNext()) {
9875 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009876 if (dumpPackage != null && (r.app == null ||
9877 !dumpPackage.equals(r.app.info.packageName))) {
9878 continue;
9879 }
9880 if (!printed) {
9881 pw.println(" Registered Receivers:");
9882 needSep = true;
9883 printed = true;
9884 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009885 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009886 r.dump(pw, " ");
9887 }
9888 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009889
9890 if (mReceiverResolver.dump(pw, needSep ?
9891 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9892 " ", dumpPackage, false)) {
9893 needSep = true;
9894 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009895 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009896
9897 for (BroadcastQueue q : mBroadcastQueues) {
9898 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009900
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009901 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009902
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009903 if (mStickyBroadcasts != null && dumpPackage == null) {
9904 if (needSep) {
9905 pw.println();
9906 }
9907 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009908 pw.println(" Sticky broadcasts:");
9909 StringBuilder sb = new StringBuilder(128);
9910 for (Map.Entry<String, ArrayList<Intent>> ent
9911 : mStickyBroadcasts.entrySet()) {
9912 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009913 if (dumpAll) {
9914 pw.println(":");
9915 ArrayList<Intent> intents = ent.getValue();
9916 final int N = intents.size();
9917 for (int i=0; i<N; i++) {
9918 sb.setLength(0);
9919 sb.append(" Intent: ");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009920 intents.get(i).toShortString(sb, false, true, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009921 pw.println(sb.toString());
9922 Bundle bundle = intents.get(i).getExtras();
9923 if (bundle != null) {
9924 pw.print(" ");
9925 pw.println(bundle.toString());
9926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009927 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009928 } else {
9929 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009930 }
9931 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009932 needSep = true;
9933 }
9934
9935 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009936 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009937 for (BroadcastQueue queue : mBroadcastQueues) {
9938 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9939 + queue.mBroadcastsScheduled);
9940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009941 pw.println(" mHandler:");
9942 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009943 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009944 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009945
9946 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009947 }
9948
Marco Nelissen18cb2872011-11-15 11:19:53 -08009949 /**
9950 * Prints a list of ServiceRecords (dumpsys activity services)
9951 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009952 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009953 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009954 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009955
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009956 ItemMatcher matcher = new ItemMatcher();
9957 matcher.build(args, opti);
9958
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009959 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009960 try {
9961 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9962 for (UserInfo user : users) {
9963 if (mServiceMap.getAllServices(user.id).size() > 0) {
9964 boolean printed = false;
9965 long nowReal = SystemClock.elapsedRealtime();
9966 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9967 user.id).iterator();
9968 needSep = false;
9969 while (it.hasNext()) {
9970 ServiceRecord r = it.next();
9971 if (!matcher.match(r, r.name)) {
9972 continue;
9973 }
9974 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9975 continue;
9976 }
9977 if (!printed) {
9978 pw.println(" Active services:");
9979 printed = true;
9980 }
9981 if (needSep) {
9982 pw.println();
9983 }
9984 pw.print(" * ");
9985 pw.println(r);
9986 if (dumpAll) {
9987 r.dump(pw, " ");
9988 needSep = true;
9989 } else {
9990 pw.print(" app=");
9991 pw.println(r.app);
9992 pw.print(" created=");
9993 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9994 pw.print(" started=");
9995 pw.print(r.startRequested);
9996 pw.print(" connections=");
9997 pw.println(r.connections.size());
9998 if (r.connections.size() > 0) {
9999 pw.println(" Connections:");
10000 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
10001 for (int i = 0; i < clist.size(); i++) {
10002 ConnectionRecord conn = clist.get(i);
10003 pw.print(" ");
10004 pw.print(conn.binding.intent.intent.getIntent()
10005 .toShortString(false, false, false));
10006 pw.print(" -> ");
10007 ProcessRecord proc = conn.binding.client;
10008 pw.println(proc != null ? proc.toShortString() : "null");
10009 }
10010 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -080010011 }
10012 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010013 if (dumpClient && r.app != null && r.app.thread != null) {
10014 pw.println(" Client:");
10015 pw.flush();
10016 try {
10017 TransferPipe tp = new TransferPipe();
10018 try {
10019 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
10020 r, args);
10021 tp.setBufferPrefix(" ");
10022 // Short timeout, since blocking here can
10023 // deadlock with the application.
10024 tp.go(fd, 2000);
10025 } finally {
10026 tp.kill();
10027 }
10028 } catch (IOException e) {
10029 pw.println(" Failure while dumping the service: " + e);
10030 } catch (RemoteException e) {
10031 pw.println(" Got a RemoteException while dumping the service");
10032 }
10033 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010034 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010035 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010036 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010038 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010039 } catch (RemoteException re) {
10040
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010042
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010043 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010044 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010045 for (int i=0; i<mPendingServices.size(); i++) {
10046 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010047 if (!matcher.match(r, r.name)) {
10048 continue;
10049 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010050 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
10051 continue;
10052 }
10053 if (!printed) {
10054 if (needSep) pw.println(" ");
10055 needSep = true;
10056 pw.println(" Pending services:");
10057 printed = true;
10058 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010059 pw.print(" * Pending "); pw.println(r);
10060 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010061 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010062 needSep = true;
10063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010064
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010065 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010066 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010067 for (int i=0; i<mRestartingServices.size(); i++) {
10068 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010069 if (!matcher.match(r, r.name)) {
10070 continue;
10071 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010072 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
10073 continue;
10074 }
10075 if (!printed) {
10076 if (needSep) pw.println(" ");
10077 needSep = true;
10078 pw.println(" Restarting services:");
10079 printed = true;
10080 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010081 pw.print(" * Restarting "); pw.println(r);
10082 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010083 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010084 needSep = true;
10085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010086
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010087 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010088 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010089 for (int i=0; i<mStoppingServices.size(); i++) {
10090 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010091 if (!matcher.match(r, r.name)) {
10092 continue;
10093 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010094 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
10095 continue;
10096 }
10097 if (!printed) {
10098 if (needSep) pw.println(" ");
10099 needSep = true;
10100 pw.println(" Stopping services:");
10101 printed = true;
10102 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010103 pw.print(" * Stopping "); pw.println(r);
10104 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010105 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010106 needSep = true;
10107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010108
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010109 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010110 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010111 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010112 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010113 = mServiceConnections.values().iterator();
10114 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010115 ArrayList<ConnectionRecord> r = it.next();
10116 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010117 ConnectionRecord cr = r.get(i);
10118 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
10119 continue;
10120 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010121 if (dumpPackage != null && (cr.binding.client == null
10122 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
10123 continue;
10124 }
10125 if (!printed) {
10126 if (needSep) pw.println(" ");
10127 needSep = true;
10128 pw.println(" Connection bindings to services:");
10129 printed = true;
10130 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010131 pw.print(" * "); pw.println(cr);
10132 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010134 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010135 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010136 }
10137 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010138
10139 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010140 }
10141
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010142 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010143 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010144 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010145
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010146 ItemMatcher matcher = new ItemMatcher();
10147 matcher.build(args, opti);
10148
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010149 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -070010150
10151 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010152
10153 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010154 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010155 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010156 ContentProviderRecord r = mLaunchingProviders.get(i);
10157 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
10158 continue;
10159 }
10160 if (!printed) {
10161 if (needSep) pw.println(" ");
10162 needSep = true;
10163 pw.println(" Launching content providers:");
10164 printed = true;
10165 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010166 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010167 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010168 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010169 }
10170
10171 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010172 if (needSep) pw.println();
10173 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010174 pw.println("Granted Uri Permissions:");
10175 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
10176 int uid = mGrantedUriPermissions.keyAt(i);
10177 HashMap<Uri, UriPermission> perms
10178 = mGrantedUriPermissions.valueAt(i);
10179 pw.print(" * UID "); pw.print(uid);
10180 pw.println(" holds:");
10181 for (UriPermission perm : perms.values()) {
10182 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010183 if (dumpAll) {
10184 perm.dump(pw, " ");
10185 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010186 }
10187 }
10188 needSep = true;
10189 }
10190
10191 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010192 }
10193
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010194 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010195 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010196 boolean needSep = false;
10197
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010198 if (mIntentSenderRecords.size() > 0) {
10199 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010200 Iterator<WeakReference<PendingIntentRecord>> it
10201 = mIntentSenderRecords.values().iterator();
10202 while (it.hasNext()) {
10203 WeakReference<PendingIntentRecord> ref = it.next();
10204 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010205 if (dumpPackage != null && (rec == null
10206 || !dumpPackage.equals(rec.key.packageName))) {
10207 continue;
10208 }
10209 if (!printed) {
10210 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
10211 printed = true;
10212 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010213 needSep = true;
10214 if (rec != null) {
10215 pw.print(" * "); pw.println(rec);
10216 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010217 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010218 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010219 } else {
10220 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010221 }
10222 }
10223 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010224
10225 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010226 }
10227
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010228 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010229 String prefix, String label, boolean complete, boolean brief, boolean client,
10230 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010231 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010232 boolean needNL = false;
10233 final String innerPrefix = prefix + " ";
10234 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010235 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010236 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010237 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
10238 continue;
10239 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -070010240 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010241 if (needNL) {
10242 pw.println(" ");
10243 needNL = false;
10244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010245 if (lastTask != r.task) {
10246 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010247 pw.print(prefix);
10248 pw.print(full ? "* " : " ");
10249 pw.println(lastTask);
10250 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010251 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010252 } else if (complete) {
10253 // Complete + brief == give a summary. Isn't that obvious?!?
10254 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010255 pw.print(prefix); pw.print(" ");
10256 pw.println(lastTask.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010257 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010259 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010260 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
10261 pw.print(" #"); pw.print(i); pw.print(": ");
10262 pw.println(r);
10263 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010264 r.dump(pw, innerPrefix);
10265 } else if (complete) {
10266 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010267 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010268 if (r.app != null) {
10269 pw.print(innerPrefix); pw.println(r.app);
10270 }
10271 }
10272 if (client && r.app != null && r.app.thread != null) {
10273 // flush anything that is already in the PrintWriter since the thread is going
10274 // to write to the file descriptor directly
10275 pw.flush();
10276 try {
10277 TransferPipe tp = new TransferPipe();
10278 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -080010279 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
10280 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010281 // Short timeout, since blocking here can
10282 // deadlock with the application.
10283 tp.go(fd, 2000);
10284 } finally {
10285 tp.kill();
10286 }
10287 } catch (IOException e) {
10288 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
10289 } catch (RemoteException e) {
10290 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
10291 }
10292 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010294 }
10295 }
10296
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010297 private static String buildOomTag(String prefix, String space, int val, int base) {
10298 if (val == base) {
10299 if (space == null) return prefix;
10300 return prefix + " ";
10301 }
10302 return prefix + "+" + Integer.toString(val-base);
10303 }
10304
10305 private static final int dumpProcessList(PrintWriter pw,
10306 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010307 String prefix, String normalLabel, String persistentLabel,
10308 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010309 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010310 final int N = list.size()-1;
10311 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010312 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010313 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10314 continue;
10315 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010316 pw.println(String.format("%s%s #%2d: %s",
10317 prefix, (r.persistent ? persistentLabel : normalLabel),
10318 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010319 if (r.persistent) {
10320 numPers++;
10321 }
10322 }
10323 return numPers;
10324 }
10325
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010326 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010327 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010328 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010329 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010330
Dianne Hackborn905577f2011-09-07 18:31:28 -070010331 ArrayList<Pair<ProcessRecord, Integer>> list
10332 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10333 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010334 ProcessRecord r = origList.get(i);
10335 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10336 continue;
10337 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010338 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10339 }
10340
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010341 if (list.size() <= 0) {
10342 return false;
10343 }
10344
Dianne Hackborn905577f2011-09-07 18:31:28 -070010345 Comparator<Pair<ProcessRecord, Integer>> comparator
10346 = new Comparator<Pair<ProcessRecord, Integer>>() {
10347 @Override
10348 public int compare(Pair<ProcessRecord, Integer> object1,
10349 Pair<ProcessRecord, Integer> object2) {
10350 if (object1.first.setAdj != object2.first.setAdj) {
10351 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10352 }
10353 if (object1.second.intValue() != object2.second.intValue()) {
10354 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10355 }
10356 return 0;
10357 }
10358 };
10359
10360 Collections.sort(list, comparator);
10361
Dianne Hackborn287952c2010-09-22 22:34:31 -070010362 final long curRealtime = SystemClock.elapsedRealtime();
10363 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10364 final long curUptime = SystemClock.uptimeMillis();
10365 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10366
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010367 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010368 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010369 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010370 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010371 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010372 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10373 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010374 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10375 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010376 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10377 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010378 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10379 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010380 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010381 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010382 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10383 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10384 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10385 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10386 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10387 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10388 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10389 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010390 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10391 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010392 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10393 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010394 } else {
10395 oomAdj = Integer.toString(r.setAdj);
10396 }
10397 String schedGroup;
10398 switch (r.setSchedGroup) {
10399 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10400 schedGroup = "B";
10401 break;
10402 case Process.THREAD_GROUP_DEFAULT:
10403 schedGroup = "F";
10404 break;
10405 default:
10406 schedGroup = Integer.toString(r.setSchedGroup);
10407 break;
10408 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010409 String foreground;
10410 if (r.foregroundActivities) {
10411 foreground = "A";
10412 } else if (r.foregroundServices) {
10413 foreground = "S";
10414 } else {
10415 foreground = " ";
10416 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010417 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010418 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010419 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10420 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010421 if (r.adjSource != null || r.adjTarget != null) {
10422 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010423 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010424 if (r.adjTarget instanceof ComponentName) {
10425 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10426 } else if (r.adjTarget != null) {
10427 pw.print(r.adjTarget.toString());
10428 } else {
10429 pw.print("{null}");
10430 }
10431 pw.print("<=");
10432 if (r.adjSource instanceof ProcessRecord) {
10433 pw.print("Proc{");
10434 pw.print(((ProcessRecord)r.adjSource).toShortString());
10435 pw.println("}");
10436 } else if (r.adjSource != null) {
10437 pw.println(r.adjSource.toString());
10438 } else {
10439 pw.println("{null}");
10440 }
10441 }
10442 if (inclDetails) {
10443 pw.print(prefix);
10444 pw.print(" ");
10445 pw.print("oom: max="); pw.print(r.maxAdj);
10446 pw.print(" hidden="); pw.print(r.hiddenAdj);
10447 pw.print(" curRaw="); pw.print(r.curRawAdj);
10448 pw.print(" setRaw="); pw.print(r.setRawAdj);
10449 pw.print(" cur="); pw.print(r.curAdj);
10450 pw.print(" set="); pw.println(r.setAdj);
10451 pw.print(prefix);
10452 pw.print(" ");
10453 pw.print("keeping="); pw.print(r.keeping);
10454 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010455 pw.print(" empty="); pw.print(r.empty);
10456 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010457
10458 if (!r.keeping) {
10459 if (r.lastWakeTime != 0) {
10460 long wtime;
10461 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10462 synchronized (stats) {
10463 wtime = stats.getProcessWakeTime(r.info.uid,
10464 r.pid, curRealtime);
10465 }
10466 long timeUsed = wtime - r.lastWakeTime;
10467 pw.print(prefix);
10468 pw.print(" ");
10469 pw.print("keep awake over ");
10470 TimeUtils.formatDuration(realtimeSince, pw);
10471 pw.print(" used ");
10472 TimeUtils.formatDuration(timeUsed, pw);
10473 pw.print(" (");
10474 pw.print((timeUsed*100)/realtimeSince);
10475 pw.println("%)");
10476 }
10477 if (r.lastCpuTime != 0) {
10478 long timeUsed = r.curCpuTime - r.lastCpuTime;
10479 pw.print(prefix);
10480 pw.print(" ");
10481 pw.print("run cpu over ");
10482 TimeUtils.formatDuration(uptimeSince, pw);
10483 pw.print(" used ");
10484 TimeUtils.formatDuration(timeUsed, pw);
10485 pw.print(" (");
10486 pw.print((timeUsed*100)/uptimeSince);
10487 pw.println("%)");
10488 }
10489 }
10490 }
10491 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010492 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010493 }
10494
Dianne Hackbornb437e092011-08-05 17:50:29 -070010495 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010496 ArrayList<ProcessRecord> procs;
10497 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010498 if (args != null && args.length > start
10499 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010500 procs = new ArrayList<ProcessRecord>();
10501 int pid = -1;
10502 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010503 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010504 } catch (NumberFormatException e) {
10505
10506 }
10507 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10508 ProcessRecord proc = mLruProcesses.get(i);
10509 if (proc.pid == pid) {
10510 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010511 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010512 procs.add(proc);
10513 }
10514 }
10515 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010516 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010517 return null;
10518 }
10519 } else {
10520 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10521 }
10522 }
10523 return procs;
10524 }
10525
10526 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10527 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010528 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010529 if (procs == null) {
10530 return;
10531 }
10532
10533 long uptime = SystemClock.uptimeMillis();
10534 long realtime = SystemClock.elapsedRealtime();
10535 pw.println("Applications Graphics Acceleration Info:");
10536 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10537
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010538 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10539 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010540 if (r.thread != null) {
10541 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10542 pw.flush();
10543 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010544 TransferPipe tp = new TransferPipe();
10545 try {
10546 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10547 tp.go(fd);
10548 } finally {
10549 tp.kill();
10550 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010551 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010552 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010553 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010554 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010555 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010556 pw.flush();
10557 }
10558 }
10559 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010560 }
10561
Jeff Brown6754ba22011-12-14 20:20:01 -080010562 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10563 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10564 if (procs == null) {
10565 return;
10566 }
10567
10568 pw.println("Applications Database Info:");
10569
10570 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10571 ProcessRecord r = procs.get(i);
10572 if (r.thread != null) {
10573 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10574 pw.flush();
10575 try {
10576 TransferPipe tp = new TransferPipe();
10577 try {
10578 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10579 tp.go(fd);
10580 } finally {
10581 tp.kill();
10582 }
10583 } catch (IOException e) {
10584 pw.println("Failure while dumping the app: " + r);
10585 pw.flush();
10586 } catch (RemoteException e) {
10587 pw.println("Got a RemoteException while dumping the app " + r);
10588 pw.flush();
10589 }
10590 }
10591 }
10592 }
10593
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010594 final static class MemItem {
10595 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010596 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010597 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010598 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010599 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010600
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010601 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010602 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010603 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010604 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010605 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010606 }
10607 }
10608
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010609 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010610 boolean sort) {
10611 if (sort) {
10612 Collections.sort(items, new Comparator<MemItem>() {
10613 @Override
10614 public int compare(MemItem lhs, MemItem rhs) {
10615 if (lhs.pss < rhs.pss) {
10616 return 1;
10617 } else if (lhs.pss > rhs.pss) {
10618 return -1;
10619 }
10620 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010621 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010622 });
10623 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010624
10625 for (int i=0; i<items.size(); i++) {
10626 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010627 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010628 if (mi.subitems != null) {
10629 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10630 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010631 }
10632 }
10633
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010634 // These are in KB.
10635 static final long[] DUMP_MEM_BUCKETS = new long[] {
10636 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10637 120*1024, 160*1024, 200*1024,
10638 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10639 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10640 };
10641
Dianne Hackborn672342c2011-11-29 11:29:02 -080010642 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10643 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010644 int start = label.lastIndexOf('.');
10645 if (start >= 0) start++;
10646 else start = 0;
10647 int end = label.length();
10648 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10649 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10650 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10651 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010652 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010653 out.append(label, start, end);
10654 return;
10655 }
10656 }
10657 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010658 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010659 out.append(label, start, end);
10660 }
10661
10662 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10663 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10664 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10665 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10666 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10667 };
10668 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10669 "System", "Persistent", "Foreground",
10670 "Visible", "Perceptible", "Heavy Weight",
10671 "Backup", "A Services", "Home", "Previous",
10672 "B Services", "Background"
10673 };
10674
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010675 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010676 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010677 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010678 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010679 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010680
10681 int opti = 0;
10682 while (opti < args.length) {
10683 String opt = args[opti];
10684 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10685 break;
10686 }
10687 opti++;
10688 if ("-a".equals(opt)) {
10689 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010690 } else if ("--oom".equals(opt)) {
10691 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010692 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010693 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010694 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010695 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010696 pw.println("If [process] is specified it can be the name or ");
10697 pw.println("pid of a specific process to dump.");
10698 return;
10699 } else {
10700 pw.println("Unknown argument: " + opt + "; use -h for help");
10701 }
10702 }
10703
10704 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010705 if (procs == null) {
10706 return;
10707 }
10708
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010709 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010710 long uptime = SystemClock.uptimeMillis();
10711 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010712
10713 if (procs.size() == 1 || isCheckinRequest) {
10714 dumpAll = true;
10715 }
10716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010717 if (isCheckinRequest) {
10718 // short checkin version
10719 pw.println(uptime + "," + realtime);
10720 pw.flush();
10721 } else {
10722 pw.println("Applications Memory Usage (kB):");
10723 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10724 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010725
Dianne Hackbornb437e092011-08-05 17:50:29 -070010726 String[] innerArgs = new String[args.length-opti];
10727 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10728
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010729 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10730 long nativePss=0, dalvikPss=0, otherPss=0;
10731 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10732
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010733 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10734 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10735 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010736
10737 long totalPss = 0;
10738
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010739 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10740 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010741 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010742 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010743 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10744 pw.flush();
10745 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010746 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010747 if (dumpAll) {
10748 try {
10749 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10750 } catch (RemoteException e) {
10751 if (!isCheckinRequest) {
10752 pw.println("Got RemoteException!");
10753 pw.flush();
10754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010755 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010756 } else {
10757 mi = new Debug.MemoryInfo();
10758 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010759 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010760
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010761 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010762 long myTotalPss = mi.getTotalPss();
10763 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010764 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010765 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010766 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010767
10768 nativePss += mi.nativePss;
10769 dalvikPss += mi.dalvikPss;
10770 otherPss += mi.otherPss;
10771 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10772 long mem = mi.getOtherPss(j);
10773 miscPss[j] += mem;
10774 otherPss -= mem;
10775 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010776
10777 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010778 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10779 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010780 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010781 if (oomProcs[oomIndex] == null) {
10782 oomProcs[oomIndex] = new ArrayList<MemItem>();
10783 }
10784 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010785 break;
10786 }
10787 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010789 }
10790 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010791
10792 if (!isCheckinRequest && procs.size() > 1) {
10793 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10794
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010795 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10796 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10797 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010798 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010799 String label = Debug.MemoryInfo.getOtherLabel(j);
10800 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010801 }
10802
Dianne Hackbornb437e092011-08-05 17:50:29 -070010803 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10804 for (int j=0; j<oomPss.length; j++) {
10805 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010806 String label = DUMP_MEM_OOM_LABEL[j];
10807 MemItem item = new MemItem(label, label, oomPss[j],
10808 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010809 item.subitems = oomProcs[j];
10810 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010811 }
10812 }
10813
Dianne Hackborn672342c2011-11-29 11:29:02 -080010814 if (outTag != null || outStack != null) {
10815 if (outTag != null) {
10816 appendMemBucket(outTag, totalPss, "total", false);
10817 }
10818 if (outStack != null) {
10819 appendMemBucket(outStack, totalPss, "total", true);
10820 }
10821 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010822 for (int i=0; i<oomMems.size(); i++) {
10823 MemItem miCat = oomMems.get(i);
10824 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10825 continue;
10826 }
10827 if (miCat.id < ProcessList.SERVICE_ADJ
10828 || miCat.id == ProcessList.HOME_APP_ADJ
10829 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010830 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10831 outTag.append(" / ");
10832 }
10833 if (outStack != null) {
10834 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10835 if (firstLine) {
10836 outStack.append(":");
10837 firstLine = false;
10838 }
10839 outStack.append("\n\t at ");
10840 } else {
10841 outStack.append("$");
10842 }
10843 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010844 for (int j=0; j<miCat.subitems.size(); j++) {
10845 MemItem mi = miCat.subitems.get(j);
10846 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010847 if (outTag != null) {
10848 outTag.append(" ");
10849 }
10850 if (outStack != null) {
10851 outStack.append("$");
10852 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010853 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010854 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10855 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10856 }
10857 if (outStack != null) {
10858 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10859 }
10860 }
10861 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10862 outStack.append("(");
10863 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10864 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10865 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10866 outStack.append(":");
10867 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10868 }
10869 }
10870 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010871 }
10872 }
10873 }
10874 }
10875
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010876 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010877 pw.println();
10878 pw.println("Total PSS by process:");
10879 dumpMemItems(pw, " ", procMems, true);
10880 pw.println();
10881 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010882 pw.println("Total PSS by OOM adjustment:");
10883 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010884 if (!oomOnly) {
10885 PrintWriter out = categoryPw != null ? categoryPw : pw;
10886 out.println();
10887 out.println("Total PSS by category:");
10888 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010889 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010890 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010891 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010893 }
10894
10895 /**
10896 * Searches array of arguments for the specified string
10897 * @param args array of argument strings
10898 * @param value value to search for
10899 * @return true if the value is contained in the array
10900 */
10901 private static boolean scanArgs(String[] args, String value) {
10902 if (args != null) {
10903 for (String arg : args) {
10904 if (value.equals(arg)) {
10905 return true;
10906 }
10907 }
10908 }
10909 return false;
10910 }
10911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010912 private final void killServicesLocked(ProcessRecord app,
10913 boolean allowRestart) {
10914 // Report disconnected services.
10915 if (false) {
10916 // XXX we are letting the client link to the service for
10917 // death notifications.
10918 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010919 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010920 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010921 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010923 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010924 = r.connections.values().iterator();
10925 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010926 ArrayList<ConnectionRecord> cl = jt.next();
10927 for (int i=0; i<cl.size(); i++) {
10928 ConnectionRecord c = cl.get(i);
10929 if (c.binding.client != app) {
10930 try {
10931 //c.conn.connected(r.className, null);
10932 } catch (Exception e) {
10933 // todo: this should be asynchronous!
10934 Slog.w(TAG, "Exception thrown disconnected servce "
10935 + r.shortName
10936 + " from app " + app.processName, e);
10937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010938 }
10939 }
10940 }
10941 }
10942 }
10943 }
10944 }
10945
10946 // Clean up any connections this application has to other services.
10947 if (app.connections.size() > 0) {
10948 Iterator<ConnectionRecord> it = app.connections.iterator();
10949 while (it.hasNext()) {
10950 ConnectionRecord r = it.next();
10951 removeConnectionLocked(r, app, null);
10952 }
10953 }
10954 app.connections.clear();
10955
10956 if (app.services.size() != 0) {
10957 // Any services running in the application need to be placed
10958 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010959 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010961 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010962 synchronized (sr.stats.getBatteryStats()) {
10963 sr.stats.stopLaunchedLocked();
10964 }
10965 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010966 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010967 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010968 if (mStoppingServices.remove(sr)) {
10969 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10970 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010971
10972 boolean hasClients = sr.bindings.size() > 0;
10973 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010974 Iterator<IntentBindRecord> bindings
10975 = sr.bindings.values().iterator();
10976 while (bindings.hasNext()) {
10977 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010978 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010979 + ": shouldUnbind=" + b.hasBound);
10980 b.binder = null;
10981 b.requested = b.received = b.hasBound = false;
10982 }
10983 }
10984
Dianne Hackborn070783f2010-12-29 16:46:28 -080010985 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10986 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010987 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010988 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010989 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010990 sr.crashCount, sr.shortName, app.pid);
10991 bringDownServiceLocked(sr, true);
10992 } else if (!allowRestart) {
10993 bringDownServiceLocked(sr, true);
10994 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010995 boolean canceled = scheduleServiceRestartLocked(sr, true);
10996
10997 // Should the service remain running? Note that in the
10998 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010999 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011000 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
11001 if (sr.pendingStarts.size() == 0) {
11002 sr.startRequested = false;
11003 if (!hasClients) {
11004 // Whoops, no reason to restart!
11005 bringDownServiceLocked(sr, true);
11006 }
11007 }
11008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011009 }
11010 }
11011
11012 if (!allowRestart) {
11013 app.services.clear();
11014 }
11015 }
11016
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011017 // Make sure we have no more records on the stopping list.
11018 int i = mStoppingServices.size();
11019 while (i > 0) {
11020 i--;
11021 ServiceRecord sr = mStoppingServices.get(i);
11022 if (sr.app == app) {
11023 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011024 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011025 }
11026 }
11027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011028 app.executingServices.clear();
11029 }
11030
11031 private final void removeDyingProviderLocked(ProcessRecord proc,
11032 ContentProviderRecord cpr) {
11033 synchronized (cpr) {
11034 cpr.launchingApp = null;
11035 cpr.notifyAll();
11036 }
11037
Amith Yamasani742a6712011-05-04 14:49:28 -070011038 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039 String names[] = cpr.info.authority.split(";");
11040 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011041 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011042 }
11043
11044 Iterator<ProcessRecord> cit = cpr.clients.iterator();
11045 while (cit.hasNext()) {
11046 ProcessRecord capp = cit.next();
11047 if (!capp.persistent && capp.thread != null
11048 && capp.pid != 0
11049 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011050 Slog.i(TAG, "Kill " + capp.processName
11051 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070011052 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070011053 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070011054 capp.processName, capp.setAdj, "dying provider "
11055 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011056 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011057 }
11058 }
11059
11060 mLaunchingProviders.remove(cpr);
11061 }
11062
11063 /**
11064 * Main code for cleaning up a process when it has gone away. This is
11065 * called both as a result of the process dying, or directly when stopping
11066 * a process when running in single process mode.
11067 */
11068 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011069 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011070 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011071 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011072 }
11073
Dianne Hackborn36124872009-10-08 16:22:03 -070011074 mProcessesToGc.remove(app);
11075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011076 // Dismiss any open dialogs.
11077 if (app.crashDialog != null) {
11078 app.crashDialog.dismiss();
11079 app.crashDialog = null;
11080 }
11081 if (app.anrDialog != null) {
11082 app.anrDialog.dismiss();
11083 app.anrDialog = null;
11084 }
11085 if (app.waitDialog != null) {
11086 app.waitDialog.dismiss();
11087 app.waitDialog = null;
11088 }
11089
11090 app.crashing = false;
11091 app.notResponding = false;
11092
11093 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070011094 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011095 app.thread = null;
11096 app.forcingToForeground = null;
11097 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070011098 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070011099 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011100 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011101
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011102 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011103
11104 boolean restart = false;
11105
11106 int NL = mLaunchingProviders.size();
11107
11108 // Remove published content providers.
11109 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011110 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011111 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011112 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011113 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070011114 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011115
11116 // See if someone is waiting for this provider... in which
11117 // case we don't remove it, but just let it restart.
11118 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011119 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011120 for (; i<NL; i++) {
11121 if (mLaunchingProviders.get(i) == cpr) {
11122 restart = true;
11123 break;
11124 }
11125 }
11126 } else {
11127 i = NL;
11128 }
11129
11130 if (i >= NL) {
11131 removeDyingProviderLocked(app, cpr);
11132 NL = mLaunchingProviders.size();
11133 }
11134 }
11135 app.pubProviders.clear();
11136 }
11137
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011138 // Take care of any launching providers waiting for this process.
11139 if (checkAppInLaunchingProvidersLocked(app, false)) {
11140 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011141 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011143 // Unregister from connected content providers.
11144 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070011145 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011146 while (it.hasNext()) {
11147 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
11148 cpr.clients.remove(app);
11149 }
11150 app.conProviders.clear();
11151 }
11152
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011153 // At this point there may be remaining entries in mLaunchingProviders
11154 // where we were the only one waiting, so they are no longer of use.
11155 // Look for these and clean up if found.
11156 // XXX Commented out for now. Trying to figure out a way to reproduce
11157 // the actual situation to identify what is actually going on.
11158 if (false) {
11159 for (int i=0; i<NL; i++) {
11160 ContentProviderRecord cpr = (ContentProviderRecord)
11161 mLaunchingProviders.get(i);
11162 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
11163 synchronized (cpr) {
11164 cpr.launchingApp = null;
11165 cpr.notifyAll();
11166 }
11167 }
11168 }
11169 }
11170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011171 skipCurrentReceiverLocked(app);
11172
11173 // Unregister any receivers.
11174 if (app.receivers.size() > 0) {
11175 Iterator<ReceiverList> it = app.receivers.iterator();
11176 while (it.hasNext()) {
11177 removeReceiverLocked(it.next());
11178 }
11179 app.receivers.clear();
11180 }
11181
Christopher Tate181fafa2009-05-14 11:12:14 -070011182 // If the app is undergoing backup, tell the backup manager about it
11183 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011184 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070011185 try {
11186 IBackupManager bm = IBackupManager.Stub.asInterface(
11187 ServiceManager.getService(Context.BACKUP_SERVICE));
11188 bm.agentDisconnected(app.info.packageName);
11189 } catch (RemoteException e) {
11190 // can't happen; backup manager is local
11191 }
11192 }
11193
Jeff Sharkey287bd832011-05-28 19:36:26 -070011194 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070011195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011196 // If the caller is restarting this app, then leave it in its
11197 // current lists and let the caller take care of it.
11198 if (restarting) {
11199 return;
11200 }
11201
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011202 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011203 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011205 mProcessNames.remove(app.processName, app.uid);
11206 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070011207 if (mHeavyWeightProcess == app) {
11208 mHeavyWeightProcess = null;
11209 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
11210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 } else if (!app.removed) {
11212 // This app is persistent, so we need to keep its record around.
11213 // If it is not already on the pending app list, add it there
11214 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011215 if (mPersistentStartingProcesses.indexOf(app) < 0) {
11216 mPersistentStartingProcesses.add(app);
11217 restart = true;
11218 }
11219 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011220 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
11221 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011222 mProcessesOnHold.remove(app);
11223
The Android Open Source Project4df24232009-03-05 14:34:35 -080011224 if (app == mHomeProcess) {
11225 mHomeProcess = null;
11226 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070011227 if (app == mPreviousProcess) {
11228 mPreviousProcess = null;
11229 }
11230
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011231 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011232 // We have components that still need to be running in the
11233 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011234 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011235 startProcessLocked(app, "restart", app.processName);
11236 } else if (app.pid > 0 && app.pid != MY_PID) {
11237 // Goodbye!
11238 synchronized (mPidsSelfLocked) {
11239 mPidsSelfLocked.remove(app.pid);
11240 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
11241 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070011242 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011243 }
11244 }
11245
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011246 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
11247 // Look through the content providers we are waiting to have launched,
11248 // and if any run in this process then either schedule a restart of
11249 // the process or kill the client waiting for it if this process has
11250 // gone bad.
11251 int NL = mLaunchingProviders.size();
11252 boolean restart = false;
11253 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011254 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011255 if (cpr.launchingApp == app) {
11256 if (!alwaysBad && !app.bad) {
11257 restart = true;
11258 } else {
11259 removeDyingProviderLocked(app, cpr);
11260 NL = mLaunchingProviders.size();
11261 }
11262 }
11263 }
11264 return restart;
11265 }
11266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011267 // =========================================================
11268 // SERVICES
11269 // =========================================================
11270
11271 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
11272 ActivityManager.RunningServiceInfo info =
11273 new ActivityManager.RunningServiceInfo();
11274 info.service = r.name;
11275 if (r.app != null) {
11276 info.pid = r.app.pid;
11277 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070011278 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011279 info.process = r.processName;
11280 info.foreground = r.isForeground;
11281 info.activeSince = r.createTime;
11282 info.started = r.startRequested;
11283 info.clientCount = r.connections.size();
11284 info.crashCount = r.crashCount;
11285 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070011286 if (r.isForeground) {
11287 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
11288 }
11289 if (r.startRequested) {
11290 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
11291 }
Dan Egnor42471dd2010-01-07 17:25:22 -080011292 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070011293 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
11294 }
11295 if (r.app != null && r.app.persistent) {
11296 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
11297 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011298
11299 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
11300 for (int i=0; i<connl.size(); i++) {
11301 ConnectionRecord conn = connl.get(i);
11302 if (conn.clientLabel != 0) {
11303 info.clientPackage = conn.binding.client.info.packageName;
11304 info.clientLabel = conn.clientLabel;
11305 return info;
11306 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011307 }
11308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011309 return info;
11310 }
11311
11312 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
11313 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011314 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011315 synchronized (this) {
11316 ArrayList<ActivityManager.RunningServiceInfo> res
11317 = new ArrayList<ActivityManager.RunningServiceInfo>();
11318
Amith Yamasani742a6712011-05-04 14:49:28 -070011319 int userId = UserId.getUserId(Binder.getCallingUid());
11320 if (mServiceMap.getAllServices(userId).size() > 0) {
11321 Iterator<ServiceRecord> it
11322 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011323 while (it.hasNext() && res.size() < maxNum) {
11324 res.add(makeRunningServiceInfoLocked(it.next()));
11325 }
11326 }
11327
11328 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
11329 ServiceRecord r = mRestartingServices.get(i);
11330 ActivityManager.RunningServiceInfo info =
11331 makeRunningServiceInfoLocked(r);
11332 info.restarting = r.nextRestartTime;
11333 res.add(info);
11334 }
11335
11336 return res;
11337 }
11338 }
11339
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011340 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011341 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011342 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011343 int userId = UserId.getUserId(Binder.getCallingUid());
11344 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011345 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011346 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
11347 for (int i=0; i<conn.size(); i++) {
11348 if (conn.get(i).clientIntent != null) {
11349 return conn.get(i).clientIntent;
11350 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011351 }
11352 }
11353 }
11354 }
11355 return null;
11356 }
11357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011358 private final ServiceRecord findServiceLocked(ComponentName name,
11359 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011360 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011361 return r == token ? r : null;
11362 }
11363
11364 private final class ServiceLookupResult {
11365 final ServiceRecord record;
11366 final String permission;
11367
11368 ServiceLookupResult(ServiceRecord _record, String _permission) {
11369 record = _record;
11370 permission = _permission;
11371 }
11372 };
11373
11374 private ServiceLookupResult findServiceLocked(Intent service,
11375 String resolvedType) {
11376 ServiceRecord r = null;
11377 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011378 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 }
11380 if (r == null) {
11381 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070011382 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011383 }
11384
11385 if (r == null) {
11386 try {
11387 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011388 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011389 service, resolvedType, 0);
11390 ServiceInfo sInfo =
11391 rInfo != null ? rInfo.serviceInfo : null;
11392 if (sInfo == null) {
11393 return null;
11394 }
11395
11396 ComponentName name = new ComponentName(
11397 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070011398 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011399 } catch (RemoteException ex) {
11400 // pm is in same process, this will never happen.
11401 }
11402 }
11403 if (r != null) {
11404 int callingPid = Binder.getCallingPid();
11405 int callingUid = Binder.getCallingUid();
11406 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011407 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011408 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011409 if (!r.exported) {
11410 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11411 + " from pid=" + callingPid
11412 + ", uid=" + callingUid
11413 + " that is not exported from uid " + r.appInfo.uid);
11414 return new ServiceLookupResult(null, "not exported from uid "
11415 + r.appInfo.uid);
11416 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011417 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 + " from pid=" + callingPid
11419 + ", uid=" + callingUid
11420 + " requires " + r.permission);
11421 return new ServiceLookupResult(null, r.permission);
11422 }
11423 return new ServiceLookupResult(r, null);
11424 }
11425 return null;
11426 }
11427
11428 private class ServiceRestarter implements Runnable {
11429 private ServiceRecord mService;
11430
11431 void setService(ServiceRecord service) {
11432 mService = service;
11433 }
11434
11435 public void run() {
11436 synchronized(ActivityManagerService.this) {
11437 performServiceRestartLocked(mService);
11438 }
11439 }
11440 }
11441
11442 private ServiceLookupResult retrieveServiceLocked(Intent service,
11443 String resolvedType, int callingPid, int callingUid) {
11444 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070011445 if (DEBUG_SERVICE)
11446 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
11447 + " origCallingUid=" + callingUid);
11448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011450 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011451 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011452 if (r == null) {
11453 Intent.FilterComparison filter = new Intent.FilterComparison(service);
11454 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
11455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011456 if (r == null) {
11457 try {
11458 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011459 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011460 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011461 ServiceInfo sInfo =
11462 rInfo != null ? rInfo.serviceInfo : null;
11463 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011464 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011465 ": not found");
11466 return null;
11467 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011468 if (Binder.getOrigCallingUser() > 0) {
11469 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo,
11470 Binder.getOrigCallingUser());
11471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011472 ComponentName name = new ComponentName(
11473 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070011474 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011475 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011476 Intent.FilterComparison filter = new Intent.FilterComparison(
11477 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011478 ServiceRestarter res = new ServiceRestarter();
11479 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11480 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11481 synchronized (stats) {
11482 ss = stats.getServiceStatsLocked(
11483 sInfo.applicationInfo.uid, sInfo.packageName,
11484 sInfo.name);
11485 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080011486 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011487 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070011488 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
11489 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011490
11491 // Make sure this component isn't in the pending list.
11492 int N = mPendingServices.size();
11493 for (int i=0; i<N; i++) {
11494 ServiceRecord pr = mPendingServices.get(i);
11495 if (pr.name.equals(name)) {
11496 mPendingServices.remove(i);
11497 i--;
11498 N--;
11499 }
11500 }
11501 }
11502 } catch (RemoteException ex) {
11503 // pm is in same process, this will never happen.
11504 }
11505 }
11506 if (r != null) {
11507 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011508 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011509 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011510 if (!r.exported) {
11511 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11512 + " from pid=" + callingPid
11513 + ", uid=" + callingUid
11514 + " that is not exported from uid " + r.appInfo.uid);
11515 return new ServiceLookupResult(null, "not exported from uid "
11516 + r.appInfo.uid);
11517 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011518 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011519 + " from pid=" + callingPid
11520 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011521 + " requires " + r.permission);
11522 return new ServiceLookupResult(null, r.permission);
11523 }
11524 return new ServiceLookupResult(r, null);
11525 }
11526 return null;
11527 }
11528
Dianne Hackborn287952c2010-09-22 22:34:31 -070011529 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11530 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11531 + why + " of " + r + " in app " + r.app);
11532 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11533 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011534 long now = SystemClock.uptimeMillis();
11535 if (r.executeNesting == 0 && r.app != null) {
11536 if (r.app.executingServices.size() == 0) {
11537 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11538 msg.obj = r.app;
11539 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11540 }
11541 r.app.executingServices.add(r);
11542 }
11543 r.executeNesting++;
11544 r.executingStart = now;
11545 }
11546
11547 private final void sendServiceArgsLocked(ServiceRecord r,
11548 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011549 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011550 if (N == 0) {
11551 return;
11552 }
11553
Dianne Hackborn39792d22010-08-19 18:01:52 -070011554 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011555 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011556 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011557 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11558 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011559 if (si.intent == null && N > 1) {
11560 // If somehow we got a dummy null intent in the middle,
11561 // then skip it. DO NOT skip a null intent when it is
11562 // the only one in the list -- this is to support the
11563 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011564 continue;
11565 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011566 si.deliveredTime = SystemClock.uptimeMillis();
11567 r.deliveredStarts.add(si);
11568 si.deliveryCount++;
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011569 if (si.targetPermissionUid >= 0 && si.intent != null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011570 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -070011571 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011572 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011573 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011574 if (!oomAdjusted) {
11575 oomAdjusted = true;
11576 updateOomAdjLocked(r.app);
11577 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011578 int flags = 0;
11579 if (si.deliveryCount > 0) {
11580 flags |= Service.START_FLAG_RETRY;
11581 }
11582 if (si.doneExecutingCount > 0) {
11583 flags |= Service.START_FLAG_REDELIVERY;
11584 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011585 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011586 } catch (RemoteException e) {
11587 // Remote process gone... we'll let the normal cleanup take
11588 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011589 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011590 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011591 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011592 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011593 break;
11594 }
11595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011596 }
11597
11598 private final boolean requestServiceBindingLocked(ServiceRecord r,
11599 IntentBindRecord i, boolean rebind) {
11600 if (r.app == null || r.app.thread == null) {
11601 // If service is not currently running, can't yet bind.
11602 return false;
11603 }
11604 if ((!i.requested || rebind) && i.apps.size() > 0) {
11605 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011606 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011607 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11608 if (!rebind) {
11609 i.requested = true;
11610 }
11611 i.hasBound = true;
11612 i.doRebind = false;
11613 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011614 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011615 return false;
11616 }
11617 }
11618 return true;
11619 }
11620
11621 private final void requestServiceBindingsLocked(ServiceRecord r) {
11622 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11623 while (bindings.hasNext()) {
11624 IntentBindRecord i = bindings.next();
11625 if (!requestServiceBindingLocked(r, i, false)) {
11626 break;
11627 }
11628 }
11629 }
11630
11631 private final void realStartServiceLocked(ServiceRecord r,
11632 ProcessRecord app) throws RemoteException {
11633 if (app.thread == null) {
11634 throw new RemoteException();
11635 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011636 if (DEBUG_MU)
11637 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011638 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011639 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011640 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011641
11642 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011643 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011644 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011645
11646 boolean created = false;
11647 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011648 mStringBuilder.setLength(0);
Dianne Hackborn90c52de2011-09-23 12:57:44 -070011649 r.intent.getIntent().toShortString(mStringBuilder, true, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011650 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011651 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011652 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011653 synchronized (r.stats.getBatteryStats()) {
11654 r.stats.startLaunchedLocked();
11655 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011656 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011657 app.thread.scheduleCreateService(r, r.serviceInfo,
11658 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011659 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011660 created = true;
11661 } finally {
11662 if (!created) {
11663 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011664 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011665 }
11666 }
11667
11668 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011669
11670 // If the service is in the started state, and there are no
11671 // pending arguments, then fake up one so its onStartCommand() will
11672 // be called.
11673 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011674 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
11675 null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011676 }
11677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011678 sendServiceArgsLocked(r, true);
11679 }
11680
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011681 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11682 boolean allowCancel) {
11683 boolean canceled = false;
11684
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011685 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011686 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011687 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011688
Dianne Hackborn070783f2010-12-29 16:46:28 -080011689 if ((r.serviceInfo.applicationInfo.flags
11690 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11691 minDuration /= 4;
11692 }
11693
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011694 // Any delivered but not yet finished starts should be put back
11695 // on the pending list.
11696 final int N = r.deliveredStarts.size();
11697 if (N > 0) {
11698 for (int i=N-1; i>=0; i--) {
11699 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011700 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011701 if (si.intent == null) {
11702 // We'll generate this again if needed.
11703 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11704 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11705 r.pendingStarts.add(0, si);
11706 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11707 dur *= 2;
11708 if (minDuration < dur) minDuration = dur;
11709 if (resetTime < dur) resetTime = dur;
11710 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011711 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011712 + r.name);
11713 canceled = true;
11714 }
11715 }
11716 r.deliveredStarts.clear();
11717 }
11718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011719 r.totalRestartCount++;
11720 if (r.restartDelay == 0) {
11721 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011722 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011723 } else {
11724 // If it has been a "reasonably long time" since the service
11725 // was started, then reset our restart duration back to
11726 // the beginning, so we don't infinitely increase the duration
11727 // on a service that just occasionally gets killed (which is
11728 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011729 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011730 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011731 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011732 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011733 if ((r.serviceInfo.applicationInfo.flags
11734 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11735 // Services in peristent processes will restart much more
11736 // quickly, since they are pretty important. (Think SystemUI).
11737 r.restartDelay += minDuration/2;
11738 } else {
11739 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11740 if (r.restartDelay < minDuration) {
11741 r.restartDelay = minDuration;
11742 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011744 }
11745 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011746
11747 r.nextRestartTime = now + r.restartDelay;
11748
11749 // Make sure that we don't end up restarting a bunch of services
11750 // all at the same time.
11751 boolean repeat;
11752 do {
11753 repeat = false;
11754 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11755 ServiceRecord r2 = mRestartingServices.get(i);
11756 if (r2 != r && r.nextRestartTime
11757 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11758 && r.nextRestartTime
11759 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11760 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11761 r.restartDelay = r.nextRestartTime - now;
11762 repeat = true;
11763 break;
11764 }
11765 }
11766 } while (repeat);
11767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011768 if (!mRestartingServices.contains(r)) {
11769 mRestartingServices.add(r);
11770 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011771
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011772 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011774 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011775 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011776 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011777 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011778 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011779 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011780 r.shortName, r.restartDelay);
11781
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011782 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011783 }
11784
11785 final void performServiceRestartLocked(ServiceRecord r) {
11786 if (!mRestartingServices.contains(r)) {
11787 return;
11788 }
11789 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11790 }
11791
11792 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11793 if (r.restartDelay == 0) {
11794 return false;
11795 }
11796 r.resetRestartCounter();
11797 mRestartingServices.remove(r);
11798 mHandler.removeCallbacks(r.restarter);
11799 return true;
11800 }
11801
11802 private final boolean bringUpServiceLocked(ServiceRecord r,
11803 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011804 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011805 //r.dump(" ");
11806
Dianne Hackborn36124872009-10-08 16:22:03 -070011807 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011808 sendServiceArgsLocked(r, false);
11809 return true;
11810 }
11811
11812 if (!whileRestarting && r.restartDelay > 0) {
11813 // If waiting for a restart, then do nothing.
11814 return true;
11815 }
11816
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011817 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011818
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011819 // We are now bringing the service up, so no longer in the
11820 // restarting state.
11821 mRestartingServices.remove(r);
11822
Dianne Hackborne7f97212011-02-24 14:40:20 -080011823 // Service is now being launched, its package can't be stopped.
11824 try {
11825 AppGlobals.getPackageManager().setPackageStoppedState(
11826 r.packageName, false);
11827 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011828 } catch (IllegalArgumentException e) {
11829 Slog.w(TAG, "Failed trying to unstop package "
11830 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011831 }
11832
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011833 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011834 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011835 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011836
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011837 if (!isolated) {
11838 app = getProcessRecordLocked(appName, r.appInfo.uid);
11839 if (DEBUG_MU)
11840 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11841 if (app != null && app.thread != null) {
11842 try {
11843 app.addPackage(r.appInfo.packageName);
11844 realStartServiceLocked(r, app);
11845 return true;
11846 } catch (RemoteException e) {
11847 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11848 }
11849
11850 // If a dead object exception was thrown -- fall through to
11851 // restart the application.
11852 }
11853 } else {
11854 // If this service runs in an isolated process, then each time
11855 // we call startProcessLocked() we will get a new isolated
11856 // process, starting another process if we are currently waiting
11857 // for a previous process to come up. To deal with this, we store
11858 // in the service any current isolated process it is running in or
11859 // waiting to have come up.
11860 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011861 }
11862
Dianne Hackborn36124872009-10-08 16:22:03 -070011863 // Not running -- get it started, and enqueue this service record
11864 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011865 if (app == null) {
11866 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11867 "service", r.name, false, isolated)) == null) {
11868 Slog.w(TAG, "Unable to launch app "
11869 + r.appInfo.packageName + "/"
11870 + r.appInfo.uid + " for service "
11871 + r.intent.getIntent() + ": process is bad");
11872 bringDownServiceLocked(r, true);
11873 return false;
11874 }
11875 if (isolated) {
11876 r.isolatedProc = app;
11877 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011878 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011880 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011881 mPendingServices.add(r);
11882 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011884 return true;
11885 }
11886
11887 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011888 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011889 //r.dump(" ");
11890
11891 // Does it still need to run?
11892 if (!force && r.startRequested) {
11893 return;
11894 }
11895 if (r.connections.size() > 0) {
11896 if (!force) {
11897 // XXX should probably keep a count of the number of auto-create
11898 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011899 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011900 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011901 ArrayList<ConnectionRecord> cr = it.next();
11902 for (int i=0; i<cr.size(); i++) {
11903 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11904 return;
11905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011906 }
11907 }
11908 }
11909
11910 // Report to all of the connections that the service is no longer
11911 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011912 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011913 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011914 ArrayList<ConnectionRecord> c = it.next();
11915 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011916 ConnectionRecord cr = c.get(i);
11917 // There is still a connection to the service that is
11918 // being brought down. Mark it as dead.
11919 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011920 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011921 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011922 } catch (Exception e) {
11923 Slog.w(TAG, "Failure disconnecting service " + r.name +
11924 " to connection " + c.get(i).conn.asBinder() +
11925 " (in " + c.get(i).binding.client.processName + ")", e);
11926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011927 }
11928 }
11929 }
11930
11931 // Tell the service that it has been unbound.
11932 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11933 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11934 while (it.hasNext()) {
11935 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011936 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011937 + ": hasBound=" + ibr.hasBound);
11938 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11939 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011940 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011941 updateOomAdjLocked(r.app);
11942 ibr.hasBound = false;
11943 r.app.thread.scheduleUnbindService(r,
11944 ibr.intent.getIntent());
11945 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011946 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011947 + r.shortName, e);
11948 serviceDoneExecutingLocked(r, true);
11949 }
11950 }
11951 }
11952 }
11953
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011954 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011955 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011956 System.identityHashCode(r), r.shortName,
11957 (r.app != null) ? r.app.pid : -1);
11958
Amith Yamasani742a6712011-05-04 14:49:28 -070011959 mServiceMap.removeServiceByName(r.name, r.userId);
11960 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011961 r.totalRestartCount = 0;
11962 unscheduleServiceRestartLocked(r);
11963
11964 // Also make sure it is not on the pending list.
11965 int N = mPendingServices.size();
11966 for (int i=0; i<N; i++) {
11967 if (mPendingServices.get(i) == r) {
11968 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011969 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011970 i--;
11971 N--;
11972 }
11973 }
11974
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011975 r.cancelNotification();
11976 r.isForeground = false;
11977 r.foregroundId = 0;
11978 r.foregroundNoti = null;
11979
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011980 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011981 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011982 r.pendingStarts.clear();
11983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984 if (r.app != null) {
11985 synchronized (r.stats.getBatteryStats()) {
11986 r.stats.stopLaunchedLocked();
11987 }
11988 r.app.services.remove(r);
11989 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011990 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011991 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011992 mStoppingServices.add(r);
11993 updateOomAdjLocked(r.app);
11994 r.app.thread.scheduleStopService(r);
11995 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011996 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011997 + r.shortName, e);
11998 serviceDoneExecutingLocked(r, true);
11999 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012000 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012001 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012002 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012003 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012004 }
12005 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012006 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012007 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012008 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080012009
12010 if (r.bindings.size() > 0) {
12011 r.bindings.clear();
12012 }
12013
12014 if (r.restarter instanceof ServiceRestarter) {
12015 ((ServiceRestarter)r.restarter).setService(null);
12016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012017 }
12018
12019 ComponentName startServiceLocked(IApplicationThread caller,
12020 Intent service, String resolvedType,
12021 int callingPid, int callingUid) {
12022 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012023 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012024 + " type=" + resolvedType + " args=" + service.getExtras());
12025
12026 if (caller != null) {
12027 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12028 if (callerApp == null) {
12029 throw new SecurityException(
12030 "Unable to find app for caller " + caller
12031 + " (pid=" + Binder.getCallingPid()
12032 + ") when starting service " + service);
12033 }
12034 }
12035
12036 ServiceLookupResult res =
12037 retrieveServiceLocked(service, resolvedType,
12038 callingPid, callingUid);
12039 if (res == null) {
12040 return null;
12041 }
12042 if (res.record == null) {
12043 return new ComponentName("!", res.permission != null
12044 ? res.permission : "private to package");
12045 }
12046 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -070012047 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
12048 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012049 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012050 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012051 }
12052 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012053 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012054 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn39792d22010-08-19 18:01:52 -070012055 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012056 r.lastActivity = SystemClock.uptimeMillis();
12057 synchronized (r.stats.getBatteryStats()) {
12058 r.stats.startRunningLocked();
12059 }
12060 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
12061 return new ComponentName("!", "Service process is bad");
12062 }
12063 return r.name;
12064 }
12065 }
12066
12067 public ComponentName startService(IApplicationThread caller, Intent service,
12068 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012069 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012070 // Refuse possible leaked file descriptors
12071 if (service != null && service.hasFileDescriptors() == true) {
12072 throw new IllegalArgumentException("File descriptors passed in Intent");
12073 }
12074
Amith Yamasani742a6712011-05-04 14:49:28 -070012075 if (DEBUG_SERVICE)
12076 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012077 synchronized(this) {
12078 final int callingPid = Binder.getCallingPid();
12079 final int callingUid = Binder.getCallingUid();
12080 final long origId = Binder.clearCallingIdentity();
12081 ComponentName res = startServiceLocked(caller, service,
12082 resolvedType, callingPid, callingUid);
12083 Binder.restoreCallingIdentity(origId);
12084 return res;
12085 }
12086 }
12087
12088 ComponentName startServiceInPackage(int uid,
12089 Intent service, String resolvedType) {
12090 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070012091 if (DEBUG_SERVICE)
12092 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012093 final long origId = Binder.clearCallingIdentity();
12094 ComponentName res = startServiceLocked(null, service,
12095 resolvedType, -1, uid);
12096 Binder.restoreCallingIdentity(origId);
12097 return res;
12098 }
12099 }
12100
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012101 private void stopServiceLocked(ServiceRecord service) {
12102 synchronized (service.stats.getBatteryStats()) {
12103 service.stats.stopRunningLocked();
12104 }
12105 service.startRequested = false;
12106 service.callStart = false;
12107 bringDownServiceLocked(service, false);
12108 }
12109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012110 public int stopService(IApplicationThread caller, Intent service,
12111 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012112 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012113 // Refuse possible leaked file descriptors
12114 if (service != null && service.hasFileDescriptors() == true) {
12115 throw new IllegalArgumentException("File descriptors passed in Intent");
12116 }
12117
12118 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012119 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012120 + " type=" + resolvedType);
12121
12122 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12123 if (caller != null && callerApp == null) {
12124 throw new SecurityException(
12125 "Unable to find app for caller " + caller
12126 + " (pid=" + Binder.getCallingPid()
12127 + ") when stopping service " + service);
12128 }
12129
12130 // If this service is active, make sure it is stopped.
12131 ServiceLookupResult r = findServiceLocked(service, resolvedType);
12132 if (r != null) {
12133 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012134 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012135 try {
12136 stopServiceLocked(r.record);
12137 } finally {
12138 Binder.restoreCallingIdentity(origId);
12139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012140 return 1;
12141 }
12142 return -1;
12143 }
12144 }
12145
12146 return 0;
12147 }
12148
12149 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012150 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012151 // Refuse possible leaked file descriptors
12152 if (service != null && service.hasFileDescriptors() == true) {
12153 throw new IllegalArgumentException("File descriptors passed in Intent");
12154 }
12155
12156 IBinder ret = null;
12157
12158 synchronized(this) {
12159 ServiceLookupResult r = findServiceLocked(service, resolvedType);
12160
12161 if (r != null) {
12162 // r.record is null if findServiceLocked() failed the caller permission check
12163 if (r.record == null) {
12164 throw new SecurityException(
12165 "Permission Denial: Accessing service " + r.record.name
12166 + " from pid=" + Binder.getCallingPid()
12167 + ", uid=" + Binder.getCallingUid()
12168 + " requires " + r.permission);
12169 }
12170 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
12171 if (ib != null) {
12172 ret = ib.binder;
12173 }
12174 }
12175 }
12176
12177 return ret;
12178 }
12179
12180 public boolean stopServiceToken(ComponentName className, IBinder token,
12181 int startId) {
12182 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012183 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012184 + " " + token + " startId=" + startId);
12185 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012186 if (r != null) {
12187 if (startId >= 0) {
12188 // Asked to only stop if done with all work. Note that
12189 // to avoid leaks, we will take this as dropping all
12190 // start items up to and including this one.
12191 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12192 if (si != null) {
12193 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070012194 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
12195 cur.removeUriPermissionsLocked();
12196 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012197 break;
12198 }
12199 }
12200 }
12201
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012202 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012203 return false;
12204 }
12205
12206 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012207 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012208 + " is last, but have " + r.deliveredStarts.size()
12209 + " remaining args");
12210 }
12211 }
12212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012213 synchronized (r.stats.getBatteryStats()) {
12214 r.stats.stopRunningLocked();
12215 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012216 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012217 }
12218 final long origId = Binder.clearCallingIdentity();
12219 bringDownServiceLocked(r, false);
12220 Binder.restoreCallingIdentity(origId);
12221 return true;
12222 }
12223 }
12224 return false;
12225 }
12226
12227 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012228 int id, Notification notification, boolean removeNotification) {
12229 final long origId = Binder.clearCallingIdentity();
12230 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012231 synchronized(this) {
12232 ServiceRecord r = findServiceLocked(className, token);
12233 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012234 if (id != 0) {
12235 if (notification == null) {
12236 throw new IllegalArgumentException("null notification");
12237 }
12238 if (r.foregroundId != id) {
12239 r.cancelNotification();
12240 r.foregroundId = id;
12241 }
12242 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
12243 r.foregroundNoti = notification;
12244 r.isForeground = true;
12245 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012246 if (r.app != null) {
12247 updateServiceForegroundLocked(r.app, true);
12248 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012249 } else {
12250 if (r.isForeground) {
12251 r.isForeground = false;
12252 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070012253 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012254 updateServiceForegroundLocked(r.app, true);
12255 }
12256 }
12257 if (removeNotification) {
12258 r.cancelNotification();
12259 r.foregroundId = 0;
12260 r.foregroundNoti = null;
12261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012262 }
12263 }
12264 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012265 } finally {
12266 Binder.restoreCallingIdentity(origId);
12267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012268 }
12269
12270 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
12271 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070012272 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012273 if (sr.isForeground) {
12274 anyForeground = true;
12275 break;
12276 }
12277 }
12278 if (anyForeground != proc.foregroundServices) {
12279 proc.foregroundServices = anyForeground;
12280 if (oomAdj) {
12281 updateOomAdjLocked();
12282 }
12283 }
12284 }
12285
12286 public int bindService(IApplicationThread caller, IBinder token,
12287 Intent service, String resolvedType,
12288 IServiceConnection connection, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012289 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012290 // Refuse possible leaked file descriptors
12291 if (service != null && service.hasFileDescriptors() == true) {
12292 throw new IllegalArgumentException("File descriptors passed in Intent");
12293 }
12294
12295 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012296 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012297 + " type=" + resolvedType + " conn=" + connection.asBinder()
12298 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070012299 if (DEBUG_MU)
12300 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
12301 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012302 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12303 if (callerApp == null) {
12304 throw new SecurityException(
12305 "Unable to find app for caller " + caller
12306 + " (pid=" + Binder.getCallingPid()
12307 + ") when binding service " + service);
12308 }
12309
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012310 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012311 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012312 activity = mMainStack.isInStackLocked(token);
12313 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012314 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012315 return 0;
12316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012317 }
12318
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012319 int clientLabel = 0;
12320 PendingIntent clientIntent = null;
12321
12322 if (callerApp.info.uid == Process.SYSTEM_UID) {
12323 // Hacky kind of thing -- allow system stuff to tell us
12324 // what they are, so we can report this elsewhere for
12325 // others to know why certain services are running.
12326 try {
12327 clientIntent = (PendingIntent)service.getParcelableExtra(
12328 Intent.EXTRA_CLIENT_INTENT);
12329 } catch (RuntimeException e) {
12330 }
12331 if (clientIntent != null) {
12332 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
12333 if (clientLabel != 0) {
12334 // There are no useful extras in the intent, trash them.
12335 // System code calling with this stuff just needs to know
12336 // this will happen.
12337 service = service.cloneFilter();
12338 }
12339 }
12340 }
12341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012342 ServiceLookupResult res =
12343 retrieveServiceLocked(service, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -070012344 Binder.getCallingPid(), Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012345 if (res == null) {
12346 return 0;
12347 }
12348 if (res.record == null) {
12349 return -1;
12350 }
12351 ServiceRecord s = res.record;
12352
12353 final long origId = Binder.clearCallingIdentity();
12354
12355 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012356 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012357 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012358 }
12359
12360 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
12361 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012362 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012363
12364 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012365 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12366 if (clist == null) {
12367 clist = new ArrayList<ConnectionRecord>();
12368 s.connections.put(binder, clist);
12369 }
12370 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012371 b.connections.add(c);
12372 if (activity != null) {
12373 if (activity.connections == null) {
12374 activity.connections = new HashSet<ConnectionRecord>();
12375 }
12376 activity.connections.add(c);
12377 }
12378 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012379 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12380 b.client.hasAboveClient = true;
12381 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012382 clist = mServiceConnections.get(binder);
12383 if (clist == null) {
12384 clist = new ArrayList<ConnectionRecord>();
12385 mServiceConnections.put(binder, clist);
12386 }
12387 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012388
12389 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
12390 s.lastActivity = SystemClock.uptimeMillis();
12391 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
12392 return 0;
12393 }
12394 }
12395
12396 if (s.app != null) {
12397 // This could have made the service more important.
12398 updateOomAdjLocked(s.app);
12399 }
12400
Joe Onorato8a9b2202010-02-26 18:56:32 -080012401 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012402 + ": received=" + b.intent.received
12403 + " apps=" + b.intent.apps.size()
12404 + " doRebind=" + b.intent.doRebind);
12405
12406 if (s.app != null && b.intent.received) {
12407 // Service is already running, so we can immediately
12408 // publish the connection.
12409 try {
12410 c.conn.connected(s.name, b.intent.binder);
12411 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012412 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012413 + " to connection " + c.conn.asBinder()
12414 + " (in " + c.binding.client.processName + ")", e);
12415 }
12416
12417 // If this is the first app connected back to this binding,
12418 // and the service had previously asked to be told when
12419 // rebound, then do so.
12420 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
12421 requestServiceBindingLocked(s, b.intent, true);
12422 }
12423 } else if (!b.intent.requested) {
12424 requestServiceBindingLocked(s, b.intent, false);
12425 }
12426
12427 Binder.restoreCallingIdentity(origId);
12428 }
12429
12430 return 1;
12431 }
12432
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012433 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012434 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012435 IBinder binder = c.conn.asBinder();
12436 AppBindRecord b = c.binding;
12437 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012438 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12439 if (clist != null) {
12440 clist.remove(c);
12441 if (clist.size() == 0) {
12442 s.connections.remove(binder);
12443 }
12444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445 b.connections.remove(c);
12446 if (c.activity != null && c.activity != skipAct) {
12447 if (c.activity.connections != null) {
12448 c.activity.connections.remove(c);
12449 }
12450 }
12451 if (b.client != skipApp) {
12452 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012453 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12454 b.client.updateHasAboveClientLocked();
12455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012456 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012457 clist = mServiceConnections.get(binder);
12458 if (clist != null) {
12459 clist.remove(c);
12460 if (clist.size() == 0) {
12461 mServiceConnections.remove(binder);
12462 }
12463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012464
12465 if (b.connections.size() == 0) {
12466 b.intent.apps.remove(b.client);
12467 }
12468
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012469 if (!c.serviceDead) {
12470 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
12471 + ": shouldUnbind=" + b.intent.hasBound);
12472 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
12473 && b.intent.hasBound) {
12474 try {
12475 bumpServiceExecutingLocked(s, "unbind");
12476 updateOomAdjLocked(s.app);
12477 b.intent.hasBound = false;
12478 // Assume the client doesn't want to know about a rebind;
12479 // we will deal with that later if it asks for one.
12480 b.intent.doRebind = false;
12481 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
12482 } catch (Exception e) {
12483 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
12484 serviceDoneExecutingLocked(s, true);
12485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012486 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012487
12488 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
12489 bringDownServiceLocked(s, false);
12490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012491 }
12492 }
12493
12494 public boolean unbindService(IServiceConnection connection) {
12495 synchronized (this) {
12496 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012497 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012498 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
12499 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012500 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012501 + connection.asBinder());
12502 return false;
12503 }
12504
12505 final long origId = Binder.clearCallingIdentity();
12506
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012507 while (clist.size() > 0) {
12508 ConnectionRecord r = clist.get(0);
12509 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012510
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012511 if (r.binding.service.app != null) {
12512 // This could have made the service less important.
12513 updateOomAdjLocked(r.binding.service.app);
12514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012515 }
12516
12517 Binder.restoreCallingIdentity(origId);
12518 }
12519
12520 return true;
12521 }
12522
12523 public void publishService(IBinder token, Intent intent, IBinder service) {
12524 // Refuse possible leaked file descriptors
12525 if (intent != null && intent.hasFileDescriptors() == true) {
12526 throw new IllegalArgumentException("File descriptors passed in Intent");
12527 }
12528
12529 synchronized(this) {
12530 if (!(token instanceof ServiceRecord)) {
12531 throw new IllegalArgumentException("Invalid service token");
12532 }
12533 ServiceRecord r = (ServiceRecord)token;
12534
12535 final long origId = Binder.clearCallingIdentity();
12536
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012537 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012538 + " " + intent + ": " + service);
12539 if (r != null) {
12540 Intent.FilterComparison filter
12541 = new Intent.FilterComparison(intent);
12542 IntentBindRecord b = r.bindings.get(filter);
12543 if (b != null && !b.received) {
12544 b.binder = service;
12545 b.requested = true;
12546 b.received = true;
12547 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012548 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012549 = r.connections.values().iterator();
12550 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012551 ArrayList<ConnectionRecord> clist = it.next();
12552 for (int i=0; i<clist.size(); i++) {
12553 ConnectionRecord c = clist.get(i);
12554 if (!filter.equals(c.binding.intent.intent)) {
12555 if (DEBUG_SERVICE) Slog.v(
12556 TAG, "Not publishing to: " + c);
12557 if (DEBUG_SERVICE) Slog.v(
12558 TAG, "Bound intent: " + c.binding.intent.intent);
12559 if (DEBUG_SERVICE) Slog.v(
12560 TAG, "Published intent: " + intent);
12561 continue;
12562 }
12563 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12564 try {
12565 c.conn.connected(r.name, service);
12566 } catch (Exception e) {
12567 Slog.w(TAG, "Failure sending service " + r.name +
12568 " to connection " + c.conn.asBinder() +
12569 " (in " + c.binding.client.processName + ")", e);
12570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012571 }
12572 }
12573 }
12574 }
12575
12576 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12577
12578 Binder.restoreCallingIdentity(origId);
12579 }
12580 }
12581 }
12582
12583 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12584 // Refuse possible leaked file descriptors
12585 if (intent != null && intent.hasFileDescriptors() == true) {
12586 throw new IllegalArgumentException("File descriptors passed in Intent");
12587 }
12588
12589 synchronized(this) {
12590 if (!(token instanceof ServiceRecord)) {
12591 throw new IllegalArgumentException("Invalid service token");
12592 }
12593 ServiceRecord r = (ServiceRecord)token;
12594
12595 final long origId = Binder.clearCallingIdentity();
12596
12597 if (r != null) {
12598 Intent.FilterComparison filter
12599 = new Intent.FilterComparison(intent);
12600 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012601 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012602 + " at " + b + ": apps="
12603 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012604
12605 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012606 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012607 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012608 // Applications have already bound since the last
12609 // unbind, so just rebind right here.
12610 requestServiceBindingLocked(r, b, true);
12611 } else {
12612 // Note to tell the service the next time there is
12613 // a new client.
12614 b.doRebind = true;
12615 }
12616 }
12617
Per Edelberg78f9fff2010-08-30 20:01:35 +020012618 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012619
12620 Binder.restoreCallingIdentity(origId);
12621 }
12622 }
12623 }
12624
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012625 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012626 synchronized(this) {
12627 if (!(token instanceof ServiceRecord)) {
12628 throw new IllegalArgumentException("Invalid service token");
12629 }
12630 ServiceRecord r = (ServiceRecord)token;
12631 boolean inStopping = mStoppingServices.contains(token);
12632 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012633 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012634 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012635 + " with incorrect token: given " + token
12636 + ", expected " + r);
12637 return;
12638 }
12639
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012640 if (type == 1) {
12641 // This is a call from a service start... take care of
12642 // book-keeping.
12643 r.callStart = true;
12644 switch (res) {
12645 case Service.START_STICKY_COMPATIBILITY:
12646 case Service.START_STICKY: {
12647 // We are done with the associated start arguments.
12648 r.findDeliveredStart(startId, true);
12649 // Don't stop if killed.
12650 r.stopIfKilled = false;
12651 break;
12652 }
12653 case Service.START_NOT_STICKY: {
12654 // We are done with the associated start arguments.
12655 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012656 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012657 // There is no more work, and this service
12658 // doesn't want to hang around if killed.
12659 r.stopIfKilled = true;
12660 }
12661 break;
12662 }
12663 case Service.START_REDELIVER_INTENT: {
12664 // We'll keep this item until they explicitly
12665 // call stop for it, but keep track of the fact
12666 // that it was delivered.
12667 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12668 if (si != null) {
12669 si.deliveryCount = 0;
12670 si.doneExecutingCount++;
12671 // Don't stop if killed.
12672 r.stopIfKilled = true;
12673 }
12674 break;
12675 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012676 case Service.START_TASK_REMOVED_COMPLETE: {
12677 // Special processing for onTaskRemoved(). Don't
12678 // impact normal onStartCommand() processing.
12679 r.findDeliveredStart(startId, true);
12680 break;
12681 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012682 default:
12683 throw new IllegalArgumentException(
12684 "Unknown service start result: " + res);
12685 }
12686 if (res == Service.START_STICKY_COMPATIBILITY) {
12687 r.callStart = false;
12688 }
12689 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012690 if (DEBUG_MU)
12691 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12692 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012693 final long origId = Binder.clearCallingIdentity();
12694 serviceDoneExecutingLocked(r, inStopping);
12695 Binder.restoreCallingIdentity(origId);
12696 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012697 Slog.w(TAG, "Done executing unknown service from pid "
12698 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012699 }
12700 }
12701 }
12702
12703 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012704 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12705 + ": nesting=" + r.executeNesting
12706 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012707 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012708 r.executeNesting--;
12709 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012710 if (DEBUG_SERVICE) Slog.v(TAG,
12711 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012712 r.app.executingServices.remove(r);
12713 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012714 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12715 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012716 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12717 }
12718 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012719 if (DEBUG_SERVICE) Slog.v(TAG,
12720 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012721 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012722 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012723 }
12724 updateOomAdjLocked(r.app);
12725 }
12726 }
12727
12728 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012729 String anrMessage = null;
12730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012731 synchronized(this) {
12732 if (proc.executingServices.size() == 0 || proc.thread == null) {
12733 return;
12734 }
12735 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12736 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12737 ServiceRecord timeout = null;
12738 long nextTime = 0;
12739 while (it.hasNext()) {
12740 ServiceRecord sr = it.next();
12741 if (sr.executingStart < maxTime) {
12742 timeout = sr;
12743 break;
12744 }
12745 if (sr.executingStart > nextTime) {
12746 nextTime = sr.executingStart;
12747 }
12748 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012749 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012750 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012751 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012752 } else {
12753 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12754 msg.obj = proc;
12755 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12756 }
12757 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012758
12759 if (anrMessage != null) {
12760 appNotResponding(proc, null, null, anrMessage);
12761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012762 }
12763
12764 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012765 // BACKUP AND RESTORE
12766 // =========================================================
12767
12768 // Cause the target app to be launched if necessary and its backup agent
12769 // instantiated. The backup agent will invoke backupAgentCreated() on the
12770 // activity manager to announce its creation.
12771 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012772 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012773 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12774
12775 synchronized(this) {
12776 // !!! TODO: currently no check here that we're already bound
12777 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12778 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12779 synchronized (stats) {
12780 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12781 }
12782
Dianne Hackborne7f97212011-02-24 14:40:20 -080012783 // Backup agent is now in use, its package can't be stopped.
12784 try {
12785 AppGlobals.getPackageManager().setPackageStoppedState(
12786 app.packageName, false);
12787 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012788 } catch (IllegalArgumentException e) {
12789 Slog.w(TAG, "Failed trying to unstop package "
12790 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012791 }
12792
Christopher Tate181fafa2009-05-14 11:12:14 -070012793 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012794 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12795 ? new ComponentName(app.packageName, app.backupAgentName)
12796 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012797 // startProcessLocked() returns existing proc's record if it's already running
12798 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012799 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012800 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012801 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012802 return false;
12803 }
12804
12805 r.app = proc;
12806 mBackupTarget = r;
12807 mBackupAppName = app.packageName;
12808
Christopher Tate6fa95972009-06-05 18:43:55 -070012809 // Try not to kill the process during backup
12810 updateOomAdjLocked(proc);
12811
Christopher Tate181fafa2009-05-14 11:12:14 -070012812 // If the process is already attached, schedule the creation of the backup agent now.
12813 // If it is not yet live, this will be done when it attaches to the framework.
12814 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012815 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012816 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012817 proc.thread.scheduleCreateBackupAgent(app,
12818 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012819 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012820 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012821 }
12822 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012823 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012824 }
12825 // Invariants: at this point, the target app process exists and the application
12826 // is either already running or in the process of coming up. mBackupTarget and
12827 // mBackupAppName describe the app, so that when it binds back to the AM we
12828 // know that it's scheduled for a backup-agent operation.
12829 }
12830
12831 return true;
12832 }
12833
12834 // A backup agent has just come up
12835 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012836 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012837 + " = " + agent);
12838
12839 synchronized(this) {
12840 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012841 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012842 return;
12843 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012844 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012845
Dianne Hackborn06740692010-09-22 22:46:21 -070012846 long oldIdent = Binder.clearCallingIdentity();
12847 try {
12848 IBackupManager bm = IBackupManager.Stub.asInterface(
12849 ServiceManager.getService(Context.BACKUP_SERVICE));
12850 bm.agentConnected(agentPackageName, agent);
12851 } catch (RemoteException e) {
12852 // can't happen; the backup manager service is local
12853 } catch (Exception e) {
12854 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12855 e.printStackTrace();
12856 } finally {
12857 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012858 }
12859 }
12860
12861 // done with this agent
12862 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012863 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012864 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012865 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012866 return;
12867 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012868
12869 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012870 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012871 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012872 return;
12873 }
12874
Christopher Tate181fafa2009-05-14 11:12:14 -070012875 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012876 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012877 return;
12878 }
12879
Christopher Tate6fa95972009-06-05 18:43:55 -070012880 ProcessRecord proc = mBackupTarget.app;
12881 mBackupTarget = null;
12882 mBackupAppName = null;
12883
12884 // Not backing this app up any more; reset its OOM adjustment
12885 updateOomAdjLocked(proc);
12886
Christopher Tatec7b31e32009-06-10 15:49:30 -070012887 // If the app crashed during backup, 'thread' will be null here
12888 if (proc.thread != null) {
12889 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012890 proc.thread.scheduleDestroyBackupAgent(appInfo,
12891 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012892 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012893 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012894 e.printStackTrace();
12895 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012896 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012897 }
12898 }
12899 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012900 // BROADCASTS
12901 // =========================================================
12902
Josh Bartel7f208742010-02-25 11:01:44 -060012903 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012904 List cur) {
12905 final ContentResolver resolver = mContext.getContentResolver();
12906 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12907 if (list == null) {
12908 return cur;
12909 }
12910 int N = list.size();
12911 for (int i=0; i<N; i++) {
12912 Intent intent = list.get(i);
12913 if (filter.match(resolver, intent, true, TAG) >= 0) {
12914 if (cur == null) {
12915 cur = new ArrayList<Intent>();
12916 }
12917 cur.add(intent);
12918 }
12919 }
12920 return cur;
12921 }
12922
Christopher Tatef46723b2012-01-26 14:19:24 -080012923 boolean isPendingBroadcastProcessLocked(int pid) {
12924 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12925 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012927
Christopher Tatef46723b2012-01-26 14:19:24 -080012928 void skipPendingBroadcastLocked(int pid) {
12929 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12930 for (BroadcastQueue queue : mBroadcastQueues) {
12931 queue.skipPendingBroadcastLocked(pid);
12932 }
12933 }
12934
12935 // The app just attached; send any pending broadcasts that it should receive
12936 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12937 boolean didSomething = false;
12938 for (BroadcastQueue queue : mBroadcastQueues) {
12939 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012941 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012942 }
12943
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012944 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012945 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012946 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012947 synchronized(this) {
12948 ProcessRecord callerApp = null;
12949 if (caller != null) {
12950 callerApp = getRecordForAppLocked(caller);
12951 if (callerApp == null) {
12952 throw new SecurityException(
12953 "Unable to find app for caller " + caller
12954 + " (pid=" + Binder.getCallingPid()
12955 + ") when registering receiver " + receiver);
12956 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012957 if (callerApp.info.uid != Process.SYSTEM_UID &&
12958 !callerApp.pkgList.contains(callerPackage)) {
12959 throw new SecurityException("Given caller package " + callerPackage
12960 + " is not running in process " + callerApp);
12961 }
12962 } else {
12963 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012964 }
12965
12966 List allSticky = null;
12967
12968 // Look for any matching sticky broadcasts...
12969 Iterator actions = filter.actionsIterator();
12970 if (actions != null) {
12971 while (actions.hasNext()) {
12972 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012973 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012974 }
12975 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012976 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012977 }
12978
12979 // The first sticky in the list is returned directly back to
12980 // the client.
12981 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12982
Joe Onorato8a9b2202010-02-26 18:56:32 -080012983 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012984 + ": " + sticky);
12985
12986 if (receiver == null) {
12987 return sticky;
12988 }
12989
12990 ReceiverList rl
12991 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12992 if (rl == null) {
12993 rl = new ReceiverList(this, callerApp,
12994 Binder.getCallingPid(),
12995 Binder.getCallingUid(), receiver);
12996 if (rl.app != null) {
12997 rl.app.receivers.add(rl);
12998 } else {
12999 try {
13000 receiver.asBinder().linkToDeath(rl, 0);
13001 } catch (RemoteException e) {
13002 return sticky;
13003 }
13004 rl.linkedToDeath = true;
13005 }
13006 mRegisteredReceivers.put(receiver.asBinder(), rl);
13007 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070013008 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013009 rl.add(bf);
13010 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013011 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013012 }
13013 mReceiverResolver.addFilter(bf);
13014
13015 // Enqueue broadcasts for all existing stickies that match
13016 // this filter.
13017 if (allSticky != null) {
13018 ArrayList receivers = new ArrayList();
13019 receivers.add(bf);
13020
13021 int N = allSticky.size();
13022 for (int i=0; i<N; i++) {
13023 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080013024 BroadcastQueue queue = broadcastQueueForIntent(intent);
13025 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013026 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013027 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080013028 queue.enqueueParallelBroadcastLocked(r);
13029 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013030 }
13031 }
13032
13033 return sticky;
13034 }
13035 }
13036
13037 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013038 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013039
Christopher Tatef46723b2012-01-26 14:19:24 -080013040 final long origId = Binder.clearCallingIdentity();
13041 try {
13042 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013043
Christopher Tatef46723b2012-01-26 14:19:24 -080013044 synchronized(this) {
13045 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013046 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080013047 if (rl != null) {
13048 if (rl.curBroadcast != null) {
13049 BroadcastRecord r = rl.curBroadcast;
13050 final boolean doNext = finishReceiverLocked(
13051 receiver.asBinder(), r.resultCode, r.resultData,
13052 r.resultExtras, r.resultAbort, true);
13053 if (doNext) {
13054 doTrim = true;
13055 r.queue.processNextBroadcast(false);
13056 }
13057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013058
Christopher Tatef46723b2012-01-26 14:19:24 -080013059 if (rl.app != null) {
13060 rl.app.receivers.remove(rl);
13061 }
13062 removeReceiverLocked(rl);
13063 if (rl.linkedToDeath) {
13064 rl.linkedToDeath = false;
13065 rl.receiver.asBinder().unlinkToDeath(rl, 0);
13066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013067 }
13068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013069
Christopher Tatef46723b2012-01-26 14:19:24 -080013070 // If we actually concluded any broadcasts, we might now be able
13071 // to trim the recipients' apps from our working set
13072 if (doTrim) {
13073 trimApplications();
13074 return;
13075 }
13076
13077 } finally {
13078 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013080 }
13081
13082 void removeReceiverLocked(ReceiverList rl) {
13083 mRegisteredReceivers.remove(rl.receiver.asBinder());
13084 int N = rl.size();
13085 for (int i=0; i<N; i++) {
13086 mReceiverResolver.removeFilter(rl.get(i));
13087 }
13088 }
13089
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070013090 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
13091 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13092 ProcessRecord r = mLruProcesses.get(i);
13093 if (r.thread != null) {
13094 try {
13095 r.thread.dispatchPackageBroadcast(cmd, packages);
13096 } catch (RemoteException ex) {
13097 }
13098 }
13099 }
13100 }
13101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013102 private final int broadcastIntentLocked(ProcessRecord callerApp,
13103 String callerPackage, Intent intent, String resolvedType,
13104 IIntentReceiver resultTo, int resultCode, String resultData,
13105 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013106 boolean ordered, boolean sticky, int callingPid, int callingUid,
13107 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013108 intent = new Intent(intent);
13109
Dianne Hackborne7f97212011-02-24 14:40:20 -080013110 // By default broadcasts do not go to stopped apps.
13111 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
13112
Joe Onorato8a9b2202010-02-26 18:56:32 -080013113 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013114 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
13115 + " ordered=" + ordered);
13116 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013117 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013118 }
13119
13120 // Handle special intents: if this broadcast is from the package
13121 // manager about a package being removed, we need to remove all of
13122 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013123 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013124 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013125 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
13126 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080013127 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013128 || uidRemoved) {
13129 if (checkComponentPermission(
13130 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080013131 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013132 == PackageManager.PERMISSION_GRANTED) {
13133 if (uidRemoved) {
13134 final Bundle intentExtras = intent.getExtras();
13135 final int uid = intentExtras != null
13136 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
13137 if (uid >= 0) {
13138 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
13139 synchronized (bs) {
13140 bs.removeUidStatsLocked(uid);
13141 }
13142 }
13143 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013144 // If resources are unvailble just force stop all
13145 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080013146 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013147 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
13148 if (list != null && (list.length > 0)) {
13149 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070013150 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013151 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070013152 sendPackageBroadcastLocked(
13153 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013154 }
13155 } else {
13156 Uri data = intent.getData();
13157 String ssp;
13158 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
13159 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
13160 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070013161 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070013162 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013163 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070013164 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
13165 new String[] {ssp});
13166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013167 }
13168 }
13169 }
13170 } else {
13171 String msg = "Permission Denial: " + intent.getAction()
13172 + " broadcast from " + callerPackage + " (pid=" + callingPid
13173 + ", uid=" + callingUid + ")"
13174 + " requires "
13175 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013176 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013177 throw new SecurityException(msg);
13178 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013179
13180 // Special case for adding a package: by default turn on compatibility
13181 // mode.
13182 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070013183 Uri data = intent.getData();
13184 String ssp;
13185 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
13186 mCompatModePackages.handlePackageAddedLocked(ssp,
13187 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013189 }
13190
13191 /*
13192 * If this is the time zone changed action, queue up a message that will reset the timezone
13193 * of all currently running processes. This message will get queued up before the broadcast
13194 * happens.
13195 */
13196 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
13197 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
13198 }
13199
Robert Greenwalt03595d02010-11-02 14:08:23 -070013200 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
13201 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
13202 }
13203
Robert Greenwalt434203a2010-10-11 16:00:27 -070013204 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
13205 ProxyProperties proxy = intent.getParcelableExtra("proxy");
13206 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
13207 }
13208
Dianne Hackborn854060af2009-07-09 18:14:31 -070013209 /*
13210 * Prevent non-system code (defined here to be non-persistent
13211 * processes) from sending protected broadcasts.
13212 */
13213 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
13214 || callingUid == Process.SHELL_UID || callingUid == 0) {
13215 // Always okay.
13216 } else if (callerApp == null || !callerApp.persistent) {
13217 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013218 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070013219 intent.getAction())) {
13220 String msg = "Permission Denial: not allowed to send broadcast "
13221 + intent.getAction() + " from pid="
13222 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013223 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070013224 throw new SecurityException(msg);
13225 }
13226 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013227 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070013228 return BROADCAST_SUCCESS;
13229 }
13230 }
13231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013232 // Add to the sticky list if requested.
13233 if (sticky) {
13234 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
13235 callingPid, callingUid)
13236 != PackageManager.PERMISSION_GRANTED) {
13237 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
13238 + callingPid + ", uid=" + callingUid
13239 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013240 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013241 throw new SecurityException(msg);
13242 }
13243 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013244 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013245 + " and enforce permission " + requiredPermission);
13246 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
13247 }
13248 if (intent.getComponent() != null) {
13249 throw new SecurityException(
13250 "Sticky broadcasts can't target a specific component");
13251 }
13252 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13253 if (list == null) {
13254 list = new ArrayList<Intent>();
13255 mStickyBroadcasts.put(intent.getAction(), list);
13256 }
13257 int N = list.size();
13258 int i;
13259 for (i=0; i<N; i++) {
13260 if (intent.filterEquals(list.get(i))) {
13261 // This sticky already exists, replace it.
13262 list.set(i, new Intent(intent));
13263 break;
13264 }
13265 }
13266 if (i >= N) {
13267 list.add(new Intent(intent));
13268 }
13269 }
13270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013271 // Figure out who all will receive this broadcast.
13272 List receivers = null;
13273 List<BroadcastFilter> registeredReceivers = null;
13274 try {
13275 if (intent.getComponent() != null) {
13276 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013277 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070013278 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013279 if (ai != null) {
13280 receivers = new ArrayList();
13281 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070013282 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013283 receivers.add(ri);
13284 }
13285 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070013286 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013287 // Need to resolve the intent to interested receivers...
13288 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
13289 == 0) {
13290 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013291 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013292 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013293 }
Mihai Preda074edef2009-05-18 17:13:31 +020013294 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013295 }
13296 } catch (RemoteException ex) {
13297 // pm is in same process, this will never happen.
13298 }
13299
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013300 final boolean replacePending =
13301 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
13302
Joe Onorato8a9b2202010-02-26 18:56:32 -080013303 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013304 + " replacePending=" + replacePending);
13305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013306 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
13307 if (!ordered && NR > 0) {
13308 // If we are not serializing this broadcast, then send the
13309 // registered receivers separately so they don't wait for the
13310 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080013311 final BroadcastQueue queue = broadcastQueueForIntent(intent);
13312 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013313 callerPackage, callingPid, callingUid, requiredPermission,
13314 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013315 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013316 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080013317 TAG, "Enqueueing parallel broadcast " + r);
13318 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013319 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013320 queue.enqueueParallelBroadcastLocked(r);
13321 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013323 registeredReceivers = null;
13324 NR = 0;
13325 }
13326
13327 // Merge into one list.
13328 int ir = 0;
13329 if (receivers != null) {
13330 // A special case for PACKAGE_ADDED: do not allow the package
13331 // being added to see this broadcast. This prevents them from
13332 // using this as a back door to get run as soon as they are
13333 // installed. Maybe in the future we want to have a special install
13334 // broadcast or such for apps, but we'd like to deliberately make
13335 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013336 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013337 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
13338 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
13339 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013340 Uri data = intent.getData();
13341 if (data != null) {
13342 String pkgName = data.getSchemeSpecificPart();
13343 if (pkgName != null) {
13344 skipPackages = new String[] { pkgName };
13345 }
13346 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013347 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013348 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070013349 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013350 if (skipPackages != null && (skipPackages.length > 0)) {
13351 for (String skipPackage : skipPackages) {
13352 if (skipPackage != null) {
13353 int NT = receivers.size();
13354 for (int it=0; it<NT; it++) {
13355 ResolveInfo curt = (ResolveInfo)receivers.get(it);
13356 if (curt.activityInfo.packageName.equals(skipPackage)) {
13357 receivers.remove(it);
13358 it--;
13359 NT--;
13360 }
13361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013362 }
13363 }
13364 }
13365
13366 int NT = receivers != null ? receivers.size() : 0;
13367 int it = 0;
13368 ResolveInfo curt = null;
13369 BroadcastFilter curr = null;
13370 while (it < NT && ir < NR) {
13371 if (curt == null) {
13372 curt = (ResolveInfo)receivers.get(it);
13373 }
13374 if (curr == null) {
13375 curr = registeredReceivers.get(ir);
13376 }
13377 if (curr.getPriority() >= curt.priority) {
13378 // Insert this broadcast record into the final list.
13379 receivers.add(it, curr);
13380 ir++;
13381 curr = null;
13382 it++;
13383 NT++;
13384 } else {
13385 // Skip to the next ResolveInfo in the final list.
13386 it++;
13387 curt = null;
13388 }
13389 }
13390 }
13391 while (ir < NR) {
13392 if (receivers == null) {
13393 receivers = new ArrayList();
13394 }
13395 receivers.add(registeredReceivers.get(ir));
13396 ir++;
13397 }
13398
13399 if ((receivers != null && receivers.size() > 0)
13400 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013401 BroadcastQueue queue = broadcastQueueForIntent(intent);
13402 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013403 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013404 receivers, resultTo, resultCode, resultData, map, ordered,
13405 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013406 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013407 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080013408 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013409 if (DEBUG_BROADCAST) {
13410 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013411 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013412 }
Christopher Tatef46723b2012-01-26 14:19:24 -080013413 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013414 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013415 queue.enqueueOrderedBroadcastLocked(r);
13416 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013418 }
13419
13420 return BROADCAST_SUCCESS;
13421 }
13422
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013423 final Intent verifyBroadcastLocked(Intent intent) {
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
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013429 int flags = intent.getFlags();
13430
13431 if (!mProcessesReady) {
13432 // if the caller really truly claims to know what they're doing, go
13433 // ahead and allow the broadcast without launching any receivers
13434 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
13435 intent = new Intent(intent);
13436 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13437 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
13438 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
13439 + " before boot completion");
13440 throw new IllegalStateException("Cannot broadcast before boot completed");
13441 }
13442 }
13443
13444 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
13445 throw new IllegalArgumentException(
13446 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
13447 }
13448
13449 return intent;
13450 }
13451
13452 public final int broadcastIntent(IApplicationThread caller,
13453 Intent intent, String resolvedType, IIntentReceiver resultTo,
13454 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013455 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013456 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013457 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013458 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070013459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013460 final ProcessRecord callerApp = getRecordForAppLocked(caller);
13461 final int callingPid = Binder.getCallingPid();
13462 final int callingUid = Binder.getCallingUid();
13463 final long origId = Binder.clearCallingIdentity();
13464 int res = broadcastIntentLocked(callerApp,
13465 callerApp != null ? callerApp.info.packageName : null,
13466 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070013467 resultCode, resultData, map, requiredPermission, serialized, sticky,
13468 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013469 Binder.restoreCallingIdentity(origId);
13470 return res;
13471 }
13472 }
13473
13474 int broadcastIntentInPackage(String packageName, int uid,
13475 Intent intent, String resolvedType, IIntentReceiver resultTo,
13476 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013477 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013478 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013479 intent = verifyBroadcastLocked(intent);
13480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013481 final long origId = Binder.clearCallingIdentity();
13482 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
13483 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013484 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013485 Binder.restoreCallingIdentity(origId);
13486 return res;
13487 }
13488 }
13489
Amith Yamasani742a6712011-05-04 14:49:28 -070013490 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
13491 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013492 // Refuse possible leaked file descriptors
13493 if (intent != null && intent.hasFileDescriptors() == true) {
13494 throw new IllegalArgumentException("File descriptors passed in Intent");
13495 }
13496
13497 synchronized(this) {
13498 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13499 != PackageManager.PERMISSION_GRANTED) {
13500 String msg = "Permission Denial: unbroadcastIntent() from pid="
13501 + Binder.getCallingPid()
13502 + ", uid=" + Binder.getCallingUid()
13503 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013504 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013505 throw new SecurityException(msg);
13506 }
13507 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13508 if (list != null) {
13509 int N = list.size();
13510 int i;
13511 for (i=0; i<N; i++) {
13512 if (intent.filterEquals(list.get(i))) {
13513 list.remove(i);
13514 break;
13515 }
13516 }
13517 }
13518 }
13519 }
13520
13521 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13522 String resultData, Bundle resultExtras, boolean resultAbort,
13523 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013524 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13525 if (r == null) {
13526 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013527 return false;
13528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013529
Christopher Tatef46723b2012-01-26 14:19:24 -080013530 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13531 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013532 }
13533
13534 public void finishReceiver(IBinder who, int resultCode, String resultData,
13535 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013536 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013537
13538 // Refuse possible leaked file descriptors
13539 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13540 throw new IllegalArgumentException("File descriptors passed in Bundle");
13541 }
13542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013543 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013544 try {
13545 boolean doNext = false;
13546 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013547
Christopher Tatef46723b2012-01-26 14:19:24 -080013548 synchronized(this) {
13549 r = broadcastRecordForReceiverLocked(who);
13550 if (r != null) {
13551 doNext = r.queue.finishReceiverLocked(r, resultCode,
13552 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013554 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013555
Christopher Tatef46723b2012-01-26 14:19:24 -080013556 if (doNext) {
13557 r.queue.processNextBroadcast(false);
13558 }
13559 trimApplications();
13560 } finally {
13561 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013563 }
13564
13565 private final void processCurBroadcastLocked(BroadcastRecord r,
13566 ProcessRecord app) throws RemoteException {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013567 if (DEBUG_BROADCAST) Slog.v(TAG,
13568 "Process cur broadcast " + r + " for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013569 if (app.thread == null) {
13570 throw new RemoteException();
13571 }
13572 r.receiver = app.thread.asBinder();
13573 r.curApp = app;
13574 app.curReceiver = r;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013575 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013576
13577 // Tell the application to launch this receiver.
13578 r.intent.setComponent(r.curComponent);
13579
13580 boolean started = false;
13581 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013582 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013583 "Delivering to component " + r.curComponent
13584 + ": " + r);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070013585 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013586 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
Dianne Hackborne2515ee2011-04-27 18:52:56 -040013587 compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013588 r.resultCode, r.resultData, r.resultExtras, r.ordered);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013589 if (DEBUG_BROADCAST) Slog.v(TAG,
13590 "Process cur broadcast " + r + " DELIVERED for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013591 started = true;
13592 } finally {
13593 if (!started) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013594 if (DEBUG_BROADCAST) Slog.v(TAG,
13595 "Process cur broadcast " + r + ": NOT STARTED!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013596 r.receiver = null;
13597 r.curApp = null;
13598 app.curReceiver = null;
13599 }
13600 }
13601
13602 }
13603
Jeff Brown4d94a762010-09-23 11:33:28 -070013604 static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013605 Intent intent, int resultCode, String data, Bundle extras,
13606 boolean ordered, boolean sticky) throws RemoteException {
Jeff Brown4d94a762010-09-23 11:33:28 -070013607 // Send the intent to the receiver asynchronously using one-way binder calls.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 if (app != null && app.thread != null) {
13609 // If we have an app thread, do the call through that so it is
13610 // correctly ordered with other one-way calls.
13611 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013612 data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013613 } else {
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013614 receiver.performReceive(intent, resultCode, data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013615 }
13616 }
13617
Jeff Brown4d94a762010-09-23 11:33:28 -070013618 private final void deliverToRegisteredReceiverLocked(BroadcastRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013619 BroadcastFilter filter, boolean ordered) {
13620 boolean skip = false;
13621 if (filter.requiredPermission != null) {
13622 int perm = checkComponentPermission(filter.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080013623 r.callingPid, r.callingUid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013624 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013625 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013626 + r.intent.toString()
13627 + " from " + r.callerPackage + " (pid="
13628 + r.callingPid + ", uid=" + r.callingUid + ")"
13629 + " requires " + filter.requiredPermission
13630 + " due to registered receiver " + filter);
13631 skip = true;
13632 }
13633 }
13634 if (r.requiredPermission != null) {
13635 int perm = checkComponentPermission(r.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080013636 filter.receiverList.pid, filter.receiverList.uid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013637 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013638 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013639 + r.intent.toString()
13640 + " to " + filter.receiverList.app
13641 + " (pid=" + filter.receiverList.pid
13642 + ", uid=" + filter.receiverList.uid + ")"
13643 + " requires " + r.requiredPermission
13644 + " due to sender " + r.callerPackage
13645 + " (uid " + r.callingUid + ")");
13646 skip = true;
13647 }
13648 }
13649
13650 if (!skip) {
13651 // If this is not being sent as an ordered broadcast, then we
13652 // don't want to touch the fields that keep track of the current
13653 // state of ordered broadcasts.
13654 if (ordered) {
13655 r.receiver = filter.receiverList.receiver.asBinder();
13656 r.curFilter = filter;
13657 filter.receiverList.curBroadcast = r;
13658 r.state = BroadcastRecord.CALL_IN_RECEIVE;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013659 if (filter.receiverList.app != null) {
13660 // Bump hosting application to no longer be in background
13661 // scheduling class. Note that we can't do that if there
13662 // isn't an app... but we can only be in that case for
13663 // things that directly call the IActivityManager API, which
13664 // are already core system stuff so don't matter for this.
13665 r.curApp = filter.receiverList.app;
13666 filter.receiverList.app.curReceiver = r;
13667 updateOomAdjLocked();
13668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013669 }
13670 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013671 if (DEBUG_BROADCAST_LIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013672 int seq = r.intent.getIntExtra("seq", -1);
Dianne Hackborn399cccb2010-04-13 22:57:49 -070013673 Slog.i(TAG, "Delivering to " + filter
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013674 + " (seq=" + seq + "): " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013675 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013676 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013677 new Intent(r.intent), r.resultCode,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013678 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013679 if (ordered) {
13680 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
13681 }
13682 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013683 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013684 if (ordered) {
13685 r.receiver = null;
13686 r.curFilter = null;
13687 filter.receiverList.curBroadcast = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013688 if (filter.receiverList.app != null) {
13689 filter.receiverList.app.curReceiver = null;
13690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013691 }
13692 }
13693 }
13694 }
13695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013696 // =========================================================
13697 // INSTRUMENTATION
13698 // =========================================================
13699
13700 public boolean startInstrumentation(ComponentName className,
13701 String profileFile, int flags, Bundle arguments,
13702 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013703 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013704 // Refuse possible leaked file descriptors
13705 if (arguments != null && arguments.hasFileDescriptors()) {
13706 throw new IllegalArgumentException("File descriptors passed in Bundle");
13707 }
13708
13709 synchronized(this) {
13710 InstrumentationInfo ii = null;
13711 ApplicationInfo ai = null;
13712 try {
13713 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013714 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013715 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013716 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013717 } catch (PackageManager.NameNotFoundException e) {
13718 }
13719 if (ii == null) {
13720 reportStartInstrumentationFailure(watcher, className,
13721 "Unable to find instrumentation info for: " + className);
13722 return false;
13723 }
13724 if (ai == null) {
13725 reportStartInstrumentationFailure(watcher, className,
13726 "Unable to find instrumentation target package: " + ii.targetPackage);
13727 return false;
13728 }
13729
13730 int match = mContext.getPackageManager().checkSignatures(
13731 ii.targetPackage, ii.packageName);
13732 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13733 String msg = "Permission Denial: starting instrumentation "
13734 + className + " from pid="
13735 + Binder.getCallingPid()
13736 + ", uid=" + Binder.getCallingPid()
13737 + " not allowed because package " + ii.packageName
13738 + " does not have a signature matching the target "
13739 + ii.targetPackage;
13740 reportStartInstrumentationFailure(watcher, className, msg);
13741 throw new SecurityException(msg);
13742 }
13743
13744 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013745 // Instrumentation can kill and relaunch even persistent processes
13746 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013747 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013748 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013749 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013750 app.instrumentationProfileFile = profileFile;
13751 app.instrumentationArguments = arguments;
13752 app.instrumentationWatcher = watcher;
13753 app.instrumentationResultClass = className;
13754 Binder.restoreCallingIdentity(origId);
13755 }
13756
13757 return true;
13758 }
13759
13760 /**
13761 * Report errors that occur while attempting to start Instrumentation. Always writes the
13762 * error to the logs, but if somebody is watching, send the report there too. This enables
13763 * the "am" command to report errors with more information.
13764 *
13765 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13766 * @param cn The component name of the instrumentation.
13767 * @param report The error report.
13768 */
13769 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13770 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013771 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013772 try {
13773 if (watcher != null) {
13774 Bundle results = new Bundle();
13775 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13776 results.putString("Error", report);
13777 watcher.instrumentationStatus(cn, -1, results);
13778 }
13779 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013780 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013781 }
13782 }
13783
13784 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13785 if (app.instrumentationWatcher != null) {
13786 try {
13787 // NOTE: IInstrumentationWatcher *must* be oneway here
13788 app.instrumentationWatcher.instrumentationFinished(
13789 app.instrumentationClass,
13790 resultCode,
13791 results);
13792 } catch (RemoteException e) {
13793 }
13794 }
13795 app.instrumentationWatcher = null;
13796 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013797 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013798 app.instrumentationProfileFile = null;
13799 app.instrumentationArguments = null;
13800
Christopher Tate3dacd842011-08-19 14:56:15 -070013801 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013802 }
13803
13804 public void finishInstrumentation(IApplicationThread target,
13805 int resultCode, Bundle results) {
13806 // Refuse possible leaked file descriptors
13807 if (results != null && results.hasFileDescriptors()) {
13808 throw new IllegalArgumentException("File descriptors passed in Intent");
13809 }
13810
13811 synchronized(this) {
13812 ProcessRecord app = getRecordForAppLocked(target);
13813 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013814 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013815 return;
13816 }
13817 final long origId = Binder.clearCallingIdentity();
13818 finishInstrumentationLocked(app, resultCode, results);
13819 Binder.restoreCallingIdentity(origId);
13820 }
13821 }
13822
13823 // =========================================================
13824 // CONFIGURATION
13825 // =========================================================
13826
13827 public ConfigurationInfo getDeviceConfigurationInfo() {
13828 ConfigurationInfo config = new ConfigurationInfo();
13829 synchronized (this) {
13830 config.reqTouchScreen = mConfiguration.touchscreen;
13831 config.reqKeyboardType = mConfiguration.keyboard;
13832 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013833 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13834 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013835 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13836 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013837 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13838 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013839 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13840 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013841 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013842 }
13843 return config;
13844 }
13845
13846 public Configuration getConfiguration() {
13847 Configuration ci;
13848 synchronized(this) {
13849 ci = new Configuration(mConfiguration);
13850 }
13851 return ci;
13852 }
13853
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013854 public void updatePersistentConfiguration(Configuration values) {
13855 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13856 "updateConfiguration()");
13857 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13858 "updateConfiguration()");
13859 if (values == null) {
13860 throw new NullPointerException("Configuration must not be null");
13861 }
13862
13863 synchronized(this) {
13864 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013865 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013866 Binder.restoreCallingIdentity(origId);
13867 }
13868 }
13869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013870 public void updateConfiguration(Configuration values) {
13871 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13872 "updateConfiguration()");
13873
13874 synchronized(this) {
13875 if (values == null && mWindowManager != null) {
13876 // sentinel: fetch the current configuration from the window manager
13877 values = mWindowManager.computeNewConfiguration();
13878 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013879
13880 if (mWindowManager != null) {
13881 mProcessList.applyDisplaySize(mWindowManager);
13882 }
13883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013884 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013885 if (values != null) {
13886 Settings.System.clearConfiguration(values);
13887 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013888 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013889 Binder.restoreCallingIdentity(origId);
13890 }
13891 }
13892
13893 /**
13894 * Do either or both things: (1) change the current configuration, and (2)
13895 * make sure the given activity is running with the (now) current
13896 * configuration. Returns true if the activity has been left running, or
13897 * false if <var>starting</var> is being destroyed to match the new
13898 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013899 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013900 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013901 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013902 ActivityRecord starting, boolean persistent, boolean initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013903 int changes = 0;
13904
13905 boolean kept = true;
13906
13907 if (values != null) {
13908 Configuration newConfig = new Configuration(mConfiguration);
13909 changes = newConfig.updateFrom(values);
13910 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013911 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013912 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013913 }
13914
Doug Zongker2bec3d42009-12-04 12:52:44 -080013915 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013916
Dianne Hackborn813075a62011-11-14 17:45:19 -080013917 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013918 saveLocaleLocked(values.locale,
13919 !values.locale.equals(mConfiguration.locale),
13920 values.userSetLocale);
13921 }
13922
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013923 mConfigurationSeq++;
13924 if (mConfigurationSeq <= 0) {
13925 mConfigurationSeq = 1;
13926 }
13927 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013928 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013929 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013930
13931 final Configuration configCopy = new Configuration(mConfiguration);
13932
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013933 AttributeCache ac = AttributeCache.instance();
13934 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013935 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013937
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013938 // Make sure all resources in our process are updated
13939 // right now, so that anyone who is going to retrieve
13940 // resource values after we return will be sure to get
13941 // the new ones. This is especially important during
13942 // boot, where the first config change needs to guarantee
13943 // all resources have that config before following boot
13944 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013945 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013946
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013947 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013948 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013949 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013950 mHandler.sendMessage(msg);
13951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013952
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013953 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13954 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013955 try {
13956 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013957 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013958 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013959 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013960 }
13961 } catch (Exception e) {
13962 }
13963 }
13964 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013965 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13966 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013967 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013968 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013969 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13970 broadcastIntentLocked(null, null,
13971 new Intent(Intent.ACTION_LOCALE_CHANGED),
13972 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013973 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013975 }
13976 }
13977
13978 if (changes != 0 && starting == null) {
13979 // If the configuration changed, and the caller is not already
13980 // in the process of starting an activity, then find the top
13981 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013982 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013983 }
13984
13985 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013986 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013987 // And we need to make sure at this point that all other activities
13988 // are made visible with the correct configuration.
13989 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013990 }
13991
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013992 if (values != null && mWindowManager != null) {
13993 mWindowManager.setNewConfiguration(mConfiguration);
13994 }
13995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013996 return kept;
13997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013998
13999 /**
14000 * Save the locale. You must be inside a synchronized (this) block.
14001 */
14002 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
14003 if(isDiff) {
14004 SystemProperties.set("user.language", l.getLanguage());
14005 SystemProperties.set("user.region", l.getCountry());
14006 }
14007
14008 if(isPersist) {
14009 SystemProperties.set("persist.sys.language", l.getLanguage());
14010 SystemProperties.set("persist.sys.country", l.getCountry());
14011 SystemProperties.set("persist.sys.localevar", l.getVariant());
14012 }
14013 }
14014
14015 // =========================================================
14016 // LIFETIME MANAGEMENT
14017 // =========================================================
14018
Christopher Tatef46723b2012-01-26 14:19:24 -080014019 // Returns which broadcast queue the app is the current [or imminent] receiver
14020 // on, or 'null' if the app is not an active broadcast recipient.
14021 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
14022 BroadcastRecord r = app.curReceiver;
14023 if (r != null) {
14024 return r.queue;
14025 }
14026
14027 // It's not the current receiver, but it might be starting up to become one
14028 synchronized (this) {
14029 for (BroadcastQueue queue : mBroadcastQueues) {
14030 r = queue.mPendingBroadcast;
14031 if (r != null && r.curApp == app) {
14032 // found it; report which queue it's in
14033 return queue;
14034 }
14035 }
14036 }
14037
14038 return null;
14039 }
14040
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014041 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014042 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014043 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014044 // This adjustment has already been computed. If we are calling
14045 // from the top, we may have already computed our adjustment with
14046 // an earlier hidden adjustment that isn't really for us... if
14047 // so, use the new hidden adjustment.
14048 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014049 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014050 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014051 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014052 }
14053
14054 if (app.thread == null) {
14055 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014056 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014057 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014058 }
14059
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014060 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
14061 app.adjSource = null;
14062 app.adjTarget = null;
14063 app.empty = false;
14064 app.hidden = false;
14065
14066 final int activitiesSize = app.activities.size();
14067
Dianne Hackborn7d608422011-08-07 16:24:18 -070014068 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014069 // The max adjustment doesn't allow this app to be anything
14070 // below foreground, so it is not worth doing work for it.
14071 app.adjType = "fixed";
14072 app.adjSeq = mAdjSeq;
14073 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014074 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014075 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014076 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014077 // System process can do UI, and when they do we want to have
14078 // them trim their memory after the user leaves the UI. To
14079 // facilitate this, here we need to determine whether or not it
14080 // is currently showing UI.
14081 app.systemNoUi = true;
14082 if (app == TOP_APP) {
14083 app.systemNoUi = false;
14084 } else if (activitiesSize > 0) {
14085 for (int j = 0; j < activitiesSize; j++) {
14086 final ActivityRecord r = app.activities.get(j);
14087 if (r.visible) {
14088 app.systemNoUi = false;
14089 break;
14090 }
14091 }
14092 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014093 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014094 }
14095
14096 final boolean hadForegroundActivities = app.foregroundActivities;
14097
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014098 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014099 app.keeping = false;
14100 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014101
The Android Open Source Project4df24232009-03-05 14:34:35 -080014102 // Determine the importance of the process, starting with most
14103 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014104 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014105 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080014106 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014107 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014108 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014109 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014110 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014111 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014112 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014113 } else if (app.instrumentationClass != null) {
14114 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014115 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014116 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014117 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080014118 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014119 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080014120 // counts as being in the foreground for OOM killer purposes.
14121 // It's placed in a sched group based on the nature of the
14122 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014123 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080014124 schedGroup = (queue == mFgBroadcastQueue)
14125 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014126 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014127 } else if (app.executingServices.size() > 0) {
14128 // An app that is currently executing a service callback also
14129 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014130 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014131 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014132 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014133 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014134 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014135 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014136 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014137 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014138 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014139 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014140 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014141 // A very not-needed process. If this is lower in the lru list,
14142 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014143 adj = hiddenAdj;
14144 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014145 app.hidden = true;
14146 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014147 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014148 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014149
14150 // Examine all activities if not already foreground.
14151 if (!app.foregroundActivities && activitiesSize > 0) {
14152 for (int j = 0; j < activitiesSize; j++) {
14153 final ActivityRecord r = app.activities.get(j);
14154 if (r.visible) {
14155 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014156 if (adj > ProcessList.VISIBLE_APP_ADJ) {
14157 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014158 app.adjType = "visible";
14159 }
14160 schedGroup = Process.THREAD_GROUP_DEFAULT;
14161 app.hidden = false;
14162 app.foregroundActivities = true;
14163 break;
14164 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
14165 || r.state == ActivityState.STOPPING) {
14166 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014167 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14168 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014169 app.adjType = "stopping";
14170 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080014171 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014172 app.foregroundActivities = true;
14173 }
14174 }
14175 }
14176
Dianne Hackborn7d608422011-08-07 16:24:18 -070014177 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014178 if (app.foregroundServices) {
14179 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014180 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014181 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014182 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014183 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014184 } else if (app.forcingToForeground != null) {
14185 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014186 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014187 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014188 app.adjType = "force-foreground";
14189 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014190 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014191 }
14192 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014193
Dianne Hackborn7d608422011-08-07 16:24:18 -070014194 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014195 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014196 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014197 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014198 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014199 app.adjType = "heavy";
14200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014201
Dianne Hackborn7d608422011-08-07 16:24:18 -070014202 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014203 // This process is hosting what we currently consider to be the
14204 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014205 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014206 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014207 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014208 app.adjType = "home";
14209 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014210
Dianne Hackbornf35fe232011-11-01 19:25:20 -070014211 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
14212 && app.activities.size() > 0) {
14213 // This was the previous process that showed UI to the user.
14214 // We want to try to keep it around more aggressively, to give
14215 // a good experience around switching between two apps.
14216 adj = ProcessList.PREVIOUS_APP_ADJ;
14217 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
14218 app.hidden = false;
14219 app.adjType = "previous";
14220 }
14221
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014222 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
14223 + " reason=" + app.adjType);
14224
The Android Open Source Project4df24232009-03-05 14:34:35 -080014225 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014226 // there are applications dependent on our services or providers, but
14227 // this gives us a baseline and makes sure we don't get into an
14228 // infinite recursion.
14229 app.adjSeq = mAdjSeq;
14230 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014231
Christopher Tate6fa95972009-06-05 18:43:55 -070014232 if (mBackupTarget != null && app == mBackupTarget.app) {
14233 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070014234 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014235 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014236 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014237 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014238 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070014239 }
14240 }
14241
Dianne Hackborn7d608422011-08-07 16:24:18 -070014242 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014243 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014244 final long now = SystemClock.uptimeMillis();
14245 // This process is more important if the top activity is
14246 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070014247 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014248 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014249 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014250 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014251 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014252 // If this process has shown some UI, let it immediately
14253 // go to the LRU list because it may be pretty heavy with
14254 // UI stuff. We'll tag it with a label just to help
14255 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014256 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014257 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014258 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014259 } else {
14260 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
14261 // This service has seen some activity within
14262 // recent memory, so we will keep its process ahead
14263 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014264 if (adj > ProcessList.SERVICE_ADJ) {
14265 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014266 app.adjType = "started-services";
14267 app.hidden = false;
14268 }
14269 }
14270 // If we have let the service slide into the background
14271 // state, still have some text describing what it is doing
14272 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014273 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014274 app.adjType = "started-bg-services";
14275 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014276 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014277 // Don't kill this process because it is doing work; it
14278 // has said it is doing work.
14279 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014280 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014281 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014282 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014283 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014284 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014285 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014286 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014287 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014288 // XXX should compute this based on the max of
14289 // all connected clients.
14290 ConnectionRecord cr = clist.get(i);
14291 if (cr.binding.client == app) {
14292 // Binding to ourself is not interesting.
14293 continue;
14294 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014295 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014296 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014297 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014298 int myHiddenAdj = hiddenAdj;
14299 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014300 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014301 myHiddenAdj = client.hiddenAdj;
14302 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014303 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014304 }
14305 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014306 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014307 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014308 String adjType = null;
14309 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
14310 // Not doing bind OOM management, so treat
14311 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014312 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014313 // If this process has shown some UI, let it immediately
14314 // go to the LRU list because it may be pretty heavy with
14315 // UI stuff. We'll tag it with a label just to help
14316 // debug and understand what is going on.
14317 if (adj > clientAdj) {
14318 adjType = "bound-bg-ui-services";
14319 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014320 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014321 clientAdj = adj;
14322 } else {
14323 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
14324 // This service has not seen activity within
14325 // recent memory, so allow it to drop to the
14326 // LRU list if there is no other reason to keep
14327 // it around. We'll also tag it with a label just
14328 // to help debug and undertand what is going on.
14329 if (adj > clientAdj) {
14330 adjType = "bound-bg-services";
14331 }
14332 clientAdj = adj;
14333 }
14334 }
14335 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014336 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014337 // If this process has recently shown UI, and
14338 // the process that is binding to it is less
14339 // important than being visible, then we don't
14340 // care about the binding as much as we care
14341 // about letting this process get into the LRU
14342 // list to be killed and restarted if needed for
14343 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014344 if (app.hasShownUi && app != mHomeProcess
14345 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014346 adjType = "bound-bg-ui-services";
14347 } else {
14348 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
14349 |Context.BIND_IMPORTANT)) != 0) {
14350 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014351 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
14352 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
14353 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14354 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14355 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014356 adj = clientAdj;
14357 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014358 app.pendingUiClean = true;
14359 if (adj > ProcessList.VISIBLE_APP_ADJ) {
14360 adj = ProcessList.VISIBLE_APP_ADJ;
14361 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014362 }
14363 if (!client.hidden) {
14364 app.hidden = false;
14365 }
14366 if (client.keeping) {
14367 app.keeping = true;
14368 }
14369 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014370 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014371 }
14372 if (adjType != null) {
14373 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014374 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14375 .REASON_SERVICE_IN_USE;
14376 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014377 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014378 app.adjTarget = s.name;
14379 }
14380 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14381 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14382 schedGroup = Process.THREAD_GROUP_DEFAULT;
14383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014384 }
14385 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014386 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
14387 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014388 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014389 (a.visible || a.state == ActivityState.RESUMED
14390 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014391 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014392 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14393 schedGroup = Process.THREAD_GROUP_DEFAULT;
14394 }
14395 app.hidden = false;
14396 app.adjType = "service";
14397 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14398 .REASON_SERVICE_IN_USE;
14399 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014400 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014401 app.adjTarget = s.name;
14402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014404 }
14405 }
14406 }
14407 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014408
Dianne Hackborn287952c2010-09-22 22:34:31 -070014409 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014410 // would like to avoid killing it unless it would prevent the current
14411 // application from running. By default we put the process in
14412 // with the rest of the background processes; as we scan through
14413 // its services we may bump it up from there.
14414 if (adj > hiddenAdj) {
14415 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014416 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014417 app.adjType = "bg-services";
14418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014419 }
14420
Dianne Hackborn7d608422011-08-07 16:24:18 -070014421 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014422 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014423 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014424 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014425 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014426 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014427 if (cpr.clients.size() != 0) {
14428 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014429 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014430 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070014431 if (client == app) {
14432 // Being our own client is not interesting.
14433 continue;
14434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014435 int myHiddenAdj = hiddenAdj;
14436 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014437 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014438 myHiddenAdj = client.hiddenAdj;
14439 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014440 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014441 }
14442 }
14443 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014444 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014445 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014446 if (app.hasShownUi && app != mHomeProcess
14447 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014448 app.adjType = "bg-ui-provider";
14449 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014450 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
14451 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014452 app.adjType = "provider";
14453 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014454 if (!client.hidden) {
14455 app.hidden = false;
14456 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014457 if (client.keeping) {
14458 app.keeping = true;
14459 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070014460 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14461 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014462 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014463 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014464 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014465 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014466 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14467 schedGroup = Process.THREAD_GROUP_DEFAULT;
14468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014469 }
14470 }
14471 // If the provider has external (non-framework) process
14472 // dependencies, ensure that its adjustment is at least
14473 // FOREGROUND_APP_ADJ.
14474 if (cpr.externals != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014475 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
14476 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014477 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014478 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014479 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014480 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014481 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014482 }
14483 }
14484 }
14485 }
14486
14487 app.curRawAdj = adj;
14488
Joe Onorato8a9b2202010-02-26 18:56:32 -080014489 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014490 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14491 if (adj > app.maxAdj) {
14492 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014493 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014494 schedGroup = Process.THREAD_GROUP_DEFAULT;
14495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014496 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014497 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014498 app.keeping = true;
14499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014500
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014501 if (app.hasAboveClient) {
14502 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14503 // then we need to drop its adjustment to be lower than the service's
14504 // in order to honor the request. We want to drop it by one adjustment
14505 // level... but there is special meaning applied to various levels so
14506 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014507 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014508 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014509 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14510 adj = ProcessList.VISIBLE_APP_ADJ;
14511 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14512 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14513 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14514 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014515 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014516 adj++;
14517 }
14518 }
14519
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014520 if (adj == ProcessList.SERVICE_ADJ) {
14521 if (doingAll) {
14522 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
14523 mNewNumServiceProcs++;
14524 }
14525 if (app.serviceb) {
14526 adj = ProcessList.SERVICE_B_ADJ;
14527 }
14528 } else {
14529 app.serviceb = false;
14530 }
14531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014532 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014533 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014534
14535 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014536 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14537 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014538 }
14539
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014540 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014541 }
14542
14543 /**
14544 * Ask a given process to GC right now.
14545 */
14546 final void performAppGcLocked(ProcessRecord app) {
14547 try {
14548 app.lastRequestedGc = SystemClock.uptimeMillis();
14549 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014550 if (app.reportLowMemory) {
14551 app.reportLowMemory = false;
14552 app.thread.scheduleLowMemory();
14553 } else {
14554 app.thread.processInBackground();
14555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014556 }
14557 } catch (Exception e) {
14558 // whatever.
14559 }
14560 }
14561
14562 /**
14563 * Returns true if things are idle enough to perform GCs.
14564 */
Josh Bartel7f208742010-02-25 11:01:44 -060014565 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014566 boolean processingBroadcasts = false;
14567 for (BroadcastQueue q : mBroadcastQueues) {
14568 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14569 processingBroadcasts = true;
14570 }
14571 }
14572 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014573 && (mSleeping || (mMainStack.mResumedActivity != null &&
14574 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014575 }
14576
14577 /**
14578 * Perform GCs on all processes that are waiting for it, but only
14579 * if things are idle.
14580 */
14581 final void performAppGcsLocked() {
14582 final int N = mProcessesToGc.size();
14583 if (N <= 0) {
14584 return;
14585 }
Josh Bartel7f208742010-02-25 11:01:44 -060014586 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014587 while (mProcessesToGc.size() > 0) {
14588 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014589 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014590 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14591 <= SystemClock.uptimeMillis()) {
14592 // To avoid spamming the system, we will GC processes one
14593 // at a time, waiting a few seconds between each.
14594 performAppGcLocked(proc);
14595 scheduleAppGcsLocked();
14596 return;
14597 } else {
14598 // It hasn't been long enough since we last GCed this
14599 // process... put it in the list to wait for its time.
14600 addProcessToGcListLocked(proc);
14601 break;
14602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014603 }
14604 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014605
14606 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014607 }
14608 }
14609
14610 /**
14611 * If all looks good, perform GCs on all processes waiting for them.
14612 */
14613 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014614 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014615 performAppGcsLocked();
14616 return;
14617 }
14618 // Still not idle, wait some more.
14619 scheduleAppGcsLocked();
14620 }
14621
14622 /**
14623 * Schedule the execution of all pending app GCs.
14624 */
14625 final void scheduleAppGcsLocked() {
14626 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014627
14628 if (mProcessesToGc.size() > 0) {
14629 // Schedule a GC for the time to the next process.
14630 ProcessRecord proc = mProcessesToGc.get(0);
14631 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14632
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014633 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014634 long now = SystemClock.uptimeMillis();
14635 if (when < (now+GC_TIMEOUT)) {
14636 when = now + GC_TIMEOUT;
14637 }
14638 mHandler.sendMessageAtTime(msg, when);
14639 }
14640 }
14641
14642 /**
14643 * Add a process to the array of processes waiting to be GCed. Keeps the
14644 * list in sorted order by the last GC time. The process can't already be
14645 * on the list.
14646 */
14647 final void addProcessToGcListLocked(ProcessRecord proc) {
14648 boolean added = false;
14649 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14650 if (mProcessesToGc.get(i).lastRequestedGc <
14651 proc.lastRequestedGc) {
14652 added = true;
14653 mProcessesToGc.add(i+1, proc);
14654 break;
14655 }
14656 }
14657 if (!added) {
14658 mProcessesToGc.add(0, proc);
14659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014660 }
14661
14662 /**
14663 * Set up to ask a process to GC itself. This will either do it
14664 * immediately, or put it on the list of processes to gc the next
14665 * time things are idle.
14666 */
14667 final void scheduleAppGcLocked(ProcessRecord app) {
14668 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014669 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014670 return;
14671 }
14672 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014673 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014674 scheduleAppGcsLocked();
14675 }
14676 }
14677
Dianne Hackborn287952c2010-09-22 22:34:31 -070014678 final void checkExcessivePowerUsageLocked(boolean doKills) {
14679 updateCpuStatsNow();
14680
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014681 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014682 boolean doWakeKills = doKills;
14683 boolean doCpuKills = doKills;
14684 if (mLastPowerCheckRealtime == 0) {
14685 doWakeKills = false;
14686 }
14687 if (mLastPowerCheckUptime == 0) {
14688 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014689 }
14690 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014691 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014692 }
14693 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014694 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14695 final long curUptime = SystemClock.uptimeMillis();
14696 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14697 mLastPowerCheckRealtime = curRealtime;
14698 mLastPowerCheckUptime = curUptime;
14699 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14700 doWakeKills = false;
14701 }
14702 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14703 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014704 }
14705 int i = mLruProcesses.size();
14706 while (i > 0) {
14707 i--;
14708 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014709 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014710 long wtime;
14711 synchronized (stats) {
14712 wtime = stats.getProcessWakeTime(app.info.uid,
14713 app.pid, curRealtime);
14714 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014715 long wtimeUsed = wtime - app.lastWakeTime;
14716 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14717 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014718 StringBuilder sb = new StringBuilder(128);
14719 sb.append("Wake for ");
14720 app.toShortString(sb);
14721 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014722 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014723 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014724 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014725 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014726 sb.append((wtimeUsed*100)/realtimeSince);
14727 sb.append("%)");
14728 Slog.i(TAG, sb.toString());
14729 sb.setLength(0);
14730 sb.append("CPU for ");
14731 app.toShortString(sb);
14732 sb.append(": over ");
14733 TimeUtils.formatDuration(uptimeSince, sb);
14734 sb.append(" used ");
14735 TimeUtils.formatDuration(cputimeUsed, sb);
14736 sb.append(" (");
14737 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014738 sb.append("%)");
14739 Slog.i(TAG, sb.toString());
14740 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014741 // If a process has held a wake lock for more
14742 // than 50% of the time during this period,
14743 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014744 if (doWakeKills && realtimeSince > 0
14745 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14746 synchronized (stats) {
14747 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14748 realtimeSince, wtimeUsed);
14749 }
14750 Slog.w(TAG, "Excessive wake lock in " + app.processName
14751 + " (pid " + app.pid + "): held " + wtimeUsed
14752 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014753 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14754 app.processName, app.setAdj, "excessive wake lock");
14755 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014756 } else if (doCpuKills && uptimeSince > 0
14757 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14758 synchronized (stats) {
14759 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14760 uptimeSince, cputimeUsed);
14761 }
14762 Slog.w(TAG, "Excessive CPU in " + app.processName
14763 + " (pid " + app.pid + "): used " + cputimeUsed
14764 + " during " + uptimeSince);
14765 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14766 app.processName, app.setAdj, "excessive cpu");
14767 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014768 } else {
14769 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014770 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014771 }
14772 }
14773 }
14774 }
14775
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014776 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014777 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014778 app.hiddenAdj = hiddenAdj;
14779
14780 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014781 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014782 }
14783
Dianne Hackborn287952c2010-09-22 22:34:31 -070014784 final boolean wasKeeping = app.keeping;
14785
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014786 boolean success = true;
14787
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014788 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014789
Jeff Brown10e89712011-07-08 18:52:57 -070014790 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070014791 if (false) {
14792 // Removing for now. Forcing GCs is not so useful anymore
14793 // with Dalvik, and the new memory level hint facility is
14794 // better for what we need to do these days.
14795 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14796 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14797 // If this app is transitioning from foreground to
14798 // non-foreground, have it do a gc.
14799 scheduleAppGcLocked(app);
14800 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14801 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14802 // Likewise do a gc when an app is moving in to the
14803 // background (such as a service stopping).
14804 scheduleAppGcLocked(app);
14805 }
Jeff Brown10e89712011-07-08 18:52:57 -070014806 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014807
Jeff Brown10e89712011-07-08 18:52:57 -070014808 if (wasKeeping && !app.keeping) {
14809 // This app is no longer something we want to keep. Note
14810 // its current wake lock time to later know to kill it if
14811 // it is not behaving well.
14812 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14813 synchronized (stats) {
14814 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14815 app.pid, SystemClock.elapsedRealtime());
14816 }
14817 app.lastCpuTime = app.curCpuTime;
14818 }
14819
14820 app.setRawAdj = app.curRawAdj;
14821 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014822
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014823 if (app.curAdj != app.setAdj) {
14824 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014825 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014826 TAG, "Set " + app.pid + " " + app.processName +
14827 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014828 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014829 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014830 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014831 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014832 }
14833 }
14834 if (app.setSchedGroup != app.curSchedGroup) {
14835 app.setSchedGroup = app.curSchedGroup;
14836 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14837 "Setting process group of " + app.processName
14838 + " to " + app.curSchedGroup);
14839 if (app.waitingToKill != null &&
14840 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14841 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14842 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14843 app.processName, app.setAdj, app.waitingToKill);
14844 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014845 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014846 } else {
14847 if (true) {
14848 long oldId = Binder.clearCallingIdentity();
14849 try {
14850 Process.setProcessGroup(app.pid, app.curSchedGroup);
14851 } catch (Exception e) {
14852 Slog.w(TAG, "Failed setting process group of " + app.pid
14853 + " to " + app.curSchedGroup);
14854 e.printStackTrace();
14855 } finally {
14856 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014857 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014858 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014859 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014860 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014861 app.thread.setSchedulingGroup(app.curSchedGroup);
14862 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014863 }
14864 }
14865 }
14866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014867 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014868 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014869 }
14870
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014871 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014872 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014873 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborncbb722e2012-02-07 18:33:49 -080014874 for (int i=mMainStack.mPausingActivities.size()-1; i>=0; i--) {
14875 ActivityRecord r = mMainStack.mPausingActivities.get(i);
14876 if (r.app != null) {
14877 resumedActivity = r;
14878 break;
14879 }
14880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014881 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014882 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014883 }
14884 }
14885 return resumedActivity;
14886 }
14887
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014888 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014889 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014890 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14891 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014892 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14893 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014894
14895 mAdjSeq++;
14896
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014897 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014898 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14899 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014900 if (nowHidden != wasHidden) {
14901 // Changed to/from hidden state, so apps after it in the LRU
14902 // list may also be changed.
14903 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014904 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014905 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014906 }
14907
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014908 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014909 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014910 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14911
14912 if (false) {
14913 RuntimeException e = new RuntimeException();
14914 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014915 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014916 }
14917
14918 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014919 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014920
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014921 // Let's determine how many processes we have running vs.
14922 // how many slots we have for background processes; we may want
14923 // to put multiple processes in a slot of there are enough of
14924 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014925 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014926 int factor = (mLruProcesses.size()-4)/numSlots;
14927 if (factor < 1) factor = 1;
14928 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014929 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014930
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014931 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014932 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014933 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014934 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014935 while (i > 0) {
14936 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014937 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014938 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014939 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14940 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014941 && app.curAdj == curHiddenAdj) {
14942 step++;
14943 if (step >= factor) {
14944 step = 0;
14945 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014946 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014947 }
14948 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014949 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014950 numHidden++;
14951 if (numHidden > mProcessLimit) {
14952 Slog.i(TAG, "No longer want " + app.processName
14953 + " (pid " + app.pid + "): hidden #" + numHidden);
14954 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14955 app.processName, app.setAdj, "too many background");
14956 app.killedBackground = true;
14957 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014958 }
14959 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014960 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14961 // If this is an isolated process, and there are no
14962 // services running in it, then the process is no longer
14963 // needed. We agressively kill these because we can by
14964 // definition not re-use the same process again, and it is
14965 // good to avoid having whatever code was running in them
14966 // left sitting around after no longer needed.
14967 Slog.i(TAG, "Isolated process " + app.processName
14968 + " (pid " + app.pid + ") no longer needed");
14969 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14970 app.processName, app.setAdj, "isolated not needed");
14971 app.killedBackground = true;
14972 Process.killProcessQuiet(app.pid);
14973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014974 }
14975 }
14976
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014977 mNumServiceProcs = mNewNumServiceProcs;
14978
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014979 // Now determine the memory trimming level of background processes.
14980 // Unfortunately we need to start at the back of the list to do this
14981 // properly. We only do this if the number of background apps we
14982 // are managing to keep around is less than half the maximum we desire;
14983 // if we are keeping a good number around, we'll let them use whatever
14984 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014985 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014986 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014987 factor = numHidden/3;
14988 int minFactor = 2;
14989 if (mHomeProcess != null) minFactor++;
14990 if (mPreviousProcess != null) minFactor++;
14991 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014992 step = 0;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014993 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014994 for (i=0; i<N; i++) {
14995 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014996 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14997 && app.curAdj != ProcessList.SERVICE_B_ADJ
14998 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014999 if (app.trimMemoryLevel < curLevel && app.thread != null) {
15000 try {
15001 app.thread.scheduleTrimMemory(curLevel);
15002 } catch (RemoteException e) {
15003 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080015004 if (false) {
15005 // For now we won't do this; our memory trimming seems
15006 // to be good enough at this point that destroying
15007 // activities causes more harm than good.
15008 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
15009 && app != mHomeProcess && app != mPreviousProcess) {
15010 // For these apps we will also finish their activities
15011 // to help them free memory.
15012 mMainStack.destroyActivitiesLocked(app, false, "trim");
15013 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015014 }
15015 }
15016 app.trimMemoryLevel = curLevel;
15017 step++;
15018 if (step >= factor) {
15019 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015020 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
15021 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015022 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015023 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
15024 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015025 break;
15026 }
15027 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070015028 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015029 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015030 && app.thread != null) {
15031 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015032 app.thread.scheduleTrimMemory(
15033 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015034 } catch (RemoteException e) {
15035 }
15036 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015037 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn7d608422011-08-07 16:24:18 -070015038 } else if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015039 && app.pendingUiClean) {
15040 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
15041 && app.thread != null) {
15042 try {
15043 app.thread.scheduleTrimMemory(
15044 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
15045 } catch (RemoteException e) {
15046 }
15047 }
15048 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
15049 app.pendingUiClean = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015050 } else {
15051 app.trimMemoryLevel = 0;
15052 }
15053 }
15054 } else {
15055 final int N = mLruProcesses.size();
15056 for (i=0; i<N; i++) {
15057 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070015058 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070015059 && app.pendingUiClean) {
15060 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
15061 && app.thread != null) {
15062 try {
15063 app.thread.scheduleTrimMemory(
15064 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
15065 } catch (RemoteException e) {
15066 }
15067 }
15068 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
15069 app.pendingUiClean = false;
15070 } else {
15071 app.trimMemoryLevel = 0;
15072 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015073 }
15074 }
15075
15076 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070015077 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015079 }
15080
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070015081 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015082 synchronized (this) {
15083 int i;
15084
15085 // First remove any unused application processes whose package
15086 // has been removed.
15087 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
15088 final ProcessRecord app = mRemovedProcesses.get(i);
15089 if (app.activities.size() == 0
15090 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080015091 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015092 TAG, "Exiting empty application process "
15093 + app.processName + " ("
15094 + (app.thread != null ? app.thread.asBinder() : null)
15095 + ")\n");
15096 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070015097 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
15098 app.processName, app.setAdj, "empty");
15099 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015100 } else {
15101 try {
15102 app.thread.scheduleExit();
15103 } catch (Exception e) {
15104 // Ignore exceptions.
15105 }
15106 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070015107 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015108 mRemovedProcesses.remove(i);
15109
15110 if (app.persistent) {
15111 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080015112 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015113 }
15114 }
15115 }
15116 }
15117
Dianne Hackbornce86ba82011-07-13 19:33:41 -070015118 // Now update the oom adj for all processes.
15119 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015120 }
15121 }
15122
15123 /** This method sends the specified signal to each of the persistent apps */
15124 public void signalPersistentProcesses(int sig) throws RemoteException {
15125 if (sig != Process.SIGNAL_USR1) {
15126 throw new SecurityException("Only SIGNAL_USR1 is allowed");
15127 }
15128
15129 synchronized (this) {
15130 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
15131 != PackageManager.PERMISSION_GRANTED) {
15132 throw new SecurityException("Requires permission "
15133 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
15134 }
15135
Dianne Hackborndd71fc82009-12-16 19:24:32 -080015136 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
15137 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015138 if (r.thread != null && r.persistent) {
15139 Process.sendSignal(r.pid, sig);
15140 }
15141 }
15142 }
15143 }
15144
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015145 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
15146 if (proc == null || proc == mProfileProc) {
15147 proc = mProfileProc;
15148 path = mProfileFile;
15149 profileType = mProfileType;
15150 clearProfilerLocked();
15151 }
15152 if (proc == null) {
15153 return;
15154 }
15155 try {
15156 proc.thread.profilerControl(false, path, null, profileType);
15157 } catch (RemoteException e) {
15158 throw new IllegalStateException("Process disappeared");
15159 }
15160 }
15161
15162 private void clearProfilerLocked() {
15163 if (mProfileFd != null) {
15164 try {
15165 mProfileFd.close();
15166 } catch (IOException e) {
15167 }
15168 }
15169 mProfileApp = null;
15170 mProfileProc = null;
15171 mProfileFile = null;
15172 mProfileType = 0;
15173 mAutoStopProfiler = false;
15174 }
15175
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015176 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070015177 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015178
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015179 try {
15180 synchronized (this) {
15181 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
15182 // its own permission.
15183 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15184 != PackageManager.PERMISSION_GRANTED) {
15185 throw new SecurityException("Requires permission "
15186 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015187 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015188
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015189 if (start && fd == null) {
15190 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015191 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015192
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015193 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015194 if (process != null) {
15195 try {
15196 int pid = Integer.parseInt(process);
15197 synchronized (mPidsSelfLocked) {
15198 proc = mPidsSelfLocked.get(pid);
15199 }
15200 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015201 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015202
15203 if (proc == null) {
15204 HashMap<String, SparseArray<ProcessRecord>> all
15205 = mProcessNames.getMap();
15206 SparseArray<ProcessRecord> procs = all.get(process);
15207 if (procs != null && procs.size() > 0) {
15208 proc = procs.valueAt(0);
15209 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015210 }
15211 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015212
15213 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015214 throw new IllegalArgumentException("Unknown process: " + process);
15215 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015216
15217 if (start) {
15218 stopProfilerLocked(null, null, 0);
15219 setProfileApp(proc.info, proc.processName, path, fd, false);
15220 mProfileProc = proc;
15221 mProfileType = profileType;
15222 try {
15223 fd = fd.dup();
15224 } catch (IOException e) {
15225 fd = null;
15226 }
15227 proc.thread.profilerControl(start, path, fd, profileType);
15228 fd = null;
15229 mProfileFd = null;
15230 } else {
15231 stopProfilerLocked(proc, path, profileType);
15232 if (fd != null) {
15233 try {
15234 fd.close();
15235 } catch (IOException e) {
15236 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015237 }
15238 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015239
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015240 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015241 }
15242 } catch (RemoteException e) {
15243 throw new IllegalStateException("Process disappeared");
15244 } finally {
15245 if (fd != null) {
15246 try {
15247 fd.close();
15248 } catch (IOException e) {
15249 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015250 }
15251 }
15252 }
Andy McFadden824c5102010-07-09 16:26:57 -070015253
15254 public boolean dumpHeap(String process, boolean managed,
15255 String path, ParcelFileDescriptor fd) throws RemoteException {
15256
15257 try {
15258 synchronized (this) {
15259 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
15260 // its own permission (same as profileControl).
15261 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15262 != PackageManager.PERMISSION_GRANTED) {
15263 throw new SecurityException("Requires permission "
15264 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
15265 }
15266
15267 if (fd == null) {
15268 throw new IllegalArgumentException("null fd");
15269 }
15270
15271 ProcessRecord proc = null;
15272 try {
15273 int pid = Integer.parseInt(process);
15274 synchronized (mPidsSelfLocked) {
15275 proc = mPidsSelfLocked.get(pid);
15276 }
15277 } catch (NumberFormatException e) {
15278 }
15279
15280 if (proc == null) {
15281 HashMap<String, SparseArray<ProcessRecord>> all
15282 = mProcessNames.getMap();
15283 SparseArray<ProcessRecord> procs = all.get(process);
15284 if (procs != null && procs.size() > 0) {
15285 proc = procs.valueAt(0);
15286 }
15287 }
15288
15289 if (proc == null || proc.thread == null) {
15290 throw new IllegalArgumentException("Unknown process: " + process);
15291 }
15292
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080015293 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
15294 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070015295 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
15296 throw new SecurityException("Process not debuggable: " + proc);
15297 }
15298 }
15299
15300 proc.thread.dumpHeap(managed, path, fd);
15301 fd = null;
15302 return true;
15303 }
15304 } catch (RemoteException e) {
15305 throw new IllegalStateException("Process disappeared");
15306 } finally {
15307 if (fd != null) {
15308 try {
15309 fd.close();
15310 } catch (IOException e) {
15311 }
15312 }
15313 }
15314 }
15315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015316 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
15317 public void monitor() {
15318 synchronized (this) { }
15319 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015320
Dianne Hackborna573f6a2012-02-09 16:12:18 -080015321 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015322 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
15323 ProcessRecord processRecord = mLruProcesses.get(i);
15324 try {
15325 if (processRecord.thread != null) {
15326 processRecord.thread.setCoreSettings(settings);
15327 }
15328 } catch (RemoteException re) {
15329 /* ignore */
15330 }
15331 }
15332 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015333
15334 // Multi-user methods
15335
Amith Yamasani742a6712011-05-04 14:49:28 -070015336 private int mCurrentUserId;
15337 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
15338
15339 public boolean switchUser(int userId) {
15340 final int callingUid = Binder.getCallingUid();
15341 if (callingUid != 0 && callingUid != Process.myUid()) {
15342 Slog.e(TAG, "Trying to switch user from unauthorized app");
15343 return false;
15344 }
15345 if (mCurrentUserId == userId)
15346 return true;
15347
15348 synchronized (this) {
15349 // Check if user is already logged in, otherwise check if user exists first before
15350 // adding to the list of logged in users.
15351 if (mLoggedInUsers.indexOfKey(userId) < 0) {
15352 if (!userExists(userId)) {
15353 return false;
15354 }
15355 mLoggedInUsers.append(userId, userId);
15356 }
15357
15358 mCurrentUserId = userId;
15359 boolean haveActivities = mMainStack.switchUser(userId);
15360 if (!haveActivities) {
15361 startHomeActivityLocked(userId);
15362 }
15363 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015364 return true;
15365 }
Amith Yamasani742a6712011-05-04 14:49:28 -070015366
15367 private boolean userExists(int userId) {
15368 try {
15369 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
15370 for (UserInfo user : users) {
15371 if (user.id == userId) {
15372 return true;
15373 }
15374 }
15375 } catch (RemoteException re) {
15376 // Won't happen, in same process
15377 }
15378
15379 return false;
15380 }
15381
15382
15383 private int applyUserId(int uid, int userId) {
15384 return UserId.getUid(userId, uid);
15385 }
15386
15387 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080015388 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070015389 ApplicationInfo newInfo = new ApplicationInfo(info);
15390 newInfo.uid = applyUserId(info.uid, userId);
15391 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
15392 newInfo.dataDir = USER_DATA_DIR + userId + "/"
15393 + info.packageName;
15394 }
15395 return newInfo;
15396 }
15397
15398 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080015399 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070015400 || userId < 1) {
15401 return aInfo;
15402 }
15403
15404 ActivityInfo info = new ActivityInfo(aInfo);
15405 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
15406 return info;
15407 }
15408
15409 static class ServiceMap {
15410
15411 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
15412 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
15413 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
15414 mServicesByIntentPerUser = new SparseArray<
15415 HashMap<Intent.FilterComparison, ServiceRecord>>();
15416
15417 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
15418 // TODO: Deal with global services
15419 if (DEBUG_MU)
15420 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
15421 return getServices(callingUser).get(name);
15422 }
15423
15424 ServiceRecord getServiceByName(ComponentName name) {
15425 return getServiceByName(name, -1);
15426 }
15427
15428 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15429 // TODO: Deal with global services
15430 if (DEBUG_MU)
15431 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
15432 return getServicesByIntent(callingUser).get(filter);
15433 }
15434
15435 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
15436 return getServiceByIntent(filter, -1);
15437 }
15438
15439 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
15440 // TODO: Deal with global services
15441 getServices(callingUser).put(name, value);
15442 }
15443
15444 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
15445 ServiceRecord value) {
15446 // TODO: Deal with global services
15447 getServicesByIntent(callingUser).put(filter, value);
15448 }
15449
15450 void removeServiceByName(ComponentName name, int callingUser) {
15451 // TODO: Deal with global services
15452 ServiceRecord removed = getServices(callingUser).remove(name);
15453 if (DEBUG_MU)
15454 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15455 + " removed=" + removed);
15456 }
15457
15458 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15459 // TODO: Deal with global services
15460 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15461 if (DEBUG_MU)
15462 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15463 + " removed=" + removed);
15464 }
15465
15466 Collection<ServiceRecord> getAllServices(int callingUser) {
15467 // TODO: Deal with global services
15468 return getServices(callingUser).values();
15469 }
15470
15471 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15472 HashMap map = mServicesByNamePerUser.get(callingUser);
15473 if (map == null) {
15474 map = new HashMap<ComponentName, ServiceRecord>();
15475 mServicesByNamePerUser.put(callingUser, map);
15476 }
15477 return map;
15478 }
15479
15480 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15481 int callingUser) {
15482 HashMap map = mServicesByIntentPerUser.get(callingUser);
15483 if (map == null) {
15484 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15485 mServicesByIntentPerUser.put(callingUser, map);
15486 }
15487 return map;
15488 }
15489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015490}