blob: a089fcff013427ee4ffa15763994b6213761f098 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Dianne Hackborn860755f2010-06-03 18:47:52 -070019import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070021import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070022import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import com.android.server.IntentResolver;
24import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.SystemServer;
26import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070027import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080028import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029
Dianne Hackborndd71fc82009-12-16 19:24:32 -080030import dalvik.system.Zygote;
31
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.app.Activity;
33import android.app.ActivityManager;
34import android.app.ActivityManagerNative;
35import android.app.ActivityThread;
36import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070037import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020038import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070040import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.IActivityWatcher;
42import android.app.IApplicationThread;
43import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070044import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070045import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.app.IServiceConnection;
47import android.app.IThumbnailReceiver;
48import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070049import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070050import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070052import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080053import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020054import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080055import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070056import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.content.ComponentName;
58import android.content.ContentResolver;
59import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020060import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.Intent;
62import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070063import android.content.IIntentReceiver;
64import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070065import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.content.pm.ActivityInfo;
67import android.content.pm.ApplicationInfo;
68import android.content.pm.ConfigurationInfo;
69import android.content.pm.IPackageDataObserver;
70import android.content.pm.IPackageManager;
71import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080072import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070074import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.content.pm.ProviderInfo;
76import android.content.pm.ResolveInfo;
77import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070078import android.content.pm.UserInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070079import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040080import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.content.res.Configuration;
82import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070083import android.net.Proxy;
84import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.net.Uri;
86import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080087import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080088import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070089import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080090import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080092import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.os.FileUtils;
94import android.os.Handler;
95import android.os.IBinder;
96import android.os.IPermissionController;
97import android.os.Looper;
98import android.os.Message;
99import android.os.Parcel;
100import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700102import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.os.RemoteException;
104import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700105import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.SystemClock;
107import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700108import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700111import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800112import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800113import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.util.PrintWriterPrinter;
115import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700116import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700117import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.view.Gravity;
119import android.view.LayoutInflater;
120import android.view.View;
121import android.view.WindowManager;
122import android.view.WindowManagerPolicy;
123
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700124import java.io.BufferedInputStream;
125import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700126import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700127import java.io.DataInputStream;
128import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import java.io.File;
130import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700131import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700133import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200134import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800135import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700137import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import java.lang.IllegalStateException;
139import java.lang.ref.WeakReference;
140import java.util.ArrayList;
Dianne Hackborncbb722e2012-02-07 18:33:49 -0800141import java.util.Arrays;
Amith Yamasani742a6712011-05-04 14:49:28 -0700142import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700143import java.util.Collections;
144import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.util.HashMap;
146import java.util.HashSet;
147import java.util.Iterator;
148import java.util.List;
149import java.util.Locale;
150import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700151import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700152import java.util.concurrent.atomic.AtomicBoolean;
153import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700155public final class ActivityManagerService extends ActivityManagerNative
156 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700157 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700159 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400161 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final boolean DEBUG_SWITCH = localLOGV || false;
163 static final boolean DEBUG_TASKS = localLOGV || false;
164 static final boolean DEBUG_PAUSE = localLOGV || false;
165 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
166 static final boolean DEBUG_TRANSITION = localLOGV || false;
167 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800168 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700169 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700171 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 static final boolean DEBUG_VISBILITY = localLOGV || false;
173 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700174 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800175 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700177 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700178 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700179 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700180 static final boolean DEBUG_POWER = localLOGV || false;
181 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700182 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 static final boolean VALIDATE_TOKENS = false;
184 static final boolean SHOW_ACTIVITY_START_TIME = true;
185
186 // Control over CPU and battery monitoring.
187 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
188 static final boolean MONITOR_CPU_USAGE = true;
189 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
190 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
191 static final boolean MONITOR_THREAD_CPU_USAGE = false;
192
Dianne Hackborn1655be42009-05-08 14:29:01 -0700193 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700194 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700195
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800196 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 // Maximum number of recent tasks that we can remember.
199 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700200
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700201 // Amount of time after a call to stopAppSwitches() during which we will
202 // prevent further untrusted switches from happening.
203 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
205 // How long we wait for a launched process to attach to the activity manager
206 // before we decide it's never going to come up for real.
207 static final int PROC_START_TIMEOUT = 10*1000;
208
Jeff Brown3f9dd282011-07-08 20:02:19 -0700209 // How long we wait for a launched process to attach to the activity manager
210 // before we decide it's never going to come up for real, when the process was
211 // started with a wrapper for instrumentation (such as Valgrind) because it
212 // could take much longer than usual.
213 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 // How long to wait after going idle before forcing apps to GC.
216 static final int GC_TIMEOUT = 5*1000;
217
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700218 // The minimum amount of time between successive GC requests for a process.
219 static final int GC_MIN_INTERVAL = 60*1000;
220
Dianne Hackborn287952c2010-09-22 22:34:31 -0700221 // The rate at which we check for apps using excessive power -- 15 mins.
222 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
223
224 // The minimum sample duration we will allow before deciding we have
225 // enough data on wake locks to start killing things.
226 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
227
228 // The minimum sample duration we will allow before deciding we have
229 // enough data on CPU usage to start killing things.
230 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800233 static final int BROADCAST_FG_TIMEOUT = 10*1000;
234 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
236 // How long we wait for a service to finish executing.
237 static final int SERVICE_TIMEOUT = 20*1000;
238
239 // How long a service needs to be running until restarting its process
240 // is no longer considered to be a relaunch of the service.
241 static final int SERVICE_RESTART_DURATION = 5*1000;
242
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700243 // How long a service needs to be running until it will start back at
244 // SERVICE_RESTART_DURATION after being killed.
245 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
246
247 // Multiplying factor to increase restart duration time by, for each time
248 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
249 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
250
251 // The minimum amount of time between restarting services that we allow.
252 // That is, when multiple services are restarting, we won't allow each
253 // to restart less than this amount of time from the last one.
254 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 // Maximum amount of time for there to be no activity on a service before
257 // we consider it non-essential and allow its process to go on the
258 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700259 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260
261 // How long we wait until we timeout on key dispatching.
262 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 // How long we wait until we timeout on key dispatching during instrumentation.
265 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
266
Dan Egnor42471dd2010-01-07 17:25:22 -0800267 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
269 static final String[] EMPTY_STRING_ARRAY = new String[0];
270
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700271 public ActivityStack mMainStack;
272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700274 * Description of a request to start a new activity, which has been held
275 * due to app switches being disabled.
276 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700277 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700278 ActivityRecord r;
279 ActivityRecord sourceRecord;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700280 Uri[] grantedUriPermissions;
281 int grantedMode;
282 boolean onlyIfNeeded;
283 }
284
285 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
286 = new ArrayList<PendingActivityLaunch>();
287
288 /**
Christopher Tatef46723b2012-01-26 14:19:24 -0800289 * BROADCASTS
290 *
291 * We keep two broadcast queues and associated bookkeeping, one for those at
292 * foreground priority, and one for normal (background-priority) broadcasts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 */
Christopher Tatef46723b2012-01-26 14:19:24 -0800294 public class BroadcastQueue {
295 static final String TAG = "BroadcastQueue";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296
Christopher Tatef46723b2012-01-26 14:19:24 -0800297 static final int MAX_BROADCAST_HISTORY = 25;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298
Christopher Tatef46723b2012-01-26 14:19:24 -0800299 /**
300 * Recognizable moniker for this queue
301 */
302 String mQueueName;
Dianne Hackborn12527f92009-11-11 17:39:50 -0800303
Christopher Tatef46723b2012-01-26 14:19:24 -0800304 /**
305 * Timeout period for this queue's broadcasts
306 */
307 long mTimeoutPeriod;
308
309 /**
310 * Lists of all active broadcasts that are to be executed immediately
311 * (without waiting for another broadcast to finish). Currently this only
312 * contains broadcasts to registered receivers, to avoid spinning up
313 * a bunch of processes to execute IntentReceiver components. Background-
314 * and foreground-priority broadcasts are queued separately.
315 */
316 final ArrayList<BroadcastRecord> mParallelBroadcasts
317 = new ArrayList<BroadcastRecord>();
318 /**
319 * List of all active broadcasts that are to be executed one at a time.
320 * The object at the top of the list is the currently activity broadcasts;
321 * those after it are waiting for the top to finish. As with parallel
322 * broadcasts, separate background- and foreground-priority queues are
323 * maintained.
324 */
325 final ArrayList<BroadcastRecord> mOrderedBroadcasts
326 = new ArrayList<BroadcastRecord>();
327
328 /**
329 * Historical data of past broadcasts, for debugging.
330 */
331 final BroadcastRecord[] mBroadcastHistory
332 = new BroadcastRecord[MAX_BROADCAST_HISTORY];
333
334 /**
335 * Set when we current have a BROADCAST_INTENT_MSG in flight.
336 */
337 boolean mBroadcastsScheduled = false;
338
339 /**
340 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
341 */
342 boolean mPendingBroadcastTimeoutMessage;
343
344 /**
345 * Intent broadcasts that we have tried to start, but are
346 * waiting for the application's process to be created. We only
347 * need one per scheduling class (instead of a list) because we always
348 * process broadcasts one at a time, so no others can be started while
349 * waiting for this one.
350 */
351 BroadcastRecord mPendingBroadcast = null;
352
353 /**
354 * The receiver index that is pending, to restart the broadcast if needed.
355 */
356 int mPendingBroadcastRecvIndex;
357
358 BroadcastQueue(String name, long timeoutPeriod) {
359 mQueueName = name;
360 mTimeoutPeriod = timeoutPeriod;
361 }
362
363 public boolean isPendingBroadcastProcessLocked(int pid) {
364 return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
365 }
366
367 public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
368 mParallelBroadcasts.add(r);
369 }
370
371 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
372 mOrderedBroadcasts.add(r);
373 }
374
375 public final boolean replaceParallelBroadcastLocked(BroadcastRecord r) {
376 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
377 if (r.intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
378 if (DEBUG_BROADCAST) Slog.v(TAG,
379 "***** DROPPING PARALLEL ["
380 + mQueueName + "]: " + r.intent);
381 mParallelBroadcasts.set(i, r);
382 return true;
383 }
384 }
385 return false;
386 }
387
388 public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
389 for (int i=mOrderedBroadcasts.size()-1; i>0; i--) {
390 if (r.intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
391 if (DEBUG_BROADCAST) Slog.v(TAG,
392 "***** DROPPING ORDERED ["
393 + mQueueName + "]: " + r.intent);
394 mOrderedBroadcasts.set(i, r);
395 return true;
396 }
397 }
398 return false;
399 }
400
401 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
402 boolean didSomething = false;
403 final BroadcastRecord br = mPendingBroadcast;
404 if (br != null && br.curApp.pid == app.pid) {
405 try {
406 mPendingBroadcast = null;
407 processCurBroadcastLocked(br, app);
408 didSomething = true;
409 } catch (Exception e) {
410 Slog.w(TAG, "Exception in new application when starting receiver "
411 + br.curComponent.flattenToShortString(), e);
412 logBroadcastReceiverDiscardLocked(br);
413 finishReceiverLocked(br, br.resultCode, br.resultData,
414 br.resultExtras, br.resultAbort, true);
415 scheduleBroadcastsLocked();
416 // We need to reset the state if we fails to start the receiver.
417 br.state = BroadcastRecord.IDLE;
418 throw new RuntimeException(e.getMessage());
419 }
420 }
421 return didSomething;
422 }
423
424 public void skipPendingBroadcastLocked(int pid) {
425 final BroadcastRecord br = mPendingBroadcast;
426 if (br != null && br.curApp.pid == pid) {
427 br.state = BroadcastRecord.IDLE;
428 br.nextReceiver = mPendingBroadcastRecvIndex;
429 mPendingBroadcast = null;
430 scheduleBroadcastsLocked();
431 }
432 }
433
434 public void skipCurrentReceiverLocked(ProcessRecord app) {
435 boolean reschedule = false;
436 BroadcastRecord r = app.curReceiver;
437 if (r != null) {
438 // The current broadcast is waiting for this app's receiver
439 // to be finished. Looks like that's not going to happen, so
440 // let the broadcast continue.
441 logBroadcastReceiverDiscardLocked(r);
442 finishReceiverLocked(r, r.resultCode, r.resultData,
443 r.resultExtras, r.resultAbort, true);
444 reschedule = true;
445 }
446
447 r = mPendingBroadcast;
448 if (r != null && r.curApp == app) {
449 if (DEBUG_BROADCAST) Slog.v(TAG,
450 "[" + mQueueName + "] skip & discard pending app " + r);
451 logBroadcastReceiverDiscardLocked(r);
452 finishReceiverLocked(r, r.resultCode, r.resultData,
453 r.resultExtras, r.resultAbort, true);
454 reschedule = true;
455 }
456 if (reschedule) {
457 scheduleBroadcastsLocked();
458 }
459 }
460
461 public void scheduleBroadcastsLocked() {
462 if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts ["
463 + mQueueName + "]: current="
464 + mBroadcastsScheduled);
465
466 if (mBroadcastsScheduled) {
467 return;
468 }
469 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
470 mBroadcastsScheduled = true;
471 }
472
473 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
474 if (mOrderedBroadcasts.size() > 0) {
475 final BroadcastRecord r = mOrderedBroadcasts.get(0);
476 if (r != null && r.receiver == receiver) {
477 return r;
478 }
479 }
480 return null;
481 }
482
483 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
484 String resultData, Bundle resultExtras, boolean resultAbort,
485 boolean explicit) {
486 int state = r.state;
487 r.state = BroadcastRecord.IDLE;
488 if (state == BroadcastRecord.IDLE) {
489 if (explicit) {
490 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
491 }
492 }
493 r.receiver = null;
494 r.intent.setComponent(null);
495 if (r.curApp != null) {
496 r.curApp.curReceiver = null;
497 }
498 if (r.curFilter != null) {
499 r.curFilter.receiverList.curBroadcast = null;
500 }
501 r.curFilter = null;
502 r.curApp = null;
503 r.curComponent = null;
504 r.curReceiver = null;
505 mPendingBroadcast = null;
506
507 r.resultCode = resultCode;
508 r.resultData = resultData;
509 r.resultExtras = resultExtras;
510 r.resultAbort = resultAbort;
511
512 // We will process the next receiver right now if this is finishing
513 // an app receiver (which is always asynchronous) or after we have
514 // come back from calling a receiver.
515 return state == BroadcastRecord.APP_RECEIVE
516 || state == BroadcastRecord.CALL_DONE_RECEIVE;
517 }
518
519 private final void processNextBroadcast(boolean fromMsg) {
520 synchronized(ActivityManagerService.this) {
521 BroadcastRecord r;
522
523 if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast ["
524 + mQueueName + "]: "
525 + mParallelBroadcasts.size() + " broadcasts, "
526 + mOrderedBroadcasts.size() + " ordered broadcasts");
527
528 updateCpuStats();
529
530 if (fromMsg) {
531 mBroadcastsScheduled = false;
532 }
533
534 // First, deliver any non-serialized broadcasts right away.
535 while (mParallelBroadcasts.size() > 0) {
536 r = mParallelBroadcasts.remove(0);
537 r.dispatchTime = SystemClock.uptimeMillis();
538 r.dispatchClockTime = System.currentTimeMillis();
539 final int N = r.receivers.size();
540 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast ["
541 + mQueueName + "] " + r);
542 for (int i=0; i<N; i++) {
543 Object target = r.receivers.get(i);
544 if (DEBUG_BROADCAST) Slog.v(TAG,
545 "Delivering non-ordered on [" + mQueueName + "] to registered "
546 + target + ": " + r);
547 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
548 }
549 addBroadcastToHistoryLocked(r);
550 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast ["
551 + mQueueName + "] " + r);
552 }
553
554 // Now take care of the next serialized one...
555
556 // If we are waiting for a process to come up to handle the next
557 // broadcast, then do nothing at this point. Just in case, we
558 // check that the process we're waiting for still exists.
559 if (mPendingBroadcast != null) {
560 if (DEBUG_BROADCAST_LIGHT) {
561 Slog.v(TAG, "processNextBroadcast ["
562 + mQueueName + "]: waiting for "
563 + mPendingBroadcast.curApp);
564 }
565
566 boolean isDead;
567 synchronized (mPidsSelfLocked) {
568 isDead = (mPidsSelfLocked.get(mPendingBroadcast.curApp.pid) == null);
569 }
570 if (!isDead) {
571 // It's still alive, so keep waiting
572 return;
573 } else {
574 Slog.w(TAG, "pending app ["
575 + mQueueName + "]" + mPendingBroadcast.curApp
576 + " died before responding to broadcast");
577 mPendingBroadcast.state = BroadcastRecord.IDLE;
578 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
579 mPendingBroadcast = null;
580 }
581 }
582
583 boolean looped = false;
584
585 do {
586 if (mOrderedBroadcasts.size() == 0) {
587 // No more broadcasts pending, so all done!
588 scheduleAppGcsLocked();
589 if (looped) {
590 // If we had finished the last ordered broadcast, then
591 // make sure all processes have correct oom and sched
592 // adjustments.
593 updateOomAdjLocked();
594 }
595 return;
596 }
597 r = mOrderedBroadcasts.get(0);
598 boolean forceReceive = false;
599
600 // Ensure that even if something goes awry with the timeout
601 // detection, we catch "hung" broadcasts here, discard them,
602 // and continue to make progress.
603 //
604 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
605 // receivers don't get executed with timeouts. They're intended for
606 // one time heavy lifting after system upgrades and can take
607 // significant amounts of time.
608 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
609 if (mProcessesReady && r.dispatchTime > 0) {
610 long now = SystemClock.uptimeMillis();
611 if ((numReceivers > 0) &&
612 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
613 Slog.w(TAG, "Hung broadcast ["
614 + mQueueName + "] discarded after timeout failure:"
615 + " now=" + now
616 + " dispatchTime=" + r.dispatchTime
617 + " startTime=" + r.receiverTime
618 + " intent=" + r.intent
619 + " numReceivers=" + numReceivers
620 + " nextReceiver=" + r.nextReceiver
621 + " state=" + r.state);
622 broadcastTimeoutLocked(false); // forcibly finish this broadcast
623 forceReceive = true;
624 r.state = BroadcastRecord.IDLE;
625 }
626 }
627
628 if (r.state != BroadcastRecord.IDLE) {
629 if (DEBUG_BROADCAST) Slog.d(TAG,
630 "processNextBroadcast("
631 + mQueueName + ") called when not idle (state="
632 + r.state + ")");
633 return;
634 }
635
636 if (r.receivers == null || r.nextReceiver >= numReceivers
637 || r.resultAbort || forceReceive) {
638 // No more receivers for this broadcast! Send the final
639 // result if requested...
640 if (r.resultTo != null) {
641 try {
642 if (DEBUG_BROADCAST) {
643 int seq = r.intent.getIntExtra("seq", -1);
644 Slog.i(TAG, "Finishing broadcast ["
645 + mQueueName + "] " + r.intent.getAction()
646 + " seq=" + seq + " app=" + r.callerApp);
647 }
648 performReceiveLocked(r.callerApp, r.resultTo,
649 new Intent(r.intent), r.resultCode,
650 r.resultData, r.resultExtras, false, false);
651 // Set this to null so that the reference
652 // (local and remote) isnt kept in the mBroadcastHistory.
653 r.resultTo = null;
654 } catch (RemoteException e) {
655 Slog.w(TAG, "Failure ["
656 + mQueueName + "] sending broadcast result of "
657 + r.intent, e);
658 }
659 }
660
661 if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
662 cancelBroadcastTimeoutLocked();
663
664 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
665 + r);
666
667 // ... and on to the next...
668 addBroadcastToHistoryLocked(r);
669 mOrderedBroadcasts.remove(0);
670 r = null;
671 looped = true;
672 continue;
673 }
674 } while (r == null);
675
676 // Get the next receiver...
677 int recIdx = r.nextReceiver++;
678
679 // Keep track of when this receiver started, and make sure there
680 // is a timeout message pending to kill it if need be.
681 r.receiverTime = SystemClock.uptimeMillis();
682 if (recIdx == 0) {
683 r.dispatchTime = r.receiverTime;
684 r.dispatchClockTime = System.currentTimeMillis();
685 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast ["
686 + mQueueName + "] " + r);
687 }
688 if (! mPendingBroadcastTimeoutMessage) {
689 long timeoutTime = r.receiverTime + mTimeoutPeriod;
690 if (DEBUG_BROADCAST) Slog.v(TAG,
691 "Submitting BROADCAST_TIMEOUT_MSG ["
692 + mQueueName + "] for " + r + " at " + timeoutTime);
693 setBroadcastTimeoutLocked(timeoutTime);
694 }
695
696 Object nextReceiver = r.receivers.get(recIdx);
697 if (nextReceiver instanceof BroadcastFilter) {
698 // Simple case: this is a registered receiver who gets
699 // a direct call.
700 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
701 if (DEBUG_BROADCAST) Slog.v(TAG,
702 "Delivering ordered ["
703 + mQueueName + "] to registered "
704 + filter + ": " + r);
705 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
706 if (r.receiver == null || !r.ordered) {
707 // The receiver has already finished, so schedule to
708 // process the next one.
709 if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing ["
710 + mQueueName + "]: ordered="
711 + r.ordered + " receiver=" + r.receiver);
712 r.state = BroadcastRecord.IDLE;
713 scheduleBroadcastsLocked();
714 }
715 return;
716 }
717
718 // Hard case: need to instantiate the receiver, possibly
719 // starting its application process to host it.
720
721 ResolveInfo info =
722 (ResolveInfo)nextReceiver;
723
724 boolean skip = false;
725 int perm = checkComponentPermission(info.activityInfo.permission,
726 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
727 info.activityInfo.exported);
728 if (perm != PackageManager.PERMISSION_GRANTED) {
729 if (!info.activityInfo.exported) {
730 Slog.w(TAG, "Permission Denial: broadcasting "
731 + r.intent.toString()
732 + " from " + r.callerPackage + " (pid=" + r.callingPid
733 + ", uid=" + r.callingUid + ")"
734 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
735 + " due to receiver " + info.activityInfo.packageName
736 + "/" + info.activityInfo.name);
737 } else {
738 Slog.w(TAG, "Permission Denial: broadcasting "
739 + r.intent.toString()
740 + " from " + r.callerPackage + " (pid=" + r.callingPid
741 + ", uid=" + r.callingUid + ")"
742 + " requires " + info.activityInfo.permission
743 + " due to receiver " + info.activityInfo.packageName
744 + "/" + info.activityInfo.name);
745 }
746 skip = true;
747 }
748 if (info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
749 r.requiredPermission != null) {
750 try {
751 perm = AppGlobals.getPackageManager().
752 checkPermission(r.requiredPermission,
753 info.activityInfo.applicationInfo.packageName);
754 } catch (RemoteException e) {
755 perm = PackageManager.PERMISSION_DENIED;
756 }
757 if (perm != PackageManager.PERMISSION_GRANTED) {
758 Slog.w(TAG, "Permission Denial: receiving "
759 + r.intent + " to "
760 + info.activityInfo.applicationInfo.packageName
761 + " requires " + r.requiredPermission
762 + " due to sender " + r.callerPackage
763 + " (uid " + r.callingUid + ")");
764 skip = true;
765 }
766 }
767 if (r.curApp != null && r.curApp.crashing) {
768 // If the target process is crashing, just skip it.
769 if (DEBUG_BROADCAST) Slog.v(TAG,
770 "Skipping deliver ordered ["
771 + mQueueName + "] " + r + " to " + r.curApp
772 + ": process crashing");
773 skip = true;
774 }
775
776 if (skip) {
777 if (DEBUG_BROADCAST) Slog.v(TAG,
778 "Skipping delivery of ordered ["
779 + mQueueName + "] " + r + " for whatever reason");
780 r.receiver = null;
781 r.curFilter = null;
782 r.state = BroadcastRecord.IDLE;
783 scheduleBroadcastsLocked();
784 return;
785 }
786
787 r.state = BroadcastRecord.APP_RECEIVE;
788 String targetProcess = info.activityInfo.processName;
789 r.curComponent = new ComponentName(
790 info.activityInfo.applicationInfo.packageName,
791 info.activityInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -0700792 if (r.callingUid != Process.SYSTEM_UID) {
793 info.activityInfo = getActivityInfoForUser(info.activityInfo, UserId
794 .getUserId(r.callingUid));
795 }
Christopher Tatef46723b2012-01-26 14:19:24 -0800796 r.curReceiver = info.activityInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -0700797 if (DEBUG_MU && r.callingUid > UserId.PER_USER_RANGE) {
798 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
799 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
800 + info.activityInfo.applicationInfo.uid);
801 }
Christopher Tatef46723b2012-01-26 14:19:24 -0800802
803 // Broadcast is being executed, its package can't be stopped.
804 try {
805 AppGlobals.getPackageManager().setPackageStoppedState(
806 r.curComponent.getPackageName(), false);
807 } catch (RemoteException e) {
808 } catch (IllegalArgumentException e) {
809 Slog.w(TAG, "Failed trying to unstop package "
810 + r.curComponent.getPackageName() + ": " + e);
811 }
812
813 // Is this receiver's application already running?
814 ProcessRecord app = getProcessRecordLocked(targetProcess,
815 info.activityInfo.applicationInfo.uid);
816 if (app != null && app.thread != null) {
817 try {
818 app.addPackage(info.activityInfo.packageName);
819 processCurBroadcastLocked(r, app);
820 return;
821 } catch (RemoteException e) {
822 Slog.w(TAG, "Exception when sending broadcast to "
823 + r.curComponent, e);
824 }
825
826 // If a dead object exception was thrown -- fall through to
827 // restart the application.
828 }
829
830 // Not running -- get it started, to be executed when the app comes up.
831 if (DEBUG_BROADCAST) Slog.v(TAG,
832 "Need to start app ["
833 + mQueueName + "] " + targetProcess + " for broadcast " + r);
834 if ((r.curApp=startProcessLocked(targetProcess,
835 info.activityInfo.applicationInfo, true,
836 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
837 "broadcast", r.curComponent,
838 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0))
839 == null) {
840 // Ah, this recipient is unavailable. Finish it if necessary,
841 // and mark the broadcast record as ready for the next.
842 Slog.w(TAG, "Unable to launch app "
843 + info.activityInfo.applicationInfo.packageName + "/"
844 + info.activityInfo.applicationInfo.uid + " for broadcast "
845 + r.intent + ": process is bad");
846 logBroadcastReceiverDiscardLocked(r);
847 finishReceiverLocked(r, r.resultCode, r.resultData,
848 r.resultExtras, r.resultAbort, true);
849 scheduleBroadcastsLocked();
850 r.state = BroadcastRecord.IDLE;
851 return;
852 }
853
854 mPendingBroadcast = r;
855 mPendingBroadcastRecvIndex = recIdx;
856 }
857 }
858
859 final void setBroadcastTimeoutLocked(long timeoutTime) {
860 if (! mPendingBroadcastTimeoutMessage) {
861 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
862 mHandler.sendMessageAtTime(msg, timeoutTime);
863 mPendingBroadcastTimeoutMessage = true;
864 }
865 }
866
867 final void cancelBroadcastTimeoutLocked() {
868 if (mPendingBroadcastTimeoutMessage) {
869 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
870 mPendingBroadcastTimeoutMessage = false;
871 }
872 }
873
874 final void broadcastTimeoutLocked(boolean fromMsg) {
875 if (fromMsg) {
876 mPendingBroadcastTimeoutMessage = false;
877 }
878
879 if (mOrderedBroadcasts.size() == 0) {
880 return;
881 }
882
883 long now = SystemClock.uptimeMillis();
884 BroadcastRecord r = mOrderedBroadcasts.get(0);
885 if (fromMsg) {
886 if (mDidDexOpt) {
887 // Delay timeouts until dexopt finishes.
888 mDidDexOpt = false;
889 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
890 setBroadcastTimeoutLocked(timeoutTime);
891 return;
892 }
893 if (! mProcessesReady) {
894 // Only process broadcast timeouts if the system is ready. That way
895 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
896 // to do heavy lifting for system up.
897 return;
898 }
899
900 long timeoutTime = r.receiverTime + mTimeoutPeriod;
901 if (timeoutTime > now) {
902 // We can observe premature timeouts because we do not cancel and reset the
903 // broadcast timeout message after each receiver finishes. Instead, we set up
904 // an initial timeout then kick it down the road a little further as needed
905 // when it expires.
906 if (DEBUG_BROADCAST) Slog.v(TAG,
907 "Premature timeout ["
908 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
909 + timeoutTime);
910 setBroadcastTimeoutLocked(timeoutTime);
911 return;
912 }
913 }
914
915 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
916 + ", started " + (now - r.receiverTime) + "ms ago");
917 r.receiverTime = now;
918 r.anrCount++;
919
920 // Current receiver has passed its expiration date.
921 if (r.nextReceiver <= 0) {
922 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
923 return;
924 }
925
926 ProcessRecord app = null;
927 String anrMessage = null;
928
929 Object curReceiver = r.receivers.get(r.nextReceiver-1);
930 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
931 logBroadcastReceiverDiscardLocked(r);
932 if (curReceiver instanceof BroadcastFilter) {
933 BroadcastFilter bf = (BroadcastFilter)curReceiver;
934 if (bf.receiverList.pid != 0
935 && bf.receiverList.pid != MY_PID) {
936 synchronized (ActivityManagerService.this.mPidsSelfLocked) {
937 app = ActivityManagerService.this.mPidsSelfLocked.get(
938 bf.receiverList.pid);
939 }
940 }
941 } else {
942 app = r.curApp;
943 }
944
945 if (app != null) {
946 anrMessage = "Broadcast of " + r.intent.toString();
947 }
948
949 if (mPendingBroadcast == r) {
950 mPendingBroadcast = null;
951 }
952
953 // Move on to the next receiver.
954 finishReceiverLocked(r, r.resultCode, r.resultData,
955 r.resultExtras, r.resultAbort, true);
956 scheduleBroadcastsLocked();
957
958 if (anrMessage != null) {
959 // Post the ANR to the handler since we do not want to process ANRs while
960 // potentially holding our lock.
961 mHandler.post(new AppNotResponding(app, anrMessage));
962 }
963 }
964
965 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
966 if (r.callingUid < 0) {
967 // This was from a registerReceiver() call; ignore it.
968 return;
969 }
970 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
971 MAX_BROADCAST_HISTORY-1);
972 r.finishTime = SystemClock.uptimeMillis();
973 mBroadcastHistory[0] = r;
974 }
975
976 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
977 if (r.nextReceiver > 0) {
978 Object curReceiver = r.receivers.get(r.nextReceiver-1);
979 if (curReceiver instanceof BroadcastFilter) {
980 BroadcastFilter bf = (BroadcastFilter) curReceiver;
981 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
982 System.identityHashCode(r),
983 r.intent.getAction(),
984 r.nextReceiver - 1,
985 System.identityHashCode(bf));
986 } else {
987 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
988 System.identityHashCode(r),
989 r.intent.getAction(),
990 r.nextReceiver - 1,
991 ((ResolveInfo)curReceiver).toString());
992 }
993 } else {
994 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
995 + r);
996 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
997 System.identityHashCode(r),
998 r.intent.getAction(),
999 r.nextReceiver,
1000 "NONE");
1001 }
1002 }
1003
1004 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1005 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
1006 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1007 || mPendingBroadcast != null) {
1008 boolean printed = false;
1009 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
1010 BroadcastRecord br = mParallelBroadcasts.get(i);
1011 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1012 continue;
1013 }
1014 if (!printed) {
1015 if (needSep) {
1016 pw.println();
1017 needSep = false;
1018 }
1019 printed = true;
1020 pw.println(" Active broadcasts [" + mQueueName + "]:");
1021 }
1022 pw.println(" Broadcast #" + i + ":");
1023 br.dump(pw, " ");
1024 }
1025 printed = false;
1026 needSep = true;
1027 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
1028 BroadcastRecord br = mOrderedBroadcasts.get(i);
1029 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1030 continue;
1031 }
1032 if (!printed) {
1033 if (needSep) {
1034 pw.println();
1035 }
1036 needSep = true;
1037 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1038 }
1039 pw.println(" Ordered Broadcast #" + i + ":");
1040 mOrderedBroadcasts.get(i).dump(pw, " ");
1041 }
1042 if (dumpPackage == null || (mPendingBroadcast != null
1043 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1044 if (needSep) {
1045 pw.println();
1046 }
1047 pw.println(" Pending broadcast [" + mQueueName + "]:");
1048 if (mPendingBroadcast != null) {
1049 mPendingBroadcast.dump(pw, " ");
1050 } else {
1051 pw.println(" (null)");
1052 }
1053 needSep = true;
1054 }
1055 }
1056
1057 boolean printed = false;
1058 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
1059 BroadcastRecord r = mBroadcastHistory[i];
1060 if (r == null) {
1061 break;
1062 }
1063 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1064 continue;
1065 }
1066 if (!printed) {
1067 if (needSep) {
1068 pw.println();
1069 }
1070 needSep = true;
1071 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1072 printed = true;
1073 }
1074 if (dumpAll) {
1075 pw.print(" Historical Broadcast #"); pw.print(i); pw.println(":");
1076 r.dump(pw, " ");
1077 } else {
1078 if (i >= 50) {
1079 pw.println(" ...");
1080 break;
1081 }
1082 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1083 }
1084 }
1085
1086 return needSep;
1087 }
1088 }
1089
1090 final BroadcastQueue mFgBroadcastQueue = new BroadcastQueue("foreground", BROADCAST_FG_TIMEOUT);
1091 final BroadcastQueue mBgBroadcastQueue = new BroadcastQueue("background", BROADCAST_BG_TIMEOUT);
1092 // Convenient for easy iteration over the queues. Foreground is first
1093 // so that dispatch of foreground broadcasts gets precedence.
1094 final BroadcastQueue[] mBroadcastQueues = { mFgBroadcastQueue, mBgBroadcastQueue };
1095
1096 BroadcastQueue broadcastQueueForIntent(Intent intent) {
1097 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
1098 if (DEBUG_BACKGROUND_BROADCAST) {
1099 Slog.i(TAG, "Broadcast intent " + intent + " on "
1100 + (isFg ? "foreground" : "background")
1101 + " queue");
1102 }
1103 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
1104 }
1105
1106 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
1107 for (BroadcastQueue queue : mBroadcastQueues) {
1108 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
1109 if (r != null) {
1110 return r;
1111 }
1112 }
1113 return null;
1114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115
1116 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 * Activity we have told the window manager to have key focus.
1118 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001119 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07001120 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 * List of intents that were used to start the most recent tasks.
1122 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001123 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124
1125 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -07001126 * Process management.
1127 */
1128 final ProcessList mProcessList = new ProcessList();
1129
1130 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 * All of the applications we currently have running organized by name.
1132 * The keys are strings of the application package name (as
1133 * returned by the package manager), and the keys are ApplicationRecord
1134 * objects.
1135 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001136 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137
1138 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -07001139 * The currently running heavy-weight process, if any.
1140 */
1141 ProcessRecord mHeavyWeightProcess = null;
1142
1143 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 * The last time that various processes have crashed.
1145 */
1146 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
1147
1148 /**
1149 * Set of applications that we consider to be bad, and will reject
1150 * incoming broadcasts from (which the user has no control over).
1151 * Processes are added to this set when they have crashed twice within
1152 * a minimum amount of time; they are removed from it when they are
1153 * later restarted (hopefully due to some user action). The value is the
1154 * time it was added to the list.
1155 */
1156 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
1157
1158 /**
1159 * All of the processes we currently have running organized by pid.
1160 * The keys are the pid running the application.
1161 *
1162 * <p>NOTE: This object is protected by its own lock, NOT the global
1163 * activity manager lock!
1164 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001165 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166
1167 /**
1168 * All of the processes that have been forced to be foreground. The key
1169 * is the pid of the caller who requested it (we hold a death
1170 * link on it).
1171 */
1172 abstract class ForegroundToken implements IBinder.DeathRecipient {
1173 int pid;
1174 IBinder token;
1175 }
1176 final SparseArray<ForegroundToken> mForegroundProcesses
1177 = new SparseArray<ForegroundToken>();
1178
1179 /**
1180 * List of records for processes that someone had tried to start before the
1181 * system was ready. We don't start them at that point, but ensure they
1182 * are started by the time booting is complete.
1183 */
1184 final ArrayList<ProcessRecord> mProcessesOnHold
1185 = new ArrayList<ProcessRecord>();
1186
1187 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 * List of persistent applications that are in the process
1189 * of being started.
1190 */
1191 final ArrayList<ProcessRecord> mPersistentStartingProcesses
1192 = new ArrayList<ProcessRecord>();
1193
1194 /**
1195 * Processes that are being forcibly torn down.
1196 */
1197 final ArrayList<ProcessRecord> mRemovedProcesses
1198 = new ArrayList<ProcessRecord>();
1199
1200 /**
1201 * List of running applications, sorted by recent usage.
1202 * The first entry in the list is the least recently used.
1203 * It contains ApplicationRecord objects. This list does NOT include
1204 * any persistent application records (since we never want to exit them).
1205 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001206 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 = new ArrayList<ProcessRecord>();
1208
1209 /**
1210 * List of processes that should gc as soon as things are idle.
1211 */
1212 final ArrayList<ProcessRecord> mProcessesToGc
1213 = new ArrayList<ProcessRecord>();
1214
1215 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -08001216 * This is the process holding what we currently consider to be
1217 * the "home" activity.
1218 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001219 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -08001220
1221 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -07001222 * This is the process holding the activity the user last visited that
1223 * is in a different process from the one they are currently in.
1224 */
1225 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -08001226
1227 /**
1228 * The time at which the previous process was last visible.
1229 */
1230 long mPreviousProcessVisibleTime;
1231
Dianne Hackbornf35fe232011-11-01 19:25:20 -07001232 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001233 * Packages that the user has asked to have run in screen size
1234 * compatibility mode instead of filling the screen.
1235 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001236 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001237
1238 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 * Set of PendingResultRecord objects that are currently active.
1240 */
1241 final HashSet mPendingResultRecords = new HashSet();
1242
1243 /**
1244 * Set of IntentSenderRecord objects that are currently active.
1245 */
1246 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
1247 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
1248
1249 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08001250 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07001251 * already logged DropBox entries for. Guarded by itself. If
1252 * something (rogue user app) forces this over
1253 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
1254 */
1255 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
1256 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
1257
1258 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07001259 * Strict Mode background batched logging state.
1260 *
1261 * The string buffer is guarded by itself, and its lock is also
1262 * used to determine if another batched write is already
1263 * in-flight.
1264 */
1265 private final StringBuilder mStrictModeBuffer = new StringBuilder();
1266
1267 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 * Keeps track of all IIntentReceivers that have been registered for
1269 * broadcasts. Hash keys are the receiver IBinder, hash value is
1270 * a ReceiverList.
1271 */
1272 final HashMap mRegisteredReceivers = new HashMap();
1273
1274 /**
1275 * Resolver for broadcast intents to registered receivers.
1276 * Holds BroadcastFilter (subclass of IntentFilter).
1277 */
1278 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
1279 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
1280 @Override
1281 protected boolean allowFilterResult(
1282 BroadcastFilter filter, List<BroadcastFilter> dest) {
1283 IBinder target = filter.receiverList.receiver.asBinder();
1284 for (int i=dest.size()-1; i>=0; i--) {
1285 if (dest.get(i).receiverList.receiver.asBinder() == target) {
1286 return false;
1287 }
1288 }
1289 return true;
1290 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001291
1292 @Override
1293 protected String packageForFilter(BroadcastFilter filter) {
1294 return filter.packageName;
1295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 };
1297
1298 /**
1299 * State of all active sticky broadcasts. Keys are the action of the
1300 * sticky Intent, values are an ArrayList of all broadcasted intents with
1301 * that action (which should usually be one).
1302 */
1303 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
1304 new HashMap<String, ArrayList<Intent>>();
1305
Amith Yamasani742a6712011-05-04 14:49:28 -07001306 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307
1308 /**
1309 * All currently bound service connections. Keys are the IBinder of
1310 * the client's IServiceConnection.
1311 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07001312 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
1313 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314
1315 /**
1316 * List of services that we have been asked to start,
1317 * but haven't yet been able to. It is used to hold start requests
1318 * while waiting for their corresponding application thread to get
1319 * going.
1320 */
1321 final ArrayList<ServiceRecord> mPendingServices
1322 = new ArrayList<ServiceRecord>();
1323
1324 /**
1325 * List of services that are scheduled to restart following a crash.
1326 */
1327 final ArrayList<ServiceRecord> mRestartingServices
1328 = new ArrayList<ServiceRecord>();
1329
1330 /**
1331 * List of services that are in the process of being stopped.
1332 */
1333 final ArrayList<ServiceRecord> mStoppingServices
1334 = new ArrayList<ServiceRecord>();
1335
1336 /**
Christopher Tate181fafa2009-05-14 11:12:14 -07001337 * Backup/restore process management
1338 */
1339 String mBackupAppName = null;
1340 BackupRecord mBackupTarget = null;
1341
1342 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 * List of PendingThumbnailsRecord objects of clients who are still
1344 * waiting to receive all of the thumbnails for a task.
1345 */
1346 final ArrayList mPendingThumbnails = new ArrayList();
1347
1348 /**
1349 * List of HistoryRecord objects that have been finished and must
1350 * still report back to a pending thumbnail receiver.
1351 */
1352 final ArrayList mCancelledThumbnails = new ArrayList();
1353
1354 /**
1355 * All of the currently running global content providers. Keys are a
1356 * string containing the provider name and values are a
1357 * ContentProviderRecord object containing the data about it. Note
1358 * that a single provider may be published under multiple names, so
1359 * there may be multiple entries here for a single one in mProvidersByClass.
1360 */
Dianne Hackborn860755f2010-06-03 18:47:52 -07001361 final HashMap<String, ContentProviderRecord> mProvidersByName
1362 = new HashMap<String, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363
1364 /**
1365 * All of the currently running global content providers. Keys are a
1366 * string containing the provider's implementation class and values are a
1367 * ContentProviderRecord object containing the data about it.
1368 */
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07001369 final HashMap<ComponentName, ContentProviderRecord> mProvidersByClass
1370 = new HashMap<ComponentName, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371
Amith Yamasani742a6712011-05-04 14:49:28 -07001372 final ProviderMap mProviderMap = new ProviderMap();
1373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 /**
1375 * List of content providers who have clients waiting for them. The
1376 * application is currently being launched and the provider will be
1377 * removed from this list once it is published.
1378 */
Dianne Hackborn860755f2010-06-03 18:47:52 -07001379 final ArrayList<ContentProviderRecord> mLaunchingProviders
1380 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381
1382 /**
1383 * Global set of specific Uri permissions that have been granted.
1384 */
1385 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
1386 = new SparseArray<HashMap<Uri, UriPermission>>();
1387
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001388 CoreSettingsObserver mCoreSettingsObserver;
1389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 /**
1391 * Thread-local storage used to carry caller permissions over through
1392 * indirect content-provider access.
1393 * @see #ActivityManagerService.openContentUri()
1394 */
1395 private class Identity {
1396 public int pid;
1397 public int uid;
1398
1399 Identity(int _pid, int _uid) {
1400 pid = _pid;
1401 uid = _uid;
1402 }
1403 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
1406
1407 /**
1408 * All information we have collected about the runtime performance of
1409 * any user id that can impact battery performance.
1410 */
1411 final BatteryStatsService mBatteryStatsService;
1412
1413 /**
1414 * information about component usage
1415 */
1416 final UsageStatsService mUsageStatsService;
1417
1418 /**
1419 * Current configuration information. HistoryRecord objects are given
1420 * a reference to this object to indicate which configuration they are
1421 * currently running in, so this object must be kept immutable.
1422 */
1423 Configuration mConfiguration = new Configuration();
1424
1425 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001426 * Current sequencing integer of the configuration, for skipping old
1427 * configurations.
1428 */
1429 int mConfigurationSeq = 0;
1430
1431 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -07001432 * Hardware-reported OpenGLES version.
1433 */
1434 final int GL_ES_VERSION;
1435
1436 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 * List of initialization arguments to pass to all processes when binding applications to them.
1438 * For example, references to the commonly used services.
1439 */
1440 HashMap<String, IBinder> mAppBindArgs;
1441
1442 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07001443 * Temporary to avoid allocations. Protected by main lock.
1444 */
1445 final StringBuilder mStringBuilder = new StringBuilder(256);
1446
1447 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 * Used to control how we initialize the service.
1449 */
1450 boolean mStartRunning = false;
1451 ComponentName mTopComponent;
1452 String mTopAction;
1453 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001454 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 boolean mSystemReady = false;
1456 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001457 boolean mWaitingUpdate = false;
1458 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001459 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001460 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461
1462 Context mContext;
1463
1464 int mFactoryTest;
1465
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001466 boolean mCheckedForSetup;
1467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001469 * The time at which we will allow normal application switches again,
1470 * after a call to {@link #stopAppSwitches()}.
1471 */
1472 long mAppSwitchesAllowedTime;
1473
1474 /**
1475 * This is set to true after the first switch after mAppSwitchesAllowedTime
1476 * is set; any switches after that will clear the time.
1477 */
1478 boolean mDidAppSwitch;
1479
1480 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -07001481 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001482 */
Dianne Hackborn287952c2010-09-22 22:34:31 -07001483 long mLastPowerCheckRealtime;
1484
1485 /**
1486 * Last time (in uptime) at which we checked for power usage.
1487 */
1488 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001489
1490 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 * Set while we are wanting to sleep, to prevent any
1492 * activities from being started/resumed.
1493 */
1494 boolean mSleeping = false;
1495
1496 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -07001497 * Set if we are shutting down the system, similar to sleeping.
1498 */
1499 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500
1501 /**
1502 * Task identifier that activities are currently being started
1503 * in. Incremented each time a new task is created.
1504 * todo: Replace this with a TokenSpace class that generates non-repeating
1505 * integers that won't wrap.
1506 */
1507 int mCurTask = 1;
1508
1509 /**
1510 * Current sequence id for oom_adj computation traversal.
1511 */
1512 int mAdjSeq = 0;
1513
1514 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -07001515 * Current sequence id for process LRU updating.
1516 */
1517 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518
1519 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -07001520 * Keep track of the number of service processes we last found, to
1521 * determine on the next iteration which should be B services.
1522 */
1523 int mNumServiceProcs = 0;
1524 int mNewNumServiceProcs = 0;
1525
1526 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 * System monitoring: number of processes that died since the last
1528 * N procs were started.
1529 */
1530 int[] mProcDeaths = new int[20];
1531
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001532 /**
1533 * This is set if we had to do a delayed dexopt of an app before launching
1534 * it, to increasing the ANR timeouts in that case.
1535 */
1536 boolean mDidDexOpt;
1537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 String mDebugApp = null;
1539 boolean mWaitForDebugger = false;
1540 boolean mDebugTransient = false;
1541 String mOrigDebugApp = null;
1542 boolean mOrigWaitForDebugger = false;
1543 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001544 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001545 String mProfileApp = null;
1546 ProcessRecord mProfileProc = null;
1547 String mProfileFile;
1548 ParcelFileDescriptor mProfileFd;
1549 int mProfileType = 0;
1550 boolean mAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001552 final RemoteCallbackList<IActivityWatcher> mWatchers
1553 = new RemoteCallbackList<IActivityWatcher>();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001554
1555 final RemoteCallbackList<IProcessObserver> mProcessObservers
1556 = new RemoteCallbackList<IProcessObserver>();
1557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 /**
1559 * Callback of last caller to {@link #requestPss}.
1560 */
1561 Runnable mRequestPssCallback;
1562
1563 /**
1564 * Remaining processes for which we are waiting results from the last
1565 * call to {@link #requestPss}.
1566 */
1567 final ArrayList<ProcessRecord> mRequestPssList
1568 = new ArrayList<ProcessRecord>();
1569
1570 /**
1571 * Runtime statistics collection thread. This object's lock is used to
1572 * protect all related state.
1573 */
1574 final Thread mProcessStatsThread;
1575
1576 /**
1577 * Used to collect process stats when showing not responding dialog.
1578 * Protected by mProcessStatsThread.
1579 */
1580 final ProcessStats mProcessStats = new ProcessStats(
1581 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001582 final AtomicLong mLastCpuTime = new AtomicLong(0);
1583 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
1584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 long mLastWriteTime = 0;
1586
1587 /**
1588 * Set to true after the system has finished booting.
1589 */
1590 boolean mBooted = false;
1591
Dianne Hackborn7d608422011-08-07 16:24:18 -07001592 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001593 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594
1595 WindowManagerService mWindowManager;
1596
1597 static ActivityManagerService mSelf;
1598 static ActivityThread mSystemThread;
1599
1600 private final class AppDeathRecipient implements IBinder.DeathRecipient {
1601 final ProcessRecord mApp;
1602 final int mPid;
1603 final IApplicationThread mAppThread;
1604
1605 AppDeathRecipient(ProcessRecord app, int pid,
1606 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001607 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 TAG, "New death recipient " + this
1609 + " for thread " + thread.asBinder());
1610 mApp = app;
1611 mPid = pid;
1612 mAppThread = thread;
1613 }
1614
1615 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001616 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 TAG, "Death received in " + this
1618 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 synchronized(ActivityManagerService.this) {
1620 appDiedLocked(mApp, mPid, mAppThread);
1621 }
1622 }
1623 }
1624
1625 static final int SHOW_ERROR_MSG = 1;
1626 static final int SHOW_NOT_RESPONDING_MSG = 2;
1627 static final int SHOW_FACTORY_ERROR_MSG = 3;
1628 static final int UPDATE_CONFIGURATION_MSG = 4;
1629 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1630 static final int WAIT_FOR_DEBUGGER_MSG = 6;
1631 static final int BROADCAST_INTENT_MSG = 7;
1632 static final int BROADCAST_TIMEOUT_MSG = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 static final int SERVICE_TIMEOUT_MSG = 12;
1634 static final int UPDATE_TIME_ZONE = 13;
1635 static final int SHOW_UID_ERROR_MSG = 14;
1636 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001638 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001639 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001640 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001641 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
1642 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001643 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001644 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001645 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001646 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001647 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001648 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
1649 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001650 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651
1652 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001653 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001654 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655
1656 final Handler mHandler = new Handler() {
1657 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001658 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 //}
1660
1661 public void handleMessage(Message msg) {
1662 switch (msg.what) {
1663 case SHOW_ERROR_MSG: {
1664 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 synchronized (ActivityManagerService.this) {
1666 ProcessRecord proc = (ProcessRecord)data.get("app");
1667 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001668 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 return;
1670 }
1671 AppErrorResult res = (AppErrorResult) data.get("result");
Dianne Hackborn55280a92009-05-07 15:53:46 -07001672 if (!mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -08001673 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 d.show();
1675 proc.crashDialog = d;
1676 } else {
1677 // The device is asleep, so just pretend that the user
1678 // saw a crash dialog and hit "force quit".
1679 res.set(0);
1680 }
1681 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001682
1683 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 } break;
1685 case SHOW_NOT_RESPONDING_MSG: {
1686 synchronized (ActivityManagerService.this) {
1687 HashMap data = (HashMap) msg.obj;
1688 ProcessRecord proc = (ProcessRecord)data.get("app");
1689 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001690 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 return;
1692 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001693
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001694 Intent intent = new Intent("android.intent.action.ANR");
1695 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -08001696 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1697 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001698 }
1699 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -08001700 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07001701 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -08001702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001704 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 d.show();
1706 proc.anrDialog = d;
1707 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001708
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001709 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001711 case SHOW_STRICT_MODE_VIOLATION_MSG: {
1712 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1713 synchronized (ActivityManagerService.this) {
1714 ProcessRecord proc = (ProcessRecord) data.get("app");
1715 if (proc == null) {
1716 Slog.e(TAG, "App not found when showing strict mode dialog.");
1717 break;
1718 }
1719 if (proc.crashDialog != null) {
1720 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1721 return;
1722 }
1723 AppErrorResult res = (AppErrorResult) data.get("result");
1724 if (!mSleeping && !mShuttingDown) {
1725 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
1726 d.show();
1727 proc.crashDialog = d;
1728 } else {
1729 // The device is asleep, so just pretend that the user
1730 // saw a crash dialog and hit "force quit".
1731 res.set(0);
1732 }
1733 }
1734 ensureBootCompleted();
1735 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 case SHOW_FACTORY_ERROR_MSG: {
1737 Dialog d = new FactoryErrorDialog(
1738 mContext, msg.getData().getCharSequence("msg"));
1739 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001740 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 } break;
1742 case UPDATE_CONFIGURATION_MSG: {
1743 final ContentResolver resolver = mContext.getContentResolver();
1744 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1745 } break;
1746 case GC_BACKGROUND_PROCESSES_MSG: {
1747 synchronized (ActivityManagerService.this) {
1748 performAppGcsIfAppropriateLocked();
1749 }
1750 } break;
1751 case WAIT_FOR_DEBUGGER_MSG: {
1752 synchronized (ActivityManagerService.this) {
1753 ProcessRecord app = (ProcessRecord)msg.obj;
1754 if (msg.arg1 != 0) {
1755 if (!app.waitedForDebugger) {
1756 Dialog d = new AppWaitingForDebuggerDialog(
1757 ActivityManagerService.this,
1758 mContext, app);
1759 app.waitDialog = d;
1760 app.waitedForDebugger = true;
1761 d.show();
1762 }
1763 } else {
1764 if (app.waitDialog != null) {
1765 app.waitDialog.dismiss();
1766 app.waitDialog = null;
1767 }
1768 }
1769 }
1770 } break;
1771 case BROADCAST_INTENT_MSG: {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001772 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 TAG, "Received BROADCAST_INTENT_MSG");
Christopher Tatef46723b2012-01-26 14:19:24 -08001774 BroadcastQueue queue = (BroadcastQueue) msg.obj;
1775 queue.processNextBroadcast(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 } break;
1777 case BROADCAST_TIMEOUT_MSG: {
Christopher Tatef46723b2012-01-26 14:19:24 -08001778 final BroadcastQueue queue = (BroadcastQueue) msg.obj;
Jeff Brown4d94a762010-09-23 11:33:28 -07001779 synchronized (ActivityManagerService.this) {
Christopher Tatef46723b2012-01-26 14:19:24 -08001780 queue.broadcastTimeoutLocked(true);
Jeff Hamiltonacf84742010-05-25 22:10:18 -05001781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001784 if (mDidDexOpt) {
1785 mDidDexOpt = false;
1786 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1787 nmsg.obj = msg.obj;
1788 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
1789 return;
1790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 serviceTimeout((ProcessRecord)msg.obj);
1792 } break;
1793 case UPDATE_TIME_ZONE: {
1794 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001795 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1796 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 if (r.thread != null) {
1798 try {
1799 r.thread.updateTimeZone();
1800 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001801 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 }
1803 }
1804 }
1805 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001806 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001807 case CLEAR_DNS_CACHE: {
1808 synchronized (ActivityManagerService.this) {
1809 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1810 ProcessRecord r = mLruProcesses.get(i);
1811 if (r.thread != null) {
1812 try {
1813 r.thread.clearDnsCache();
1814 } catch (RemoteException ex) {
1815 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1816 }
1817 }
1818 }
1819 }
1820 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001821 case UPDATE_HTTP_PROXY: {
1822 ProxyProperties proxy = (ProxyProperties)msg.obj;
1823 String host = "";
1824 String port = "";
1825 String exclList = "";
1826 if (proxy != null) {
1827 host = proxy.getHost();
1828 port = Integer.toString(proxy.getPort());
1829 exclList = proxy.getExclusionList();
1830 }
1831 synchronized (ActivityManagerService.this) {
1832 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1833 ProcessRecord r = mLruProcesses.get(i);
1834 if (r.thread != null) {
1835 try {
1836 r.thread.setHttpProxy(host, port, exclList);
1837 } catch (RemoteException ex) {
1838 Slog.w(TAG, "Failed to update http proxy for: " +
1839 r.info.processName);
1840 }
1841 }
1842 }
1843 }
1844 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 case SHOW_UID_ERROR_MSG: {
1846 // XXX This is a temporary dialog, no need to localize.
1847 AlertDialog d = new BaseErrorDialog(mContext);
1848 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1849 d.setCancelable(false);
1850 d.setTitle("System UIDs Inconsistent");
1851 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 +02001852 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1854 mUidAlert = d;
1855 d.show();
1856 } break;
1857 case IM_FEELING_LUCKY_MSG: {
1858 if (mUidAlert != null) {
1859 mUidAlert.dismiss();
1860 mUidAlert = null;
1861 }
1862 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001864 if (mDidDexOpt) {
1865 mDidDexOpt = false;
1866 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1867 nmsg.obj = msg.obj;
1868 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1869 return;
1870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 ProcessRecord app = (ProcessRecord)msg.obj;
1872 synchronized (ActivityManagerService.this) {
1873 processStartTimedOutLocked(app);
1874 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001875 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001876 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1877 synchronized (ActivityManagerService.this) {
1878 doPendingActivityLaunchesLocked(true);
1879 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001880 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001881 case KILL_APPLICATION_MSG: {
1882 synchronized (ActivityManagerService.this) {
1883 int uid = msg.arg1;
1884 boolean restart = (msg.arg2 == 1);
1885 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001886 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001887 }
1888 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001889 case FINALIZE_PENDING_INTENT_MSG: {
1890 ((PendingIntentRecord)msg.obj).completeFinalize();
1891 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001892 case POST_HEAVY_NOTIFICATION_MSG: {
1893 INotificationManager inm = NotificationManager.getService();
1894 if (inm == null) {
1895 return;
1896 }
1897
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001898 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001899 ProcessRecord process = root.app;
1900 if (process == null) {
1901 return;
1902 }
1903
1904 try {
1905 Context context = mContext.createPackageContext(process.info.packageName, 0);
1906 String text = mContext.getString(R.string.heavy_weight_notification,
1907 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1908 Notification notification = new Notification();
1909 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1910 notification.when = 0;
1911 notification.flags = Notification.FLAG_ONGOING_EVENT;
1912 notification.tickerText = text;
1913 notification.defaults = 0; // please be quiet
1914 notification.sound = null;
1915 notification.vibrate = null;
1916 notification.setLatestEventInfo(context, text,
1917 mContext.getText(R.string.heavy_weight_notification_detail),
1918 PendingIntent.getActivity(mContext, 0, root.intent,
1919 PendingIntent.FLAG_CANCEL_CURRENT));
1920
1921 try {
1922 int[] outId = new int[1];
1923 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1924 notification, outId);
1925 } catch (RuntimeException e) {
1926 Slog.w(ActivityManagerService.TAG,
1927 "Error showing notification for heavy-weight app", e);
1928 } catch (RemoteException e) {
1929 }
1930 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001931 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001932 }
1933 } break;
1934 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1935 INotificationManager inm = NotificationManager.getService();
1936 if (inm == null) {
1937 return;
1938 }
1939 try {
1940 inm.cancelNotification("android",
1941 R.string.heavy_weight_notification);
1942 } catch (RuntimeException e) {
1943 Slog.w(ActivityManagerService.TAG,
1944 "Error canceling notification for service", e);
1945 } catch (RemoteException e) {
1946 }
1947 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001948 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1949 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001950 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001951 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001952 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1953 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001954 }
1955 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001956 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1957 synchronized (ActivityManagerService.this) {
1958 ActivityRecord ar = (ActivityRecord)msg.obj;
1959 if (mCompatModeDialog != null) {
1960 if (mCompatModeDialog.mAppInfo.packageName.equals(
1961 ar.info.applicationInfo.packageName)) {
1962 return;
1963 }
1964 mCompatModeDialog.dismiss();
1965 mCompatModeDialog = null;
1966 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001967 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001968 if (mCompatModePackages.getPackageAskCompatModeLocked(
1969 ar.packageName)) {
1970 int mode = mCompatModePackages.computeCompatModeLocked(
1971 ar.info.applicationInfo);
1972 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1973 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1974 mCompatModeDialog = new CompatModeDialog(
1975 ActivityManagerService.this, mContext,
1976 ar.info.applicationInfo);
1977 mCompatModeDialog.show();
1978 }
1979 }
1980 }
1981 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001982 break;
1983 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001984 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001985 final int pid = msg.arg1;
1986 final int uid = msg.arg2;
1987 final boolean foregroundActivities = (Boolean) msg.obj;
1988 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001989 break;
1990 }
1991 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001992 final int pid = msg.arg1;
1993 final int uid = msg.arg2;
1994 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001995 break;
1996 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001997 case REPORT_MEM_USAGE: {
1998 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1999 if (!isDebuggable) {
2000 return;
2001 }
2002 synchronized (ActivityManagerService.this) {
2003 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002004 if (now < (mLastMemUsageReportTime+5*60*1000)) {
2005 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002006 // avoid spamming.
2007 return;
2008 }
2009 mLastMemUsageReportTime = now;
2010 }
2011 Thread thread = new Thread() {
2012 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002013 StringBuilder dropBuilder = new StringBuilder(1024);
2014 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08002015 StringWriter oomSw = new StringWriter();
2016 PrintWriter oomPw = new PrintWriter(oomSw);
2017 StringWriter catSw = new StringWriter();
2018 PrintWriter catPw = new PrintWriter(catSw);
2019 String[] emptyArgs = new String[] { };
2020 StringBuilder tag = new StringBuilder(128);
2021 StringBuilder stack = new StringBuilder(128);
2022 tag.append("Low on memory -- ");
2023 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
2024 tag, stack);
2025 dropBuilder.append(stack);
2026 dropBuilder.append('\n');
2027 dropBuilder.append('\n');
2028 String oomString = oomSw.toString();
2029 dropBuilder.append(oomString);
2030 dropBuilder.append('\n');
2031 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002032 try {
2033 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
2034 "procrank", });
2035 final InputStreamReader converter = new InputStreamReader(
2036 proc.getInputStream());
2037 BufferedReader in = new BufferedReader(converter);
2038 String line;
2039 while (true) {
2040 line = in.readLine();
2041 if (line == null) {
2042 break;
2043 }
2044 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002045 logBuilder.append(line);
2046 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002047 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002048 dropBuilder.append(line);
2049 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002050 }
2051 converter.close();
2052 } catch (IOException e) {
2053 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002054 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08002055 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002056 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002057 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002058 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002059 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002060 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08002061 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002062 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08002063 addErrorToDropBox("lowmem", null, "system_server", null,
2064 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08002065 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002066 synchronized (ActivityManagerService.this) {
2067 long now = SystemClock.uptimeMillis();
2068 if (mLastMemUsageReportTime < now) {
2069 mLastMemUsageReportTime = now;
2070 }
2071 }
2072 }
2073 };
2074 thread.start();
2075 break;
2076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 }
2078 }
2079 };
2080
2081 public static void setSystemProcess() {
2082 try {
2083 ActivityManagerService m = mSelf;
2084
2085 ServiceManager.addService("activity", m);
2086 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07002087 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08002088 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 if (MONITOR_CPU_USAGE) {
2090 ServiceManager.addService("cpuinfo", new CpuBinder(m));
2091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 ServiceManager.addService("permission", new PermissionController(m));
2093
2094 ApplicationInfo info =
2095 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07002096 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07002097 mSystemThread.installSystemApplicationInfo(info);
2098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 synchronized (mSelf) {
2100 ProcessRecord app = mSelf.newProcessRecordLocked(
2101 mSystemThread.getApplicationThread(), info,
2102 info.processName);
2103 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08002104 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07002105 app.maxAdj = ProcessList.SYSTEM_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 mSelf.mProcessNames.put(app.processName, app.info.uid, app);
2107 synchronized (mSelf.mPidsSelfLocked) {
2108 mSelf.mPidsSelfLocked.put(app.pid, app);
2109 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002110 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 }
2112 } catch (PackageManager.NameNotFoundException e) {
2113 throw new RuntimeException(
2114 "Unable to find android system package", e);
2115 }
2116 }
2117
2118 public void setWindowManager(WindowManagerService wm) {
2119 mWindowManager = wm;
2120 }
2121
2122 public static final Context main(int factoryTest) {
2123 AThread thr = new AThread();
2124 thr.start();
2125
2126 synchronized (thr) {
2127 while (thr.mService == null) {
2128 try {
2129 thr.wait();
2130 } catch (InterruptedException e) {
2131 }
2132 }
2133 }
2134
2135 ActivityManagerService m = thr.mService;
2136 mSelf = m;
2137 ActivityThread at = ActivityThread.systemMain();
2138 mSystemThread = at;
2139 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08002140 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 m.mContext = context;
2142 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002143 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144
2145 m.mBatteryStatsService.publish(context);
2146 m.mUsageStatsService.publish(context);
2147
2148 synchronized (thr) {
2149 thr.mReady = true;
2150 thr.notifyAll();
2151 }
2152
2153 m.startRunning(null, null, null, null);
2154
2155 return context;
2156 }
2157
2158 public static ActivityManagerService self() {
2159 return mSelf;
2160 }
2161
2162 static class AThread extends Thread {
2163 ActivityManagerService mService;
2164 boolean mReady = false;
2165
2166 public AThread() {
2167 super("ActivityManager");
2168 }
2169
2170 public void run() {
2171 Looper.prepare();
2172
2173 android.os.Process.setThreadPriority(
2174 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07002175 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176
2177 ActivityManagerService m = new ActivityManagerService();
2178
2179 synchronized (this) {
2180 mService = m;
2181 notifyAll();
2182 }
2183
2184 synchronized (this) {
2185 while (!mReady) {
2186 try {
2187 wait();
2188 } catch (InterruptedException e) {
2189 }
2190 }
2191 }
2192
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07002193 // For debug builds, log event loop stalls to dropbox for analysis.
2194 if (StrictMode.conditionallyEnableDebugLogging()) {
2195 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
2196 }
2197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 Looper.loop();
2199 }
2200 }
2201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 static class MemBinder extends Binder {
2203 ActivityManagerService mActivityManagerService;
2204 MemBinder(ActivityManagerService activityManagerService) {
2205 mActivityManagerService = activityManagerService;
2206 }
2207
2208 @Override
2209 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002210 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2211 != PackageManager.PERMISSION_GRANTED) {
2212 pw.println("Permission Denial: can't dump meminfo from from pid="
2213 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2214 + " without permission " + android.Manifest.permission.DUMP);
2215 return;
2216 }
2217
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08002218 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08002219 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 }
2221 }
2222
Chet Haase9c1e23b2011-03-24 10:51:31 -07002223 static class GraphicsBinder extends Binder {
2224 ActivityManagerService mActivityManagerService;
2225 GraphicsBinder(ActivityManagerService activityManagerService) {
2226 mActivityManagerService = activityManagerService;
2227 }
2228
2229 @Override
2230 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002231 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2232 != PackageManager.PERMISSION_GRANTED) {
2233 pw.println("Permission Denial: can't dump gfxinfo from from pid="
2234 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2235 + " without permission " + android.Manifest.permission.DUMP);
2236 return;
2237 }
2238
Dianne Hackborne17aeb32011-04-07 15:11:57 -07002239 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07002240 }
2241 }
2242
Jeff Brown6754ba22011-12-14 20:20:01 -08002243 static class DbBinder extends Binder {
2244 ActivityManagerService mActivityManagerService;
2245 DbBinder(ActivityManagerService activityManagerService) {
2246 mActivityManagerService = activityManagerService;
2247 }
2248
2249 @Override
2250 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2251 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2252 != PackageManager.PERMISSION_GRANTED) {
2253 pw.println("Permission Denial: can't dump dbinfo from from pid="
2254 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2255 + " without permission " + android.Manifest.permission.DUMP);
2256 return;
2257 }
2258
2259 mActivityManagerService.dumpDbInfo(fd, pw, args);
2260 }
2261 }
2262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 static class CpuBinder extends Binder {
2264 ActivityManagerService mActivityManagerService;
2265 CpuBinder(ActivityManagerService activityManagerService) {
2266 mActivityManagerService = activityManagerService;
2267 }
2268
2269 @Override
2270 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002271 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2272 != PackageManager.PERMISSION_GRANTED) {
2273 pw.println("Permission Denial: can't dump cpuinfo from from pid="
2274 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2275 + " without permission " + android.Manifest.permission.DUMP);
2276 return;
2277 }
2278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002280 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
2281 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
2282 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 }
2284 }
2285 }
2286
2287 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002288 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07002289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 File dataDir = Environment.getDataDirectory();
2291 File systemDir = new File(dataDir, "system");
2292 systemDir.mkdirs();
2293 mBatteryStatsService = new BatteryStatsService(new File(
2294 systemDir, "batterystats.bin").toString());
2295 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07002296 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07002297 mOnBattery = DEBUG_POWER ? true
2298 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002299 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002300
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002301 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07002302 systemDir, "usagestats").toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303
Jack Palevichb90d28c2009-07-22 15:35:24 -07002304 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
2305 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
2306
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002307 mConfiguration.setToDefaults();
2308 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08002309 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 mProcessStats.init();
2311
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002312 mCompatModePackages = new CompatModePackages(this, systemDir);
2313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 // Add ourself to the Watchdog monitors.
2315 Watchdog.getInstance().addMonitor(this);
2316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 mProcessStatsThread = new Thread("ProcessStats") {
2318 public void run() {
2319 while (true) {
2320 try {
2321 try {
2322 synchronized(this) {
2323 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002324 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002326 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 // + ", write delay=" + nextWriteDelay);
2328 if (nextWriteDelay < nextCpuDelay) {
2329 nextCpuDelay = nextWriteDelay;
2330 }
2331 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002332 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 this.wait(nextCpuDelay);
2334 }
2335 }
2336 } catch (InterruptedException e) {
2337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 updateCpuStatsNow();
2339 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002340 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 }
2342 }
2343 }
2344 };
2345 mProcessStatsThread.start();
2346 }
2347
2348 @Override
2349 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2350 throws RemoteException {
2351 try {
2352 return super.onTransact(code, data, reply, flags);
2353 } catch (RuntimeException e) {
2354 // The activity manager only throws security exceptions, so let's
2355 // log all others.
2356 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002357 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 }
2359 throw e;
2360 }
2361 }
2362
2363 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002364 final long now = SystemClock.uptimeMillis();
2365 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
2366 return;
2367 }
2368 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
2369 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 mProcessStatsThread.notify();
2371 }
2372 }
2373 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 void updateCpuStatsNow() {
2376 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002377 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 final long now = SystemClock.uptimeMillis();
2379 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07002380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07002382 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
2383 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 haveNewCpuStats = true;
2385 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002386 //Slog.i(TAG, mProcessStats.printCurrentState());
2387 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 // + mProcessStats.getTotalCpuPercent() + "%");
2389
Joe Onorato8a9b2202010-02-26 18:56:32 -08002390 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 if ("true".equals(SystemProperties.get("events.cpu"))) {
2392 int user = mProcessStats.getLastUserTime();
2393 int system = mProcessStats.getLastSystemTime();
2394 int iowait = mProcessStats.getLastIoWaitTime();
2395 int irq = mProcessStats.getLastIrqTime();
2396 int softIrq = mProcessStats.getLastSoftIrqTime();
2397 int idle = mProcessStats.getLastIdleTime();
2398
2399 int total = user + system + iowait + irq + softIrq + idle;
2400 if (total == 0) total = 1;
2401
Doug Zongker2bec3d42009-12-04 12:52:44 -08002402 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 ((user+system+iowait+irq+softIrq) * 100) / total,
2404 (user * 100) / total,
2405 (system * 100) / total,
2406 (iowait * 100) / total,
2407 (irq * 100) / total,
2408 (softIrq * 100) / total);
2409 }
2410 }
2411
Amith Yamasanie43530a2009-08-21 13:11:37 -07002412 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07002413 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002414 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 synchronized(mPidsSelfLocked) {
2416 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002417 if (mOnBattery) {
2418 int perc = bstats.startAddingCpuLocked();
2419 int totalUTime = 0;
2420 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07002421 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07002423 ProcessStats.Stats st = mProcessStats.getStats(i);
2424 if (!st.working) {
2425 continue;
2426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002428 int otherUTime = (st.rel_utime*perc)/100;
2429 int otherSTime = (st.rel_stime*perc)/100;
2430 totalUTime += otherUTime;
2431 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 if (pr != null) {
2433 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002434 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
2435 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07002436 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07002437 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002438 } else {
2439 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07002440 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002441 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002442 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
2443 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07002444 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 }
2447 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002448 bstats.finishAddingCpuLocked(perc, totalUTime,
2449 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 }
2451 }
2452 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
2455 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07002456 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 }
2458 }
2459 }
2460 }
2461
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002462 @Override
2463 public void batteryNeedsCpuUpdate() {
2464 updateCpuStatsNow();
2465 }
2466
2467 @Override
2468 public void batteryPowerChanged(boolean onBattery) {
2469 // When plugging in, update the CPU stats first before changing
2470 // the plug state.
2471 updateCpuStatsNow();
2472 synchronized (this) {
2473 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07002474 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002475 }
2476 }
2477 }
2478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 /**
2480 * Initialize the application bind args. These are passed to each
2481 * process when the bindApplication() IPC is sent to the process. They're
2482 * lazily setup to make sure the services are running when they're asked for.
2483 */
2484 private HashMap<String, IBinder> getCommonServicesLocked() {
2485 if (mAppBindArgs == null) {
2486 mAppBindArgs = new HashMap<String, IBinder>();
2487
2488 // Setup the application init args
2489 mAppBindArgs.put("package", ServiceManager.getService("package"));
2490 mAppBindArgs.put("window", ServiceManager.getService("window"));
2491 mAppBindArgs.put(Context.ALARM_SERVICE,
2492 ServiceManager.getService(Context.ALARM_SERVICE));
2493 }
2494 return mAppBindArgs;
2495 }
2496
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002497 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 if (mFocusedActivity != r) {
2499 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08002500 if (r != null) {
2501 mWindowManager.setFocusedApp(r.appToken, true);
2502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 }
2504 }
2505
Dianne Hackborn906497c2010-05-10 15:57:38 -07002506 private final void updateLruProcessInternalLocked(ProcessRecord app,
2507 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002509 int lrui = mLruProcesses.indexOf(app);
2510 if (lrui >= 0) mLruProcesses.remove(lrui);
2511
2512 int i = mLruProcesses.size()-1;
2513 int skipTop = 0;
2514
Dianne Hackborn906497c2010-05-10 15:57:38 -07002515 app.lruSeq = mLruSeq;
2516
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002517 // compute the new weight for this process.
2518 if (updateActivityTime) {
2519 app.lastActivityTime = SystemClock.uptimeMillis();
2520 }
2521 if (app.activities.size() > 0) {
2522 // If this process has activities, we more strongly want to keep
2523 // it around.
2524 app.lruWeight = app.lastActivityTime;
2525 } else if (app.pubProviders.size() > 0) {
2526 // If this process contains content providers, we want to keep
2527 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002528 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002529 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002530 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002531 } else {
2532 // If this process doesn't have activities, we less strongly
2533 // want to keep it around, and generally want to avoid getting
2534 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002535 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_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 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07002539
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002540 while (i >= 0) {
2541 ProcessRecord p = mLruProcesses.get(i);
2542 // If this app shouldn't be in front of the first N background
2543 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002544 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002545 skipTop--;
2546 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07002547 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002548 mLruProcesses.add(i+1, app);
2549 break;
2550 }
2551 i--;
2552 }
2553 if (i < 0) {
2554 mLruProcesses.add(0, app);
2555 }
2556
Dianne Hackborn906497c2010-05-10 15:57:38 -07002557 // If the app is currently using a content provider or service,
2558 // bump those processes as well.
2559 if (app.connections.size() > 0) {
2560 for (ConnectionRecord cr : app.connections) {
2561 if (cr.binding != null && cr.binding.service != null
2562 && cr.binding.service.app != null
2563 && cr.binding.service.app.lruSeq != mLruSeq) {
2564 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
2565 updateActivityTime, i+1);
2566 }
2567 }
2568 }
2569 if (app.conProviders.size() > 0) {
2570 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07002571 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
2572 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07002573 updateActivityTime, i+1);
2574 }
2575 }
2576 }
2577
Joe Onorato8a9b2202010-02-26 18:56:32 -08002578 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 if (oomAdj) {
2580 updateOomAdjLocked();
2581 }
2582 }
2583
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002584 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07002585 boolean oomAdj, boolean updateActivityTime) {
2586 mLruSeq++;
2587 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
2588 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002589
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002590 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 String processName, int uid) {
2592 if (uid == Process.SYSTEM_UID) {
2593 // The system gets to run in any process. If there are multiple
2594 // processes with the same uid, just pick the first (this
2595 // should never happen).
2596 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
2597 processName);
2598 return procs != null ? procs.valueAt(0) : null;
2599 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002600 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 ProcessRecord proc = mProcessNames.get(processName, uid);
2602 return proc;
2603 }
2604
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002605 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002606 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002607 try {
2608 if (pm.performDexOpt(packageName)) {
2609 mDidDexOpt = true;
2610 }
2611 } catch (RemoteException e) {
2612 }
2613 }
2614
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002615 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 int transit = mWindowManager.getPendingAppTransition();
2617 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
2618 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
2619 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
2620 }
2621
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002622 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002624 String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 ProcessRecord app = getProcessRecordLocked(processName, info.uid);
2626 // We don't have to do anything more if:
2627 // (1) There is an existing application record; and
2628 // (2) The caller doesn't think it is dead, OR there is no thread
2629 // object attached to it so we know it couldn't have crashed; and
2630 // (3) There is a pid assigned to it, so it is either starting or
2631 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002632 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 + " app=" + app + " knownToBeDead=" + knownToBeDead
2634 + " thread=" + (app != null ? app.thread : null)
2635 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01002636 if (app != null && app.pid > 0) {
2637 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002638 // We already have the app running, or are waiting for it to
2639 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002640 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002641 // If this is a new package in the process, add the package to the list
2642 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002643 return app;
2644 } else {
2645 // An application record is attached to a previous process,
2646 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002647 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002648 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 String hostingNameStr = hostingName != null
2653 ? hostingName.flattenToShortString() : null;
2654
2655 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2656 // If we are in the background, then check to see if this process
2657 // is bad. If so, we will just silently fail.
2658 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002659 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2660 + "/" + info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 return null;
2662 }
2663 } else {
2664 // When the user is explicitly starting a process, then clear its
2665 // crash count so that we won't make it bad until they see at
2666 // least one crash dialog again, and make the process good again
2667 // if it had been bad.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002668 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
2669 + "/" + info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 mProcessCrashTimes.remove(info.processName, info.uid);
2671 if (mBadProcesses.get(info.processName, info.uid) != null) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08002672 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 info.processName);
2674 mBadProcesses.remove(info.processName, info.uid);
2675 if (app != null) {
2676 app.bad = false;
2677 }
2678 }
2679 }
2680
2681 if (app == null) {
2682 app = newProcessRecordLocked(null, info, processName);
2683 mProcessNames.put(processName, info.uid, app);
2684 } else {
2685 // If this is a new package in the process, add the package to the list
2686 app.addPackage(info.packageName);
2687 }
2688
2689 // If the system is not ready yet, then hold off on starting this
2690 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002691 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002692 && !isAllowedWhileBooting(info)
2693 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 if (!mProcessesOnHold.contains(app)) {
2695 mProcessesOnHold.add(app);
2696 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002697 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 return app;
2699 }
2700
2701 startProcessLocked(app, hostingType, hostingNameStr);
2702 return (app.pid != 0) ? app : null;
2703 }
2704
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002705 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2706 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2707 }
2708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 private final void startProcessLocked(ProcessRecord app,
2710 String hostingType, String hostingNameStr) {
2711 if (app.pid > 0 && app.pid != MY_PID) {
2712 synchronized (mPidsSelfLocked) {
2713 mPidsSelfLocked.remove(app.pid);
2714 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2715 }
2716 app.pid = 0;
2717 }
2718
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002719 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2720 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 mProcessesOnHold.remove(app);
2722
2723 updateCpuStats();
2724
2725 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2726 mProcDeaths[0] = 0;
2727
2728 try {
2729 int uid = app.info.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 int[] gids = null;
2732 try {
2733 gids = mContext.getPackageManager().getPackageGids(
2734 app.info.packageName);
2735 } catch (PackageManager.NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002736 Slog.w(TAG, "Unable to retrieve gids", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 }
2738 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2739 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2740 && mTopComponent != null
2741 && app.processName.equals(mTopComponent.getPackageName())) {
2742 uid = 0;
2743 }
2744 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2745 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2746 uid = 0;
2747 }
2748 }
2749 int debugFlags = 0;
2750 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2751 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002752 // Also turn on CheckJNI for debuggable apps. It's quite
2753 // awkward to turn on otherwise.
2754 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002756 // Run the app in safe mode if its manifest requests so or the
2757 // system is booted in safe mode.
2758 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2759 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002760 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2763 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2764 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002765 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2766 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 if ("1".equals(SystemProperties.get("debug.assert"))) {
2769 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2770 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002771
2772 // Start the process. It will either succeed and return a result containing
2773 // the PID of the new process, or else throw a RuntimeException.
2774 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002775 app.processName, uid, uid, gids, debugFlags,
2776 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2779 synchronized (bs) {
2780 if (bs.isOnBattery()) {
2781 app.batteryStats.incStartsLocked();
2782 }
2783 }
2784
Jeff Brown3f9dd282011-07-08 20:02:19 -07002785 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 app.processName, hostingType,
2787 hostingNameStr != null ? hostingNameStr : "");
2788
2789 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002790 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 }
2792
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002793 StringBuilder buf = mStringBuilder;
2794 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 buf.append("Start proc ");
2796 buf.append(app.processName);
2797 buf.append(" for ");
2798 buf.append(hostingType);
2799 if (hostingNameStr != null) {
2800 buf.append(" ");
2801 buf.append(hostingNameStr);
2802 }
2803 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002804 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 buf.append(" uid=");
2806 buf.append(uid);
2807 buf.append(" gids={");
2808 if (gids != null) {
2809 for (int gi=0; gi<gids.length; gi++) {
2810 if (gi != 0) buf.append(", ");
2811 buf.append(gids[gi]);
2812
2813 }
2814 }
2815 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002816 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002817 app.pid = startResult.pid;
2818 app.usingWrapper = startResult.usingWrapper;
2819 app.removed = false;
2820 synchronized (mPidsSelfLocked) {
2821 this.mPidsSelfLocked.put(startResult.pid, app);
2822 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2823 msg.obj = app;
2824 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2825 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 }
2827 } catch (RuntimeException e) {
2828 // XXX do better error recovery.
2829 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002830 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 }
2832 }
2833
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002834 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 if (resumed) {
2836 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2837 } else {
2838 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2839 }
2840 }
2841
Amith Yamasani742a6712011-05-04 14:49:28 -07002842 boolean startHomeActivityLocked(int userId) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002843 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2844 && mTopAction == null) {
2845 // We are running in factory test mode, but unable to find
2846 // the factory test app, so just sit around displaying the
2847 // error message and don't try to start anything.
2848 return false;
2849 }
2850 Intent intent = new Intent(
2851 mTopAction,
2852 mTopData != null ? Uri.parse(mTopData) : null);
2853 intent.setComponent(mTopComponent);
2854 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2855 intent.addCategory(Intent.CATEGORY_HOME);
2856 }
2857 ActivityInfo aInfo =
2858 intent.resolveActivityInfo(mContext.getPackageManager(),
2859 STOCK_PM_FLAGS);
2860 if (aInfo != null) {
2861 intent.setComponent(new ComponentName(
2862 aInfo.applicationInfo.packageName, aInfo.name));
2863 // Don't do this if the home app is currently being
2864 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002865 aInfo = new ActivityInfo(aInfo);
2866 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002867 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2868 aInfo.applicationInfo.uid);
2869 if (app == null || app.instrumentationClass == null) {
2870 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002871 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002872 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002873 }
2874 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002875
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002876 return true;
2877 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002878
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002879 /**
2880 * Starts the "new version setup screen" if appropriate.
2881 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002882 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002883 // Only do this once per boot.
2884 if (mCheckedForSetup) {
2885 return;
2886 }
2887
2888 // We will show this screen if the current one is a different
2889 // version than the last one shown, and we are not running in
2890 // low-level factory test mode.
2891 final ContentResolver resolver = mContext.getContentResolver();
2892 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2893 Settings.Secure.getInt(resolver,
2894 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2895 mCheckedForSetup = true;
2896
2897 // See if we should be showing the platform update setup UI.
2898 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2899 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2900 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2901
2902 // We don't allow third party apps to replace this.
2903 ResolveInfo ri = null;
2904 for (int i=0; ris != null && i<ris.size(); i++) {
2905 if ((ris.get(i).activityInfo.applicationInfo.flags
2906 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2907 ri = ris.get(i);
2908 break;
2909 }
2910 }
2911
2912 if (ri != null) {
2913 String vers = ri.activityInfo.metaData != null
2914 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2915 : null;
2916 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2917 vers = ri.activityInfo.applicationInfo.metaData.getString(
2918 Intent.METADATA_SETUP_VERSION);
2919 }
2920 String lastVers = Settings.Secure.getString(
2921 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2922 if (vers != null && !vers.equals(lastVers)) {
2923 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2924 intent.setComponent(new ComponentName(
2925 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002926 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002927 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002928 }
2929 }
2930 }
2931 }
2932
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002933 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002934 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002935 }
2936
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002937 public int getFrontActivityScreenCompatMode() {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002938 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002939 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2940 }
2941 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002942
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002943 public void setFrontActivityScreenCompatMode(int mode) {
2944 synchronized (this) {
2945 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2946 }
2947 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002948
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002949 public int getPackageScreenCompatMode(String packageName) {
2950 synchronized (this) {
2951 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2952 }
2953 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002954
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002955 public void setPackageScreenCompatMode(String packageName, int mode) {
2956 synchronized (this) {
2957 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002958 }
2959 }
2960
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002961 public boolean getPackageAskScreenCompat(String packageName) {
2962 synchronized (this) {
2963 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2964 }
2965 }
2966
2967 public void setPackageAskScreenCompat(String packageName, boolean ask) {
2968 synchronized (this) {
2969 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2970 }
2971 }
2972
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002973 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002974 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002975
2976 final int identHash = System.identityHashCode(r);
2977 updateUsageStats(r, true);
2978
2979 int i = mWatchers.beginBroadcast();
2980 while (i > 0) {
2981 i--;
2982 IActivityWatcher w = mWatchers.getBroadcastItem(i);
2983 if (w != null) {
2984 try {
2985 w.activityResuming(identHash);
2986 } catch (RemoteException e) {
2987 }
2988 }
2989 }
2990 mWatchers.finishBroadcast();
2991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992
Jeff Sharkeya4620792011-05-20 15:29:23 -07002993 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2994 int i = mProcessObservers.beginBroadcast();
2995 while (i > 0) {
2996 i--;
2997 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2998 if (observer != null) {
2999 try {
3000 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
3001 } catch (RemoteException e) {
3002 }
3003 }
3004 }
3005 mProcessObservers.finishBroadcast();
3006 }
3007
3008 private void dispatchProcessDied(int pid, int uid) {
3009 int i = mProcessObservers.beginBroadcast();
3010 while (i > 0) {
3011 i--;
3012 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3013 if (observer != null) {
3014 try {
3015 observer.onProcessDied(pid, uid);
3016 } catch (RemoteException e) {
3017 }
3018 }
3019 }
3020 mProcessObservers.finishBroadcast();
3021 }
3022
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003023 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003024 final int N = mPendingActivityLaunches.size();
3025 if (N <= 0) {
3026 return;
3027 }
3028 for (int i=0; i<N; i++) {
3029 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003030 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003031 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
3032 doResume && i == (N-1));
3033 }
3034 mPendingActivityLaunches.clear();
3035 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003036
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003037 public final int startActivity(IApplicationThread caller,
3038 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3039 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003040 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
3041 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Amith Yamasani742a6712011-05-04 14:49:28 -07003042 int userId = 0;
3043 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
3044 // Requesting home, set the identity to the current user
3045 // HACK!
3046 userId = mCurrentUserId;
3047 } else {
3048 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
3049 // the current user's userId
3050 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
3051 userId = 0;
3052 } else {
3053 userId = Binder.getOrigCallingUser();
3054 }
3055 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003056 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -07003057 grantedUriPermissions, grantedMode, resultTo, resultWho, requestCode, onlyIfNeeded,
3058 debug, profileFile, profileFd, autoStopProfiler, null, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003059 }
3060
3061 public final WaitResult startActivityAndWait(IApplicationThread caller,
3062 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3063 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003064 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
3065 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003066 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07003067 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003068 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003069 grantedUriPermissions, grantedMode, resultTo, resultWho,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003070 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
Amith Yamasani742a6712011-05-04 14:49:28 -07003071 res, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003072 return res;
3073 }
3074
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003075 public final int startActivityWithConfig(IApplicationThread caller,
3076 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3077 int grantedMode, IBinder resultTo,
3078 String resultWho, int requestCode, boolean onlyIfNeeded,
3079 boolean debug, Configuration config) {
Amith Yamasani742a6712011-05-04 14:49:28 -07003080 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003081 grantedUriPermissions, grantedMode, resultTo, resultWho,
Amith Yamasani742a6712011-05-04 14:49:28 -07003082 requestCode, onlyIfNeeded,
3083 debug, null, null, false, null, config, Binder.getOrigCallingUser());
3084 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003085 }
3086
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003087 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003088 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003089 IBinder resultTo, String resultWho, int requestCode,
3090 int flagsMask, int flagsValues) {
3091 // Refuse possible leaked file descriptors
3092 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
3093 throw new IllegalArgumentException("File descriptors passed in Intent");
3094 }
3095
3096 IIntentSender sender = intent.getTarget();
3097 if (!(sender instanceof PendingIntentRecord)) {
3098 throw new IllegalArgumentException("Bad PendingIntent object");
3099 }
3100
3101 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003102
3103 synchronized (this) {
3104 // If this is coming from the currently resumed activity, it is
3105 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003106 if (mMainStack.mResumedActivity != null
3107 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003108 Binder.getCallingUid()) {
3109 mAppSwitchesAllowedTime = 0;
3110 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003111 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003112 int ret = pir.sendInner(0, fillInIntent, resolvedType, null,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003113 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
Amith Yamasani742a6712011-05-04 14:49:28 -07003114 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003115 }
3116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 public boolean startNextMatchingActivity(IBinder callingActivity,
3118 Intent intent) {
3119 // Refuse possible leaked file descriptors
3120 if (intent != null && intent.hasFileDescriptors() == true) {
3121 throw new IllegalArgumentException("File descriptors passed in Intent");
3122 }
3123
3124 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003125 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
3126 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 return false;
3128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 if (r.app == null || r.app.thread == null) {
3130 // The caller is not running... d'oh!
3131 return false;
3132 }
3133 intent = new Intent(intent);
3134 // The caller is not allowed to change the data.
3135 intent.setDataAndType(r.intent.getData(), r.intent.getType());
3136 // And we are resetting to find the next component...
3137 intent.setComponent(null);
3138
3139 ActivityInfo aInfo = null;
3140 try {
3141 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003142 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07003144 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145
3146 // Look for the original activity in the list...
3147 final int N = resolves != null ? resolves.size() : 0;
3148 for (int i=0; i<N; i++) {
3149 ResolveInfo rInfo = resolves.get(i);
3150 if (rInfo.activityInfo.packageName.equals(r.packageName)
3151 && rInfo.activityInfo.name.equals(r.info.name)) {
3152 // We found the current one... the next matching is
3153 // after it.
3154 i++;
3155 if (i<N) {
3156 aInfo = resolves.get(i).activityInfo;
3157 }
3158 break;
3159 }
3160 }
3161 } catch (RemoteException e) {
3162 }
3163
3164 if (aInfo == null) {
3165 // Nobody who is next!
3166 return false;
3167 }
3168
3169 intent.setComponent(new ComponentName(
3170 aInfo.applicationInfo.packageName, aInfo.name));
3171 intent.setFlags(intent.getFlags()&~(
3172 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
3173 Intent.FLAG_ACTIVITY_CLEAR_TOP|
3174 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
3175 Intent.FLAG_ACTIVITY_NEW_TASK));
3176
3177 // Okay now we need to start the new activity, replacing the
3178 // currently running activity. This is a little tricky because
3179 // we want to start the new one as if the current one is finished,
3180 // but not finish the current one first so that there is no flicker.
3181 // And thus...
3182 final boolean wasFinishing = r.finishing;
3183 r.finishing = true;
3184
3185 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003186 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 final String resultWho = r.resultWho;
3188 final int requestCode = r.requestCode;
3189 r.resultTo = null;
3190 if (resultTo != null) {
3191 resultTo.removeResultsLocked(r, resultWho, requestCode);
3192 }
3193
3194 final long origId = Binder.clearCallingIdentity();
3195 // XXX we are not dealing with propagating grantedUriPermissions...
3196 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003197 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackbornbe707852011-11-11 14:32:10 -08003198 r.resolvedType, null, 0, aInfo,
3199 resultTo != null ? resultTo.appToken : null, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003200 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 Binder.restoreCallingIdentity(origId);
3202
3203 r.finishing = wasFinishing;
3204 if (res != START_SUCCESS) {
3205 return false;
3206 }
3207 return true;
3208 }
3209 }
3210
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003211 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 Intent intent, String resolvedType, IBinder resultTo,
3213 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003214
3215 // This is so super not safe, that only the system (or okay root)
3216 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07003217 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003218 final int callingUid = Binder.getCallingUid();
3219 if (callingUid != 0 && callingUid != Process.myUid()) {
3220 throw new SecurityException(
3221 "startActivityInPackage only available to the system");
3222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223
Amith Yamasani742a6712011-05-04 14:49:28 -07003224 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003225 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false,
Amith Yamasani742a6712011-05-04 14:49:28 -07003226 null, null, false, null, null, userId);
3227 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003228 }
3229
3230 public final int startActivities(IApplicationThread caller,
3231 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
Amith Yamasani742a6712011-05-04 14:49:28 -07003232 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
3233 Binder.getOrigCallingUser());
3234 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003235 }
3236
3237 public final int startActivitiesInPackage(int uid,
3238 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
3239
3240 // This is so super not safe, that only the system (or okay root)
3241 // can do it.
3242 final int callingUid = Binder.getCallingUid();
3243 if (callingUid != 0 && callingUid != Process.myUid()) {
3244 throw new SecurityException(
3245 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003247 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
3248 UserId.getUserId(uid));
3249 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 }
3251
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003252 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08003254 // Quick case: check if the top-most recent task is the same.
3255 if (N > 0 && mRecentTasks.get(0) == task) {
3256 return;
3257 }
3258 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 for (int i=0; i<N; i++) {
3260 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07003261 if (task.userId == tr.userId
3262 && ((task.affinity != null && task.affinity.equals(tr.affinity))
3263 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 mRecentTasks.remove(i);
3265 i--;
3266 N--;
3267 if (task.intent == null) {
3268 // If the new recent task we are adding is not fully
3269 // specified, then replace it with the existing recent task.
3270 task = tr;
3271 }
3272 }
3273 }
3274 if (N >= MAX_RECENT_TASKS) {
3275 mRecentTasks.remove(N-1);
3276 }
3277 mRecentTasks.add(0, task);
3278 }
3279
3280 public void setRequestedOrientation(IBinder token,
3281 int requestedOrientation) {
3282 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003283 ActivityRecord r = mMainStack.isInStackLocked(token);
3284 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 return;
3286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08003288 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07003290 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08003291 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 if (config != null) {
3293 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08003294 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003295 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 }
3297 }
3298 Binder.restoreCallingIdentity(origId);
3299 }
3300 }
3301
3302 public int getRequestedOrientation(IBinder token) {
3303 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003304 ActivityRecord r = mMainStack.isInStackLocked(token);
3305 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3307 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003308 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 }
3310 }
3311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 /**
3313 * This is the internal entry point for handling Activity.finish().
3314 *
3315 * @param token The Binder token referencing the Activity we want to finish.
3316 * @param resultCode Result code, if any, from this Activity.
3317 * @param resultData Result data (Intent), if any, from this Activity.
3318 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11003319 * @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 -08003320 */
3321 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
3322 // Refuse possible leaked file descriptors
3323 if (resultData != null && resultData.hasFileDescriptors() == true) {
3324 throw new IllegalArgumentException("File descriptors passed in Intent");
3325 }
3326
3327 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003328 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003330 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 if (next != null) {
3332 // ask watcher if this is allowed
3333 boolean resumeOK = true;
3334 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003335 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003337 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 }
3339
3340 if (!resumeOK) {
3341 return false;
3342 }
3343 }
3344 }
3345 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003346 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 resultData, "app-request");
3348 Binder.restoreCallingIdentity(origId);
3349 return res;
3350 }
3351 }
3352
Dianne Hackborn860755f2010-06-03 18:47:52 -07003353 public final void finishHeavyWeightApp() {
3354 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3355 != PackageManager.PERMISSION_GRANTED) {
3356 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
3357 + Binder.getCallingPid()
3358 + ", uid=" + Binder.getCallingUid()
3359 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3360 Slog.w(TAG, msg);
3361 throw new SecurityException(msg);
3362 }
3363
3364 synchronized(this) {
3365 if (mHeavyWeightProcess == null) {
3366 return;
3367 }
3368
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003369 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07003370 mHeavyWeightProcess.activities);
3371 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003372 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003373 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003374 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003375 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003376 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07003377 null, "finish-heavy");
3378 }
3379 }
3380 }
3381
3382 mHeavyWeightProcess = null;
3383 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3384 }
3385 }
3386
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003387 public void crashApplication(int uid, int initialPid, String packageName,
3388 String message) {
3389 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3390 != PackageManager.PERMISSION_GRANTED) {
3391 String msg = "Permission Denial: crashApplication() from pid="
3392 + Binder.getCallingPid()
3393 + ", uid=" + Binder.getCallingUid()
3394 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3395 Slog.w(TAG, msg);
3396 throw new SecurityException(msg);
3397 }
3398
3399 synchronized(this) {
3400 ProcessRecord proc = null;
3401
3402 // Figure out which process to kill. We don't trust that initialPid
3403 // still has any relation to current pids, so must scan through the
3404 // list.
3405 synchronized (mPidsSelfLocked) {
3406 for (int i=0; i<mPidsSelfLocked.size(); i++) {
3407 ProcessRecord p = mPidsSelfLocked.valueAt(i);
3408 if (p.info.uid != uid) {
3409 continue;
3410 }
3411 if (p.pid == initialPid) {
3412 proc = p;
3413 break;
3414 }
3415 for (String str : p.pkgList) {
3416 if (str.equals(packageName)) {
3417 proc = p;
3418 }
3419 }
3420 }
3421 }
3422
3423 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07003424 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003425 + " initialPid=" + initialPid
3426 + " packageName=" + packageName);
3427 return;
3428 }
3429
3430 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07003431 if (proc.pid == Process.myPid()) {
3432 Log.w(TAG, "crashApplication: trying to crash self!");
3433 return;
3434 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07003435 long ident = Binder.clearCallingIdentity();
3436 try {
3437 proc.thread.scheduleCrash(message);
3438 } catch (RemoteException e) {
3439 }
3440 Binder.restoreCallingIdentity(ident);
3441 }
3442 }
3443 }
3444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 public final void finishSubActivity(IBinder token, String resultWho,
3446 int requestCode) {
3447 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003448 ActivityRecord self = mMainStack.isInStackLocked(token);
3449 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 return;
3451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452
3453 final long origId = Binder.clearCallingIdentity();
3454
3455 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003456 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3457 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 if (r.resultTo == self && r.requestCode == requestCode) {
3459 if ((r.resultWho == null && resultWho == null) ||
3460 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003461 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 Activity.RESULT_CANCELED, null, "request-sub");
3463 }
3464 }
3465 }
3466
3467 Binder.restoreCallingIdentity(origId);
3468 }
3469 }
3470
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003471 public boolean willActivityBeVisible(IBinder token) {
3472 synchronized(this) {
3473 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003474 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3475 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003476 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003477 return true;
3478 }
3479 if (r.fullscreen && !r.finishing) {
3480 return false;
3481 }
3482 }
3483 return true;
3484 }
3485 }
3486
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003487 public void overridePendingTransition(IBinder token, String packageName,
3488 int enterAnim, int exitAnim) {
3489 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003490 ActivityRecord self = mMainStack.isInStackLocked(token);
3491 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003492 return;
3493 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003494
3495 final long origId = Binder.clearCallingIdentity();
3496
3497 if (self.state == ActivityState.RESUMED
3498 || self.state == ActivityState.PAUSING) {
3499 mWindowManager.overridePendingAppTransition(packageName,
3500 enterAnim, exitAnim);
3501 }
3502
3503 Binder.restoreCallingIdentity(origId);
3504 }
3505 }
3506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003508 * Main function for removing an existing process from the activity manager
3509 * as a result of that process going away. Clears out all connections
3510 * to the process.
3511 */
3512 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003513 boolean restarting, boolean allowRestart) {
3514 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003516 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 }
3518
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003519 if (mProfileProc == app) {
3520 clearProfilerLocked();
3521 }
3522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003523 // Just in case...
Dianne Hackborncbb722e2012-02-07 18:33:49 -08003524 mMainStack.appDiedLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525
3526 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003527 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528
3529 boolean atTop = true;
3530 boolean hasVisibleActivities = false;
3531
3532 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003533 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003534 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 TAG, "Removing app " + app + " from history with " + i + " entries");
3536 while (i > 0) {
3537 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003538 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003539 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3541 if (r.app == app) {
3542 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003543 if (ActivityStack.DEBUG_ADD_REMOVE) {
3544 RuntimeException here = new RuntimeException("here");
3545 here.fillInStackTrace();
3546 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
3547 + ": haveState=" + r.haveState
3548 + " stateNotNeeded=" + r.stateNotNeeded
3549 + " finishing=" + r.finishing
3550 + " state=" + r.state, here);
3551 }
3552 if (!r.finishing) {
3553 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08003554 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3555 System.identityHashCode(r),
3556 r.task.taskId, r.shortComponentName,
3557 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003558 }
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003559 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003560 mMainStack.mHistory.remove(i);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003561 r.takeFromHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08003562 mWindowManager.removeAppToken(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003564 mMainStack.validateAppTokensLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003565 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003566 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567
3568 } else {
3569 // We have the current state for this activity, so
3570 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003571 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003572 TAG, "Keeping entry, setting app to null");
3573 if (r.visible) {
3574 hasVisibleActivities = true;
3575 }
3576 r.app = null;
3577 r.nowVisible = false;
3578 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003579 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
3580 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 r.icicle = null;
3582 }
3583 }
3584
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003585 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 }
3587 atTop = false;
3588 }
3589
3590 app.activities.clear();
3591
3592 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003593 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 + " running instrumentation " + app.instrumentationClass);
3595 Bundle info = new Bundle();
3596 info.putString("shortMsg", "Process crashed.");
3597 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3598 }
3599
3600 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003601 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 // If there was nothing to resume, and we are not already
3603 // restarting this process, but there is a visible activity that
3604 // is hosted by the process... then make sure all visible
3605 // activities are running, taking care of restarting this
3606 // process.
3607 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003608 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 }
3610 }
3611 }
3612 }
3613
3614 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3615 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003617 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3618 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003619 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3620 return i;
3621 }
3622 }
3623 return -1;
3624 }
3625
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003626 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627 IApplicationThread thread) {
3628 if (thread == null) {
3629 return null;
3630 }
3631
3632 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003633 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 }
3635
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003636 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 IApplicationThread thread) {
3638
3639 mProcDeaths[0]++;
3640
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003641 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3642 synchronized (stats) {
3643 stats.noteProcessDiedLocked(app.info.uid, pid);
3644 }
3645
Magnus Edlund7bb25812010-02-24 15:45:06 +01003646 // Clean up already done if the process has been re-started.
3647 if (app.pid == pid && app.thread != null &&
3648 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003649 if (!app.killedBackground) {
3650 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3651 + ") has died.");
3652 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08003653 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003654 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 TAG, "Dying app: " + app + ", pid: " + pid
3656 + ", thread: " + thread.asBinder());
3657 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003658 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659
3660 if (doLowMem) {
3661 // If there are no longer any background processes running,
3662 // and the app that died was not running instrumentation,
3663 // then tell everyone we are now low on memory.
3664 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003665 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3666 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003667 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 haveBg = true;
3669 break;
3670 }
3671 }
3672
3673 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003674 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003675 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003676 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3677 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003678 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003679 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3680 // The low memory report is overriding any current
3681 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003682 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003683 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003684 rec.lastRequestedGc = 0;
3685 } else {
3686 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003688 rec.reportLowMemory = true;
3689 rec.lastLowMemory = now;
3690 mProcessesToGc.remove(rec);
3691 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 }
3693 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003694 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003695 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 }
3697 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003698 } else if (app.pid != pid) {
3699 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003700 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003701 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003702 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003703 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003704 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 + thread.asBinder());
3706 }
3707 }
3708
Dan Egnor42471dd2010-01-07 17:25:22 -08003709 /**
3710 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003711 * @param clearTraces causes the dump file to be erased prior to the new
3712 * traces being written, if true; when false, the new traces will be
3713 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003714 * @param firstPids of dalvik VM processes to dump stack traces for first
3715 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08003716 * @return file containing stack traces, or null if no dump file is configured
3717 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003718 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
3719 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003720 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3721 if (tracesPath == null || tracesPath.length() == 0) {
3722 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003724
3725 File tracesFile = new File(tracesPath);
3726 try {
3727 File tracesDir = tracesFile.getParentFile();
3728 if (!tracesDir.exists()) tracesFile.mkdirs();
3729 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3730
Christopher Tate6ee412d2010-05-28 12:01:56 -07003731 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003732 tracesFile.createNewFile();
3733 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3734 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003735 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003736 return null;
3737 }
3738
3739 // Use a FileObserver to detect when traces finish writing.
3740 // The order of traces is considered important to maintain for legibility.
3741 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3742 public synchronized void onEvent(int event, String path) { notify(); }
3743 };
3744
3745 try {
3746 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003747
3748 // First collect all of the stacks of the most important pids.
3749 try {
3750 int num = firstPids.size();
3751 for (int i = 0; i < num; i++) {
3752 synchronized (observer) {
3753 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3754 observer.wait(200); // Wait for write-close, give up after 200msec
3755 }
3756 }
3757 } catch (InterruptedException e) {
3758 Log.wtf(TAG, e);
3759 }
3760
3761 // Next measure CPU usage.
3762 if (processStats != null) {
3763 processStats.init();
3764 System.gc();
3765 processStats.update();
3766 try {
3767 synchronized (processStats) {
3768 processStats.wait(500); // measure over 1/2 second.
3769 }
3770 } catch (InterruptedException e) {
3771 }
3772 processStats.update();
3773
3774 // We'll take the stack crawls of just the top apps using CPU.
3775 final int N = processStats.countWorkingStats();
3776 int numProcs = 0;
3777 for (int i=0; i<N && numProcs<5; i++) {
3778 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3779 if (lastPids.indexOfKey(stats.pid) >= 0) {
3780 numProcs++;
3781 try {
3782 synchronized (observer) {
3783 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3784 observer.wait(200); // Wait for write-close, give up after 200msec
3785 }
3786 } catch (InterruptedException e) {
3787 Log.wtf(TAG, e);
3788 }
3789
3790 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003791 }
3792 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003793
3794 return tracesFile;
3795
Dan Egnor42471dd2010-01-07 17:25:22 -08003796 } finally {
3797 observer.stopWatching();
3798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 }
3800
Jeff Brown4d94a762010-09-23 11:33:28 -07003801 private final class AppNotResponding implements Runnable {
3802 private final ProcessRecord mApp;
3803 private final String mAnnotation;
3804
3805 public AppNotResponding(ProcessRecord app, String annotation) {
3806 mApp = app;
3807 mAnnotation = annotation;
3808 }
3809
3810 @Override
3811 public void run() {
3812 appNotResponding(mApp, null, null, mAnnotation);
3813 }
3814 }
3815
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003816 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3817 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003818 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3819 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3820
Dianne Hackborn287952c2010-09-22 22:34:31 -07003821 if (mController != null) {
3822 try {
3823 // 0 == continue, -1 = kill process immediately
3824 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3825 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3826 } catch (RemoteException e) {
3827 mController = null;
3828 }
3829 }
3830
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003831 long anrTime = SystemClock.uptimeMillis();
3832 if (MONITOR_CPU_USAGE) {
3833 updateCpuStatsNow();
3834 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003835
3836 synchronized (this) {
3837 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3838 if (mShuttingDown) {
3839 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3840 return;
3841 } else if (app.notResponding) {
3842 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3843 return;
3844 } else if (app.crashing) {
3845 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3846 return;
3847 }
3848
3849 // In case we come through here for the same app before completing
3850 // this one, mark as anring now so we will bail out.
3851 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003852
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003853 // Log the ANR to the event log.
3854 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3855 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003856
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003857 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003858 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003859
3860 int parentPid = app.pid;
3861 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003862 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003863
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003864 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003865
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003866 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3867 ProcessRecord r = mLruProcesses.get(i);
3868 if (r != null && r.thread != null) {
3869 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003870 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3871 if (r.persistent) {
3872 firstPids.add(pid);
3873 } else {
3874 lastPids.put(pid, Boolean.TRUE);
3875 }
3876 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 }
3879 }
3880
Dan Egnor42471dd2010-01-07 17:25:22 -08003881 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003882 StringBuilder info = mStringBuilder;
3883 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003884 info.append("ANR in ").append(app.processName);
3885 if (activity != null && activity.shortComponentName != null) {
3886 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003887 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003888 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003890 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003892 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003893 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895
Dianne Hackborn287952c2010-09-22 22:34:31 -07003896 final ProcessStats processStats = new ProcessStats(true);
3897
3898 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3899
Dan Egnor42471dd2010-01-07 17:25:22 -08003900 String cpuInfo = null;
3901 if (MONITOR_CPU_USAGE) {
3902 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003903 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003904 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003905 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003906 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003907 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003910 info.append(processStats.printCurrentState(anrTime));
3911
Joe Onorato8a9b2202010-02-26 18:56:32 -08003912 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003913 if (tracesFile == null) {
3914 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3915 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3916 }
3917
Jeff Sharkeya353d262011-10-28 11:12:06 -07003918 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3919 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003920
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003921 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003923 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3924 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003926 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3927 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 }
3929 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003930 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 }
3932 }
3933
Dan Egnor42471dd2010-01-07 17:25:22 -08003934 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3935 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3936 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003937
3938 synchronized (this) {
3939 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003940 Slog.w(TAG, "Killing " + app + ": background ANR");
3941 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3942 app.processName, app.setAdj, "background ANR");
3943 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003944 return;
3945 }
3946
3947 // Set the app's notResponding state, and look up the errorReportReceiver
3948 makeAppNotRespondingLocked(app,
3949 activity != null ? activity.shortComponentName : null,
3950 annotation != null ? "ANR " + annotation : "ANR",
3951 info.toString());
3952
3953 // Bring up the infamous App Not Responding dialog
3954 Message msg = Message.obtain();
3955 HashMap map = new HashMap();
3956 msg.what = SHOW_NOT_RESPONDING_MSG;
3957 msg.obj = map;
3958 map.put("app", app);
3959 if (activity != null) {
3960 map.put("activity", activity);
3961 }
3962
3963 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965 }
3966
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003967 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3968 if (!mLaunchWarningShown) {
3969 mLaunchWarningShown = true;
3970 mHandler.post(new Runnable() {
3971 @Override
3972 public void run() {
3973 synchronized (ActivityManagerService.this) {
3974 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3975 d.show();
3976 mHandler.postDelayed(new Runnable() {
3977 @Override
3978 public void run() {
3979 synchronized (ActivityManagerService.this) {
3980 d.dismiss();
3981 mLaunchWarningShown = false;
3982 }
3983 }
3984 }, 4000);
3985 }
3986 }
3987 });
3988 }
3989 }
3990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003992 final IPackageDataObserver observer, final int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 int uid = Binder.getCallingUid();
3994 int pid = Binder.getCallingPid();
3995 long callingId = Binder.clearCallingIdentity();
3996 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003997 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 int pkgUid = -1;
3999 synchronized(this) {
4000 try {
4001 pkgUid = pm.getPackageUid(packageName);
4002 } catch (RemoteException e) {
4003 }
4004 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004005 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 return false;
4007 }
4008 if (uid == pkgUid || checkComponentPermission(
4009 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004010 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08004012 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 } else {
4014 throw new SecurityException(pid+" does not have permission:"+
4015 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
4016 "for process:"+packageName);
4017 }
4018 }
4019
4020 try {
4021 //clear application user data
4022 pm.clearApplicationUserData(packageName, observer);
4023 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
4024 Uri.fromParts("package", packageName, null));
4025 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004026 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07004027 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 } catch (RemoteException e) {
4029 }
4030 } finally {
4031 Binder.restoreCallingIdentity(callingId);
4032 }
4033 return true;
4034 }
4035
Dianne Hackborn03abb812010-01-04 18:43:19 -08004036 public void killBackgroundProcesses(final String packageName) {
4037 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4038 != PackageManager.PERMISSION_GRANTED &&
4039 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
4040 != PackageManager.PERMISSION_GRANTED) {
4041 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004042 + Binder.getCallingPid()
4043 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08004044 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004045 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 throw new SecurityException(msg);
4047 }
4048
4049 long callingId = Binder.clearCallingIdentity();
4050 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004051 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052 int pkgUid = -1;
4053 synchronized(this) {
4054 try {
4055 pkgUid = pm.getPackageUid(packageName);
4056 } catch (RemoteException e) {
4057 }
4058 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004059 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 return;
4061 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004062 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004063 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
4064 }
4065 } finally {
4066 Binder.restoreCallingIdentity(callingId);
4067 }
4068 }
4069
4070 public void killAllBackgroundProcesses() {
4071 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4072 != PackageManager.PERMISSION_GRANTED) {
4073 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
4074 + Binder.getCallingPid()
4075 + ", uid=" + Binder.getCallingUid()
4076 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4077 Slog.w(TAG, msg);
4078 throw new SecurityException(msg);
4079 }
4080
4081 long callingId = Binder.clearCallingIdentity();
4082 try {
4083 synchronized(this) {
4084 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
4085 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
4086 final int NA = apps.size();
4087 for (int ia=0; ia<NA; ia++) {
4088 ProcessRecord app = apps.valueAt(ia);
4089 if (app.persistent) {
4090 // we don't kill persistent processes
4091 continue;
4092 }
4093 if (app.removed) {
4094 procs.add(app);
4095 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
4096 app.removed = true;
4097 procs.add(app);
4098 }
4099 }
4100 }
4101
4102 int N = procs.size();
4103 for (int i=0; i<N; i++) {
4104 removeProcessLocked(procs.get(i), false, true, "kill all background");
4105 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004106 }
4107 } finally {
4108 Binder.restoreCallingIdentity(callingId);
4109 }
4110 }
4111
4112 public void forceStopPackage(final String packageName) {
4113 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4114 != PackageManager.PERMISSION_GRANTED) {
4115 String msg = "Permission Denial: forceStopPackage() from pid="
4116 + Binder.getCallingPid()
4117 + ", uid=" + Binder.getCallingUid()
4118 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004119 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004120 throw new SecurityException(msg);
4121 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004122 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08004123 long callingId = Binder.clearCallingIdentity();
4124 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004125 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08004126 int pkgUid = -1;
4127 synchronized(this) {
4128 try {
4129 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004130 // Convert the uid to the one for the calling user
4131 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004132 } catch (RemoteException e) {
4133 }
4134 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004135 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004136 return;
4137 }
4138 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08004139 try {
4140 pm.setPackageStoppedState(packageName, true);
4141 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08004142 } catch (IllegalArgumentException e) {
4143 Slog.w(TAG, "Failed trying to unstop package "
4144 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08004145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 }
4147 } finally {
4148 Binder.restoreCallingIdentity(callingId);
4149 }
4150 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004151
4152 /*
4153 * The pkg name and uid have to be specified.
4154 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
4155 */
4156 public void killApplicationWithUid(String pkg, int uid) {
4157 if (pkg == null) {
4158 return;
4159 }
4160 // Make sure the uid is valid.
4161 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004162 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004163 return;
4164 }
4165 int callerUid = Binder.getCallingUid();
4166 // Only the system server can kill an application
4167 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07004168 // Post an aysnc message to kill the application
4169 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
4170 msg.arg1 = uid;
4171 msg.arg2 = 0;
4172 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07004173 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004174 } else {
4175 throw new SecurityException(callerUid + " cannot kill pkg: " +
4176 pkg);
4177 }
4178 }
4179
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004180 public void closeSystemDialogs(String reason) {
4181 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004182 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004183 if (reason != null) {
4184 intent.putExtra("reason", reason);
4185 }
4186
4187 final int uid = Binder.getCallingUid();
4188 final long origId = Binder.clearCallingIdentity();
4189 synchronized (this) {
4190 int i = mWatchers.beginBroadcast();
4191 while (i > 0) {
4192 i--;
4193 IActivityWatcher w = mWatchers.getBroadcastItem(i);
4194 if (w != null) {
4195 try {
4196 w.closingSystemDialogs(reason);
4197 } catch (RemoteException e) {
4198 }
4199 }
4200 }
4201 mWatchers.finishBroadcast();
4202
Dianne Hackbornffa42482009-09-23 22:20:11 -07004203 mWindowManager.closeSystemDialogs(reason);
4204
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004205 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
4206 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07004207 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004208 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07004209 Activity.RESULT_CANCELED, null, "close-sys");
4210 }
4211 }
4212
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004213 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07004214 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004215 }
4216 Binder.restoreCallingIdentity(origId);
4217 }
4218
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004219 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004220 throws RemoteException {
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004221 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
4222 for (int i=pids.length-1; i>=0; i--) {
4223 infos[i] = new Debug.MemoryInfo();
4224 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004225 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004226 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004227 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07004228
Dianne Hackbornb437e092011-08-05 17:50:29 -07004229 public long[] getProcessPss(int[] pids) throws RemoteException {
4230 long[] pss = new long[pids.length];
4231 for (int i=pids.length-1; i>=0; i--) {
4232 pss[i] = Debug.getPss(pids[i]);
4233 }
4234 return pss;
4235 }
4236
Christopher Tate5e1ab332009-09-01 20:32:49 -07004237 public void killApplicationProcess(String processName, int uid) {
4238 if (processName == null) {
4239 return;
4240 }
4241
4242 int callerUid = Binder.getCallingUid();
4243 // Only the system server can kill an application
4244 if (callerUid == Process.SYSTEM_UID) {
4245 synchronized (this) {
4246 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07004247 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07004248 try {
4249 app.thread.scheduleSuicide();
4250 } catch (RemoteException e) {
4251 // If the other end already died, then our work here is done.
4252 }
4253 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004254 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07004255 + processName + " / " + uid);
4256 }
4257 }
4258 } else {
4259 throw new SecurityException(callerUid + " cannot kill app process: " +
4260 processName);
4261 }
4262 }
4263
Dianne Hackborn03abb812010-01-04 18:43:19 -08004264 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004265 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
4267 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004268 if (!mProcessesReady) {
4269 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 intent.putExtra(Intent.EXTRA_UID, uid);
4272 broadcastIntentLocked(null, null, intent,
4273 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07004274 false, false,
4275 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 }
4277
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004278 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07004279 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004280 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08004281 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282
Dianne Hackborn03abb812010-01-04 18:43:19 -08004283 // Remove all processes this package may have touched: all with the
4284 // same UID (except for the system or root user), and all whose name
4285 // matches the package name.
4286 final String procNamePrefix = packageName + ":";
4287 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
4288 final int NA = apps.size();
4289 for (int ia=0; ia<NA; ia++) {
4290 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07004291 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07004292 // we don't kill persistent processes
4293 continue;
4294 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004295 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004296 if (doit) {
4297 procs.add(app);
4298 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004299 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
4300 || app.processName.equals(packageName)
4301 || app.processName.startsWith(procNamePrefix)) {
4302 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004303 if (!doit) {
4304 return true;
4305 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004306 app.removed = true;
4307 procs.add(app);
4308 }
4309 }
4310 }
4311 }
4312
4313 int N = procs.size();
4314 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004315 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004316 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004317 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08004318 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004319
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004320 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07004321 boolean callerWillRestart, boolean purgeCache, boolean doit,
4322 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004323 int i;
4324 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 if (uid < 0) {
4327 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004328 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004329 } catch (RemoteException e) {
4330 }
4331 }
4332
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004333 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004334 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004335
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004336 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
4337 while (badApps.hasNext()) {
4338 SparseArray<Long> ba = badApps.next();
4339 if (ba.get(uid) != null) {
4340 badApps.remove();
4341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 }
4343 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004344
4345 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004346 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004348 TaskRecord lastTask = null;
4349 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004350 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004351 final boolean samePackage = r.packageName.equals(name);
4352 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07004353 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004354 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07004355 if (r.finishing) {
4356 // If this activity is just finishing, then it is not
4357 // interesting as far as something to stop.
4358 continue;
4359 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004360 return true;
4361 }
4362 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004363 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004364 if (samePackage) {
4365 if (r.app != null) {
4366 r.app.removed = true;
4367 }
4368 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07004370 lastTask = r.task;
4371 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
4372 null, "force-stop")) {
4373 i--;
4374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004375 }
4376 }
4377
4378 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07004379 int userId = UserId.getUserId(uid);
4380 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07004381 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07004382 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004383 if (!doit) {
4384 return true;
4385 }
4386 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004387 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 if (service.app != null) {
4389 service.app.removed = true;
4390 }
4391 service.app = null;
4392 services.add(service);
4393 }
4394 }
4395
4396 N = services.size();
4397 for (i=0; i<N; i++) {
4398 bringDownServiceLocked(services.get(i), true);
4399 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004400
4401 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
4402 for (ContentProviderRecord provider : mProvidersByClass.values()) {
4403 if (provider.info.packageName.equals(name)
4404 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
4405 if (!doit) {
4406 return true;
4407 }
4408 didSomething = true;
4409 providers.add(provider);
4410 }
4411 }
4412
4413 N = providers.size();
4414 for (i=0; i<N; i++) {
4415 removeDyingProviderLocked(null, providers.get(i));
4416 }
4417
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004418 if (doit) {
4419 if (purgeCache) {
4420 AttributeCache ac = AttributeCache.instance();
4421 if (ac != null) {
4422 ac.removePackage(name);
4423 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004424 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004425 if (mBooted) {
4426 mMainStack.resumeTopActivityLocked(null);
4427 mMainStack.scheduleIdleLocked();
4428 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004429 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004430
4431 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 }
4433
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004434 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004435 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004436 final String name = app.processName;
4437 final int uid = app.info.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004438 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004439 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440 + "/" + uid + ")");
4441
4442 mProcessNames.remove(name, uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004443 if (mHeavyWeightProcess == app) {
4444 mHeavyWeightProcess = null;
4445 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
4446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 boolean needRestart = false;
4448 if (app.pid > 0 && app.pid != MY_PID) {
4449 int pid = app.pid;
4450 synchronized (mPidsSelfLocked) {
4451 mPidsSelfLocked.remove(pid);
4452 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4453 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004454 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004455 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004456 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004457 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004458
4459 if (app.persistent) {
4460 if (!callerWillRestart) {
4461 addAppLocked(app.info);
4462 } else {
4463 needRestart = true;
4464 }
4465 }
4466 } else {
4467 mRemovedProcesses.add(app);
4468 }
4469
4470 return needRestart;
4471 }
4472
4473 private final void processStartTimedOutLocked(ProcessRecord app) {
4474 final int pid = app.pid;
4475 boolean gone = false;
4476 synchronized (mPidsSelfLocked) {
4477 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4478 if (knownApp != null && knownApp.thread == null) {
4479 mPidsSelfLocked.remove(pid);
4480 gone = true;
4481 }
4482 }
4483
4484 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004485 Slog.w(TAG, "Process " + app + " failed to attach");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004486 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.info.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004487 app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004489 if (mHeavyWeightProcess == app) {
4490 mHeavyWeightProcess = null;
4491 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
4492 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004493 // Take care of any launching providers waiting for this process.
4494 checkAppInLaunchingProvidersLocked(app, true);
4495 // Take care of any services that are waiting for the process.
4496 for (int i=0; i<mPendingServices.size(); i++) {
4497 ServiceRecord sr = mPendingServices.get(i);
4498 if (app.info.uid == sr.appInfo.uid
4499 && app.processName.equals(sr.processName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004500 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004501 mPendingServices.remove(i);
4502 i--;
4503 bringDownServiceLocked(sr, true);
4504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004506 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
4507 app.processName, app.setAdj, "start timeout");
4508 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004509 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004510 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004511 try {
4512 IBackupManager bm = IBackupManager.Stub.asInterface(
4513 ServiceManager.getService(Context.BACKUP_SERVICE));
4514 bm.agentDisconnected(app.info.packageName);
4515 } catch (RemoteException e) {
4516 // Can't happen; the backup manager is local
4517 }
4518 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004519 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004520 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004521 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004524 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 }
4526 }
4527
4528 private final boolean attachApplicationLocked(IApplicationThread thread,
4529 int pid) {
4530
4531 // Find the application record that is being attached... either via
4532 // the pid if we are running in multiple processes, or just pull the
4533 // next app record if we are emulating process with anonymous threads.
4534 ProcessRecord app;
4535 if (pid != MY_PID && pid >= 0) {
4536 synchronized (mPidsSelfLocked) {
4537 app = mPidsSelfLocked.get(pid);
4538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 } else {
4540 app = null;
4541 }
4542
4543 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004544 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004546 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004547 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004548 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004549 } else {
4550 try {
4551 thread.scheduleExit();
4552 } catch (Exception e) {
4553 // Ignore exceptions.
4554 }
4555 }
4556 return false;
4557 }
4558
4559 // If this application record is still attached to a previous
4560 // process, clean it up now.
4561 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004562 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563 }
4564
4565 // Tell the process all about itself.
4566
Joe Onorato8a9b2202010-02-26 18:56:32 -08004567 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 TAG, "Binding process pid " + pid + " to record " + app);
4569
4570 String processName = app.processName;
4571 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004572 AppDeathRecipient adr = new AppDeathRecipient(
4573 app, pid, thread);
4574 thread.asBinder().linkToDeath(adr, 0);
4575 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 } catch (RemoteException e) {
4577 app.resetPackageList();
4578 startProcessLocked(app, "link fail", processName);
4579 return false;
4580 }
4581
Doug Zongker2bec3d42009-12-04 12:52:44 -08004582 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583
4584 app.thread = thread;
4585 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004586 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4587 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 app.forcingToForeground = null;
4589 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004590 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 app.debugging = false;
4592
4593 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4594
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004595 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004596 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004597
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004598 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004599 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004600 }
4601
Joe Onorato8a9b2202010-02-26 18:56:32 -08004602 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004603 TAG, "New app record " + app
4604 + " thread=" + thread.asBinder() + " pid=" + pid);
4605 try {
4606 int testMode = IApplicationThread.DEBUG_OFF;
4607 if (mDebugApp != null && mDebugApp.equals(processName)) {
4608 testMode = mWaitForDebugger
4609 ? IApplicationThread.DEBUG_WAIT
4610 : IApplicationThread.DEBUG_ON;
4611 app.debugging = true;
4612 if (mDebugTransient) {
4613 mDebugApp = mOrigDebugApp;
4614 mWaitForDebugger = mOrigWaitForDebugger;
4615 }
4616 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004617 String profileFile = app.instrumentationProfileFile;
4618 ParcelFileDescriptor profileFd = null;
4619 boolean profileAutoStop = false;
4620 if (mProfileApp != null && mProfileApp.equals(processName)) {
4621 mProfileProc = app;
4622 profileFile = mProfileFile;
4623 profileFd = mProfileFd;
4624 profileAutoStop = mAutoStopProfiler;
4625 }
4626
Christopher Tate181fafa2009-05-14 11:12:14 -07004627 // If the app is being launched for restore or full backup, set it up specially
4628 boolean isRestrictedBackupMode = false;
4629 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4630 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004631 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004632 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4633 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004634
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004635 ensurePackageDexOpt(app.instrumentationInfo != null
4636 ? app.instrumentationInfo.packageName
4637 : app.info.packageName);
4638 if (app.instrumentationClass != null) {
4639 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004640 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004641 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004642 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004643 ApplicationInfo appInfo = app.instrumentationInfo != null
4644 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004645 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004646 if (profileFd != null) {
4647 profileFd = profileFd.dup();
4648 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004649 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004650 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn5d927c22011-09-02 12:22:18 -07004652 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004653 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004654 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004655 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004656 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 } catch (Exception e) {
4658 // todo: Yikes! What should we do? For now we will try to
4659 // start another process, but that could easily get us in
4660 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004661 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004662
4663 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004664 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 startProcessLocked(app, "bind fail", processName);
4666 return false;
4667 }
4668
4669 // Remove this record from the list of starting applications.
4670 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004671 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4672 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004673 mProcessesOnHold.remove(app);
4674
4675 boolean badApp = false;
4676 boolean didSomething = false;
4677
4678 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004679 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004680 if (hr != null && normalMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004681 if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
4682 && processName.equals(hr.processName)) {
4683 try {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004684 if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004685 didSomething = true;
4686 }
4687 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004688 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 + hr.intent.getComponent().flattenToShortString(), e);
4690 badApp = true;
4691 }
4692 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004693 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 }
4695 }
4696
4697 // Find any services that should be running in this process...
4698 if (!badApp && mPendingServices.size() > 0) {
4699 ServiceRecord sr = null;
4700 try {
4701 for (int i=0; i<mPendingServices.size(); i++) {
4702 sr = mPendingServices.get(i);
4703 if (app.info.uid != sr.appInfo.uid
4704 || !processName.equals(sr.processName)) {
4705 continue;
4706 }
4707
4708 mPendingServices.remove(i);
4709 i--;
4710 realStartServiceLocked(sr, app);
4711 didSomething = true;
4712 }
4713 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004714 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 + sr.shortName, e);
4716 badApp = true;
4717 }
4718 }
4719
Christopher Tatef46723b2012-01-26 14:19:24 -08004720 // Check if a next-broadcast receiver is in this process...
4721 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004722 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004723 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004724 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004725 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004726 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004727 }
4728 }
4729
Christopher Tate181fafa2009-05-14 11:12:14 -07004730 // Check whether the next backup agent is in this process...
4731 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.info.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004732 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004733 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004734 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004735 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4736 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4737 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004738 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004739 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004740 e.printStackTrace();
4741 }
4742 }
4743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004744 if (badApp) {
4745 // todo: Also need to kill application to deal with all
4746 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004747 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 return false;
4749 }
4750
4751 if (!didSomething) {
4752 updateOomAdjLocked();
4753 }
4754
4755 return true;
4756 }
4757
4758 public final void attachApplication(IApplicationThread thread) {
4759 synchronized (this) {
4760 int callingPid = Binder.getCallingPid();
4761 final long origId = Binder.clearCallingIdentity();
4762 attachApplicationLocked(thread, callingPid);
4763 Binder.restoreCallingIdentity(origId);
4764 }
4765 }
4766
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004767 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004768 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004769 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4770 if (stopProfiling) {
4771 synchronized (this) {
4772 if (mProfileProc == r.app) {
4773 if (mProfileFd != null) {
4774 try {
4775 mProfileFd.close();
4776 } catch (IOException e) {
4777 }
4778 clearProfilerLocked();
4779 }
4780 }
4781 }
4782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004783 Binder.restoreCallingIdentity(origId);
4784 }
4785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004786 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004787 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004788 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004789 mWindowManager.enableScreenAfterBoot();
4790 }
4791
Dianne Hackborn661cd522011-08-22 00:26:20 -07004792 public void showBootMessage(final CharSequence msg, final boolean always) {
4793 mWindowManager.showBootMessage(msg, always);
4794 }
4795
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004796 public void dismissKeyguardOnNextActivity() {
4797 synchronized (this) {
4798 mMainStack.dismissKeyguardOnNextActivityLocked();
4799 }
4800 }
4801
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004802 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004803 IntentFilter pkgFilter = new IntentFilter();
4804 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4805 pkgFilter.addDataScheme("package");
4806 mContext.registerReceiver(new BroadcastReceiver() {
4807 @Override
4808 public void onReceive(Context context, Intent intent) {
4809 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4810 if (pkgs != null) {
4811 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004812 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004813 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004814 setResultCode(Activity.RESULT_OK);
4815 return;
4816 }
4817 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004818 }
4819 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004820 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004821 }, pkgFilter);
4822
4823 synchronized (this) {
4824 // Ensure that any processes we had put on hold are now started
4825 // up.
4826 final int NP = mProcessesOnHold.size();
4827 if (NP > 0) {
4828 ArrayList<ProcessRecord> procs =
4829 new ArrayList<ProcessRecord>(mProcessesOnHold);
4830 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004831 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4832 + procs.get(ip));
4833 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004834 }
4835 }
4836
4837 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004838 // Start looking for apps that are abusing wake locks.
4839 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004840 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004841 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004842 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004843 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004844 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004845 broadcastIntentLocked(null, null,
4846 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4847 null, null, 0, null, null,
4848 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004849 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004850 }
4851 }
4852 }
4853
4854 final void ensureBootCompleted() {
4855 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004856 boolean enableScreen;
4857 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004858 booting = mBooting;
4859 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004860 enableScreen = !mBooted;
4861 mBooted = true;
4862 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004863
4864 if (booting) {
4865 finishBooting();
4866 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004867
4868 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004869 enableScreenAfterBoot();
4870 }
4871 }
4872
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004873 public final void activityPaused(IBinder token) {
4874 final long origId = Binder.clearCallingIdentity();
4875 mMainStack.activityPaused(token, false);
4876 Binder.restoreCallingIdentity(origId);
4877 }
4878
4879 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4880 CharSequence description) {
4881 if (localLOGV) Slog.v(
4882 TAG, "Activity stopped: token=" + token);
4883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 // Refuse possible leaked file descriptors
4885 if (icicle != null && icicle.hasFileDescriptors()) {
4886 throw new IllegalArgumentException("File descriptors passed in Bundle");
4887 }
4888
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004889 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890
4891 final long origId = Binder.clearCallingIdentity();
4892
4893 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004894 r = mMainStack.isInStackLocked(token);
4895 if (r != null) {
4896 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004897 }
4898 }
4899
4900 if (r != null) {
4901 sendPendingThumbnail(r, null, null, null, false);
4902 }
4903
4904 trimApplications();
4905
4906 Binder.restoreCallingIdentity(origId);
4907 }
4908
4909 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004910 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004911 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004912 }
4913
4914 public String getCallingPackage(IBinder token) {
4915 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004916 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004917 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004918 }
4919 }
4920
4921 public ComponentName getCallingActivity(IBinder token) {
4922 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004923 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004924 return r != null ? r.intent.getComponent() : null;
4925 }
4926 }
4927
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004928 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004929 ActivityRecord r = mMainStack.isInStackLocked(token);
4930 if (r == null) {
4931 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004932 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004933 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004934 }
4935
4936 public ComponentName getActivityClassForToken(IBinder token) {
4937 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004938 ActivityRecord r = mMainStack.isInStackLocked(token);
4939 if (r == null) {
4940 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004942 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943 }
4944 }
4945
4946 public String getPackageForToken(IBinder token) {
4947 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004948 ActivityRecord r = mMainStack.isInStackLocked(token);
4949 if (r == null) {
4950 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004951 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004952 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004953 }
4954 }
4955
4956 public IIntentSender getIntentSender(int type,
4957 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004958 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004959 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004960 if (intents != null) {
4961 if (intents.length < 1) {
4962 throw new IllegalArgumentException("Intents array length must be >= 1");
4963 }
4964 for (int i=0; i<intents.length; i++) {
4965 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004966 if (intent != null) {
4967 if (intent.hasFileDescriptors()) {
4968 throw new IllegalArgumentException("File descriptors passed in Intent");
4969 }
4970 if (type == INTENT_SENDER_BROADCAST &&
4971 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4972 throw new IllegalArgumentException(
4973 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4974 }
4975 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004976 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004977 }
4978 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004979 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004980 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004981 }
4982 }
4983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984 synchronized(this) {
4985 int callingUid = Binder.getCallingUid();
4986 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004987 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004988 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004989 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004990 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004991 String msg = "Permission Denial: getIntentSender() from pid="
4992 + Binder.getCallingPid()
4993 + ", uid=" + Binder.getCallingUid()
4994 + ", (need uid=" + uid + ")"
4995 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004996 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004997 throw new SecurityException(msg);
4998 }
4999 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005000
Amith Yamasani742a6712011-05-04 14:49:28 -07005001 if (DEBUG_MU)
5002 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
5003 + Binder.getOrigCallingUid());
5004 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005005 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07005006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005007 } catch (RemoteException e) {
5008 throw new SecurityException(e);
5009 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005010 }
5011 }
5012
5013 IIntentSender getIntentSenderLocked(int type,
5014 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005015 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005016 if (DEBUG_MU)
5017 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005018 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07005019 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005020 activity = mMainStack.isInStackLocked(token);
5021 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005022 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005024 if (activity.finishing) {
5025 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005026 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005027 }
5028
5029 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
5030 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
5031 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
5032 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
5033 |PendingIntent.FLAG_UPDATE_CURRENT);
5034
5035 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
5036 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005037 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07005038 WeakReference<PendingIntentRecord> ref;
5039 ref = mIntentSenderRecords.get(key);
5040 PendingIntentRecord rec = ref != null ? ref.get() : null;
5041 if (rec != null) {
5042 if (!cancelCurrent) {
5043 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005044 if (rec.key.requestIntent != null) {
5045 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
5046 }
5047 if (intents != null) {
5048 intents[intents.length-1] = rec.key.requestIntent;
5049 rec.key.allIntents = intents;
5050 rec.key.allResolvedTypes = resolvedTypes;
5051 } else {
5052 rec.key.allIntents = null;
5053 rec.key.allResolvedTypes = null;
5054 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005056 return rec;
5057 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005058 rec.canceled = true;
5059 mIntentSenderRecords.remove(key);
5060 }
5061 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 return rec;
5063 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005064 rec = new PendingIntentRecord(this, key, callingUid);
5065 mIntentSenderRecords.put(key, rec.ref);
5066 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
5067 if (activity.pendingResults == null) {
5068 activity.pendingResults
5069 = new HashSet<WeakReference<PendingIntentRecord>>();
5070 }
5071 activity.pendingResults.add(rec.ref);
5072 }
5073 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 }
5075
5076 public void cancelIntentSender(IIntentSender sender) {
5077 if (!(sender instanceof PendingIntentRecord)) {
5078 return;
5079 }
5080 synchronized(this) {
5081 PendingIntentRecord rec = (PendingIntentRecord)sender;
5082 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005083 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005084 .getPackageUid(rec.key.packageName);
5085 if (uid != Binder.getCallingUid()) {
5086 String msg = "Permission Denial: cancelIntentSender() from pid="
5087 + Binder.getCallingPid()
5088 + ", uid=" + Binder.getCallingUid()
5089 + " is not allowed to cancel packges "
5090 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005091 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 throw new SecurityException(msg);
5093 }
5094 } catch (RemoteException e) {
5095 throw new SecurityException(e);
5096 }
5097 cancelIntentSenderLocked(rec, true);
5098 }
5099 }
5100
5101 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
5102 rec.canceled = true;
5103 mIntentSenderRecords.remove(rec.key);
5104 if (cleanActivity && rec.key.activity != null) {
5105 rec.key.activity.pendingResults.remove(rec.ref);
5106 }
5107 }
5108
5109 public String getPackageForIntentSender(IIntentSender pendingResult) {
5110 if (!(pendingResult instanceof PendingIntentRecord)) {
5111 return null;
5112 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07005113 try {
5114 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5115 return res.key.packageName;
5116 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005117 }
5118 return null;
5119 }
5120
Dianne Hackborn6c418d52011-06-29 14:05:33 -07005121 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
5122 if (!(pendingResult instanceof PendingIntentRecord)) {
5123 return false;
5124 }
5125 try {
5126 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5127 if (res.key.allIntents == null) {
5128 return false;
5129 }
5130 for (int i=0; i<res.key.allIntents.length; i++) {
5131 Intent intent = res.key.allIntents[i];
5132 if (intent.getPackage() != null && intent.getComponent() != null) {
5133 return false;
5134 }
5135 }
5136 return true;
5137 } catch (ClassCastException e) {
5138 }
5139 return false;
5140 }
5141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005142 public void setProcessLimit(int max) {
5143 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5144 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005145 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005146 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005147 mProcessLimitOverride = max;
5148 }
5149 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150 }
5151
5152 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005153 synchronized (this) {
5154 return mProcessLimitOverride;
5155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 }
5157
5158 void foregroundTokenDied(ForegroundToken token) {
5159 synchronized (ActivityManagerService.this) {
5160 synchronized (mPidsSelfLocked) {
5161 ForegroundToken cur
5162 = mForegroundProcesses.get(token.pid);
5163 if (cur != token) {
5164 return;
5165 }
5166 mForegroundProcesses.remove(token.pid);
5167 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
5168 if (pr == null) {
5169 return;
5170 }
5171 pr.forcingToForeground = null;
5172 pr.foregroundServices = false;
5173 }
5174 updateOomAdjLocked();
5175 }
5176 }
5177
5178 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
5179 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5180 "setProcessForeground()");
5181 synchronized(this) {
5182 boolean changed = false;
5183
5184 synchronized (mPidsSelfLocked) {
5185 ProcessRecord pr = mPidsSelfLocked.get(pid);
5186 if (pr == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005187 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005188 return;
5189 }
5190 ForegroundToken oldToken = mForegroundProcesses.get(pid);
5191 if (oldToken != null) {
5192 oldToken.token.unlinkToDeath(oldToken, 0);
5193 mForegroundProcesses.remove(pid);
5194 pr.forcingToForeground = null;
5195 changed = true;
5196 }
5197 if (isForeground && token != null) {
5198 ForegroundToken newToken = new ForegroundToken() {
5199 public void binderDied() {
5200 foregroundTokenDied(this);
5201 }
5202 };
5203 newToken.pid = pid;
5204 newToken.token = token;
5205 try {
5206 token.linkToDeath(newToken, 0);
5207 mForegroundProcesses.put(pid, newToken);
5208 pr.forcingToForeground = token;
5209 changed = true;
5210 } catch (RemoteException e) {
5211 // If the process died while doing this, we will later
5212 // do the cleanup with the process death link.
5213 }
5214 }
5215 }
5216
5217 if (changed) {
5218 updateOomAdjLocked();
5219 }
5220 }
5221 }
5222
5223 // =========================================================
5224 // PERMISSIONS
5225 // =========================================================
5226
5227 static class PermissionController extends IPermissionController.Stub {
5228 ActivityManagerService mActivityManagerService;
5229 PermissionController(ActivityManagerService activityManagerService) {
5230 mActivityManagerService = activityManagerService;
5231 }
5232
5233 public boolean checkPermission(String permission, int pid, int uid) {
5234 return mActivityManagerService.checkPermission(permission, pid,
5235 uid) == PackageManager.PERMISSION_GRANTED;
5236 }
5237 }
5238
5239 /**
5240 * This can be called with or without the global lock held.
5241 */
5242 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005243 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 // We might be performing an operation on behalf of an indirect binder
5245 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
5246 // client identity accordingly before proceeding.
5247 Identity tlsIdentity = sCallerIdentity.get();
5248 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005249 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
5251 uid = tlsIdentity.uid;
5252 pid = tlsIdentity.pid;
5253 }
5254
5255 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005256 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257 return PackageManager.PERMISSION_GRANTED;
5258 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005259 // If there is a uid that owns whatever is being accessed, it has
5260 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07005261 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005262 return PackageManager.PERMISSION_GRANTED;
5263 }
5264 // If the target is not exported, then nobody else can get to it.
5265 if (!exported) {
5266 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005267 return PackageManager.PERMISSION_DENIED;
5268 }
5269 if (permission == null) {
5270 return PackageManager.PERMISSION_GRANTED;
5271 }
5272 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005273 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005274 .checkUidPermission(permission, uid);
5275 } catch (RemoteException e) {
5276 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08005277 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005278 }
5279 return PackageManager.PERMISSION_DENIED;
5280 }
5281
5282 /**
5283 * As the only public entry point for permissions checking, this method
5284 * can enforce the semantic that requesting a check on a null global
5285 * permission is automatically denied. (Internally a null permission
5286 * string is used when calling {@link #checkComponentPermission} in cases
5287 * when only uid-based security is needed.)
5288 *
5289 * This can be called with or without the global lock held.
5290 */
5291 public int checkPermission(String permission, int pid, int uid) {
5292 if (permission == null) {
5293 return PackageManager.PERMISSION_DENIED;
5294 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005295 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005296 }
5297
5298 /**
5299 * Binder IPC calls go through the public entry point.
5300 * This can be called with or without the global lock held.
5301 */
5302 int checkCallingPermission(String permission) {
5303 return checkPermission(permission,
5304 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07005305 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005306 }
5307
5308 /**
5309 * This can be called with or without the global lock held.
5310 */
5311 void enforceCallingPermission(String permission, String func) {
5312 if (checkCallingPermission(permission)
5313 == PackageManager.PERMISSION_GRANTED) {
5314 return;
5315 }
5316
5317 String msg = "Permission Denial: " + func + " from pid="
5318 + Binder.getCallingPid()
5319 + ", uid=" + Binder.getCallingUid()
5320 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005321 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005322 throw new SecurityException(msg);
5323 }
5324
5325 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07005326 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
5327 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
5328 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
5329 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5330 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005332 // Is the component private from the target uid?
5333 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
5334
5335 // Acceptable if the there is no read permission needed from the
5336 // target or the target is holding the read permission.
5337 if (!readPerm) {
5338 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005339 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07005340 == PackageManager.PERMISSION_GRANTED)) {
5341 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005342 }
5343 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005344
5345 // Acceptable if the there is no write permission needed from the
5346 // target or the target is holding the read permission.
5347 if (!writePerm) {
5348 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005349 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07005350 == PackageManager.PERMISSION_GRANTED)) {
5351 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005352 }
5353 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005354
5355 // Acceptable if there is a path permission matching the URI that
5356 // the target holds the permission on.
5357 PathPermission[] pps = pi.pathPermissions;
5358 if (pps != null && (!readPerm || !writePerm)) {
5359 final String path = uri.getPath();
5360 int i = pps.length;
5361 while (i > 0 && (!readPerm || !writePerm)) {
5362 i--;
5363 PathPermission pp = pps[i];
5364 if (!readPerm) {
5365 final String pprperm = pp.getReadPermission();
5366 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5367 + pprperm + " for " + pp.getPath()
5368 + ": match=" + pp.match(path)
5369 + " check=" + pm.checkUidPermission(pprperm, uid));
5370 if (pprperm != null && pp.match(path) &&
5371 (pm.checkUidPermission(pprperm, uid)
5372 == PackageManager.PERMISSION_GRANTED)) {
5373 readPerm = true;
5374 }
5375 }
5376 if (!writePerm) {
5377 final String ppwperm = pp.getWritePermission();
5378 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5379 + ppwperm + " for " + pp.getPath()
5380 + ": match=" + pp.match(path)
5381 + " check=" + pm.checkUidPermission(ppwperm, uid));
5382 if (ppwperm != null && pp.match(path) &&
5383 (pm.checkUidPermission(ppwperm, uid)
5384 == PackageManager.PERMISSION_GRANTED)) {
5385 writePerm = true;
5386 }
5387 }
5388 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005390 } catch (RemoteException e) {
5391 return false;
5392 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005393
5394 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 }
5396
5397 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5398 int modeFlags) {
5399 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005400 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005401 return true;
5402 }
5403 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5404 if (perms == null) return false;
5405 UriPermission perm = perms.get(uri);
5406 if (perm == null) return false;
5407 return (modeFlags&perm.modeFlags) == modeFlags;
5408 }
5409
5410 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
5411 // Another redirected-binder-call permissions check as in
5412 // {@link checkComponentPermission}.
5413 Identity tlsIdentity = sCallerIdentity.get();
5414 if (tlsIdentity != null) {
5415 uid = tlsIdentity.uid;
5416 pid = tlsIdentity.pid;
5417 }
5418
Amith Yamasani742a6712011-05-04 14:49:28 -07005419 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 // Our own process gets to do everything.
5421 if (pid == MY_PID) {
5422 return PackageManager.PERMISSION_GRANTED;
5423 }
5424 synchronized(this) {
5425 return checkUriPermissionLocked(uri, uid, modeFlags)
5426 ? PackageManager.PERMISSION_GRANTED
5427 : PackageManager.PERMISSION_DENIED;
5428 }
5429 }
5430
Dianne Hackborn39792d22010-08-19 18:01:52 -07005431 /**
5432 * Check if the targetPkg can be granted permission to access uri by
5433 * the callingUid using the given modeFlags. Throws a security exception
5434 * if callingUid is not allowed to do this. Returns the uid of the target
5435 * if the URI permission grant should be performed; returns -1 if it is not
5436 * needed (for example targetPkg already has permission to access the URI).
5437 */
5438 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
5439 Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005440 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5441 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5442 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005443 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444 }
5445
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005446 if (targetPkg != null) {
5447 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5448 "Checking grant " + targetPkg + " permission to " + uri);
5449 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005450
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005451 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452
5453 // If this is not a content: uri, we can't do anything with it.
5454 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005455 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005456 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005457 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458 }
5459
5460 String name = uri.getAuthority();
5461 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005462 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
5463 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 if (cpr != null) {
5465 pi = cpr.info;
5466 } else {
5467 try {
5468 pi = pm.resolveContentProvider(name,
5469 PackageManager.GET_URI_PERMISSION_PATTERNS);
5470 } catch (RemoteException ex) {
5471 }
5472 }
5473 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005474 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005475 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 }
5477
5478 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005479 if (targetPkg != null) {
5480 try {
5481 targetUid = pm.getPackageUid(targetPkg);
5482 if (targetUid < 0) {
5483 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5484 "Can't grant URI permission no uid for: " + targetPkg);
5485 return -1;
5486 }
5487 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005488 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005490 } else {
5491 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005492 }
5493
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005494 if (targetUid >= 0) {
5495 // First... does the target actually need this permission?
5496 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5497 // No need to grant the target this permission.
5498 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5499 "Target " + targetPkg + " already has full permission to " + uri);
5500 return -1;
5501 }
5502 } else {
5503 // First... there is no target package, so can anyone access it?
5504 boolean allowed = pi.exported;
5505 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5506 if (pi.readPermission != null) {
5507 allowed = false;
5508 }
5509 }
5510 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5511 if (pi.writePermission != null) {
5512 allowed = false;
5513 }
5514 }
5515 if (allowed) {
5516 return -1;
5517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 }
5519
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005520 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 if (!pi.grantUriPermissions) {
5522 throw new SecurityException("Provider " + pi.packageName
5523 + "/" + pi.name
5524 + " does not allow granting of Uri permissions (uri "
5525 + uri + ")");
5526 }
5527 if (pi.uriPermissionPatterns != null) {
5528 final int N = pi.uriPermissionPatterns.length;
5529 boolean allowed = false;
5530 for (int i=0; i<N; i++) {
5531 if (pi.uriPermissionPatterns[i] != null
5532 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5533 allowed = true;
5534 break;
5535 }
5536 }
5537 if (!allowed) {
5538 throw new SecurityException("Provider " + pi.packageName
5539 + "/" + pi.name
5540 + " does not allow granting of permission to path of Uri "
5541 + uri);
5542 }
5543 }
5544
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005545 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005547 if (callingUid != Process.myUid()) {
5548 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5549 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5550 throw new SecurityException("Uid " + callingUid
5551 + " does not have permission to uri " + uri);
5552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 }
5554 }
5555
Dianne Hackborn39792d22010-08-19 18:01:52 -07005556 return targetUid;
5557 }
5558
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005559 public int checkGrantUriPermission(int callingUid, String targetPkg,
5560 Uri uri, int modeFlags) {
5561 synchronized(this) {
5562 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
5563 }
5564 }
5565
Dianne Hackborn39792d22010-08-19 18:01:52 -07005566 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5567 Uri uri, int modeFlags, UriPermissionOwner owner) {
5568 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5569 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5570 if (modeFlags == 0) {
5571 return;
5572 }
5573
5574 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 // to the uri, and the target doesn't. Let's now give this to
5576 // the target.
5577
Joe Onorato8a9b2202010-02-26 18:56:32 -08005578 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005579 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 HashMap<Uri, UriPermission> targetUris
5582 = mGrantedUriPermissions.get(targetUid);
5583 if (targetUris == null) {
5584 targetUris = new HashMap<Uri, UriPermission>();
5585 mGrantedUriPermissions.put(targetUid, targetUris);
5586 }
5587
5588 UriPermission perm = targetUris.get(uri);
5589 if (perm == null) {
5590 perm = new UriPermission(targetUid, uri);
5591 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005592 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005595 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005597 } else {
5598 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5599 perm.readOwners.add(owner);
5600 owner.addReadPermission(perm);
5601 }
5602 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5603 perm.writeOwners.add(owner);
5604 owner.addWritePermission(perm);
5605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 }
5607 }
5608
Dianne Hackborn39792d22010-08-19 18:01:52 -07005609 void grantUriPermissionLocked(int callingUid,
5610 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005611 if (targetPkg == null) {
5612 throw new NullPointerException("targetPkg");
5613 }
5614
Dianne Hackborn39792d22010-08-19 18:01:52 -07005615 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
5616 if (targetUid < 0) {
5617 return;
5618 }
5619
5620 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5621 }
5622
5623 /**
5624 * Like checkGrantUriPermissionLocked, but takes an Intent.
5625 */
5626 int checkGrantUriPermissionFromIntentLocked(int callingUid,
5627 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005628 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005629 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005630 + " from " + intent + "; flags=0x"
5631 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5632
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005633 if (targetPkg == null) {
5634 throw new NullPointerException("targetPkg");
5635 }
5636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005638 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 }
5640 Uri data = intent.getData();
5641 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005642 return -1;
5643 }
5644 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5645 intent.getFlags());
5646 }
5647
5648 /**
5649 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5650 */
5651 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
5652 String targetPkg, Intent intent, UriPermissionOwner owner) {
5653 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
5654 intent.getFlags(), owner);
5655 }
5656
5657 void grantUriPermissionFromIntentLocked(int callingUid,
5658 String targetPkg, Intent intent, UriPermissionOwner owner) {
5659 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
5660 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 return;
5662 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005663
5664 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 }
5666
5667 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5668 Uri uri, int modeFlags) {
5669 synchronized(this) {
5670 final ProcessRecord r = getRecordForAppLocked(caller);
5671 if (r == null) {
5672 throw new SecurityException("Unable to find app for caller "
5673 + caller
5674 + " when granting permission to uri " + uri);
5675 }
5676 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005677 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 }
5679 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005680 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 }
5682
5683 grantUriPermissionLocked(r.info.uid, targetPkg, uri, modeFlags,
5684 null);
5685 }
5686 }
5687
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005688 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5690 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5691 HashMap<Uri, UriPermission> perms
5692 = mGrantedUriPermissions.get(perm.uid);
5693 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005694 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005695 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 perms.remove(perm.uri);
5697 if (perms.size() == 0) {
5698 mGrantedUriPermissions.remove(perm.uid);
5699 }
5700 }
5701 }
5702 }
5703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005704 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5705 int modeFlags) {
5706 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5707 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5708 if (modeFlags == 0) {
5709 return;
5710 }
5711
Joe Onorato8a9b2202010-02-26 18:56:32 -08005712 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005713 "Revoking all granted permissions to " + uri);
5714
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005715 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716
5717 final String authority = uri.getAuthority();
5718 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005719 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
5720 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 if (cpr != null) {
5722 pi = cpr.info;
5723 } else {
5724 try {
5725 pi = pm.resolveContentProvider(authority,
5726 PackageManager.GET_URI_PERMISSION_PATTERNS);
5727 } catch (RemoteException ex) {
5728 }
5729 }
5730 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005731 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 return;
5733 }
5734
5735 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005736 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 // Right now, if you are not the original owner of the permission,
5738 // you are not allowed to revoke it.
5739 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5740 throw new SecurityException("Uid " + callingUid
5741 + " does not have permission to uri " + uri);
5742 //}
5743 }
5744
5745 // Go through all of the permissions and remove any that match.
5746 final List<String> SEGMENTS = uri.getPathSegments();
5747 if (SEGMENTS != null) {
5748 final int NS = SEGMENTS.size();
5749 int N = mGrantedUriPermissions.size();
5750 for (int i=0; i<N; i++) {
5751 HashMap<Uri, UriPermission> perms
5752 = mGrantedUriPermissions.valueAt(i);
5753 Iterator<UriPermission> it = perms.values().iterator();
5754 toploop:
5755 while (it.hasNext()) {
5756 UriPermission perm = it.next();
5757 Uri targetUri = perm.uri;
5758 if (!authority.equals(targetUri.getAuthority())) {
5759 continue;
5760 }
5761 List<String> targetSegments = targetUri.getPathSegments();
5762 if (targetSegments == null) {
5763 continue;
5764 }
5765 if (targetSegments.size() < NS) {
5766 continue;
5767 }
5768 for (int j=0; j<NS; j++) {
5769 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5770 continue toploop;
5771 }
5772 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005773 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005774 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775 perm.clearModes(modeFlags);
5776 if (perm.modeFlags == 0) {
5777 it.remove();
5778 }
5779 }
5780 if (perms.size() == 0) {
5781 mGrantedUriPermissions.remove(
5782 mGrantedUriPermissions.keyAt(i));
5783 N--;
5784 i--;
5785 }
5786 }
5787 }
5788 }
5789
5790 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5791 int modeFlags) {
5792 synchronized(this) {
5793 final ProcessRecord r = getRecordForAppLocked(caller);
5794 if (r == null) {
5795 throw new SecurityException("Unable to find app for caller "
5796 + caller
5797 + " when revoking permission to uri " + uri);
5798 }
5799 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005800 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801 return;
5802 }
5803
5804 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5805 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5806 if (modeFlags == 0) {
5807 return;
5808 }
5809
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005810 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811
5812 final String authority = uri.getAuthority();
5813 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005814 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
5815 UserId.getUserId(r.info.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 if (cpr != null) {
5817 pi = cpr.info;
5818 } else {
5819 try {
5820 pi = pm.resolveContentProvider(authority,
5821 PackageManager.GET_URI_PERMISSION_PATTERNS);
5822 } catch (RemoteException ex) {
5823 }
5824 }
5825 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005826 Slog.w(TAG, "No content provider found for permission revoke: "
5827 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 return;
5829 }
5830
5831 revokeUriPermissionLocked(r.info.uid, uri, modeFlags);
5832 }
5833 }
5834
Dianne Hackborn7e269642010-08-25 19:50:20 -07005835 @Override
5836 public IBinder newUriPermissionOwner(String name) {
5837 synchronized(this) {
5838 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5839 return owner.getExternalTokenLocked();
5840 }
5841 }
5842
5843 @Override
5844 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5845 Uri uri, int modeFlags) {
5846 synchronized(this) {
5847 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5848 if (owner == null) {
5849 throw new IllegalArgumentException("Unknown owner: " + token);
5850 }
5851 if (fromUid != Binder.getCallingUid()) {
5852 if (Binder.getCallingUid() != Process.myUid()) {
5853 // Only system code can grant URI permissions on behalf
5854 // of other users.
5855 throw new SecurityException("nice try");
5856 }
5857 }
5858 if (targetPkg == null) {
5859 throw new IllegalArgumentException("null target");
5860 }
5861 if (uri == null) {
5862 throw new IllegalArgumentException("null uri");
5863 }
5864
5865 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5866 }
5867 }
5868
5869 @Override
5870 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5871 synchronized(this) {
5872 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5873 if (owner == null) {
5874 throw new IllegalArgumentException("Unknown owner: " + token);
5875 }
5876
5877 if (uri == null) {
5878 owner.removeUriPermissionsLocked(mode);
5879 } else {
5880 owner.removeUriPermissionLocked(uri, mode);
5881 }
5882 }
5883 }
5884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5886 synchronized (this) {
5887 ProcessRecord app =
5888 who != null ? getRecordForAppLocked(who) : null;
5889 if (app == null) return;
5890
5891 Message msg = Message.obtain();
5892 msg.what = WAIT_FOR_DEBUGGER_MSG;
5893 msg.obj = app;
5894 msg.arg1 = waiting ? 1 : 0;
5895 mHandler.sendMessage(msg);
5896 }
5897 }
5898
5899 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005900 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5901 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005903 outInfo.threshold = homeAppMem;
5904 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5905 outInfo.hiddenAppThreshold = hiddenAppMem;
5906 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005907 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005908 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5909 ProcessList.VISIBLE_APP_ADJ);
5910 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5911 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 }
5913
5914 // =========================================================
5915 // TASK MANAGEMENT
5916 // =========================================================
5917
5918 public List getTasks(int maxNum, int flags,
5919 IThumbnailReceiver receiver) {
5920 ArrayList list = new ArrayList();
5921
5922 PendingThumbnailsRecord pending = null;
5923 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005924 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925
5926 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005927 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005928 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5929 + ", receiver=" + receiver);
5930
5931 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5932 != PackageManager.PERMISSION_GRANTED) {
5933 if (receiver != null) {
5934 // If the caller wants to wait for pending thumbnails,
5935 // it ain't gonna get them.
5936 try {
5937 receiver.finished();
5938 } catch (RemoteException ex) {
5939 }
5940 }
5941 String msg = "Permission Denial: getTasks() from pid="
5942 + Binder.getCallingPid()
5943 + ", uid=" + Binder.getCallingUid()
5944 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005945 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 throw new SecurityException(msg);
5947 }
5948
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005949 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005950 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005951 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005952 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005953 TaskRecord curTask = null;
5954 int numActivities = 0;
5955 int numRunning = 0;
5956 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005957 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005958 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005959 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960
5961 // Initialize state for next task if needed.
5962 if (top == null ||
5963 (top.state == ActivityState.INITIALIZING
5964 && top.task == r.task)) {
5965 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 curTask = r.task;
5967 numActivities = numRunning = 0;
5968 }
5969
5970 // Add 'r' into the current task.
5971 numActivities++;
5972 if (r.app != null && r.app.thread != null) {
5973 numRunning++;
5974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975
Joe Onorato8a9b2202010-02-26 18:56:32 -08005976 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 TAG, r.intent.getComponent().flattenToShortString()
5978 + ": task=" + r.task);
5979
5980 // If the next one is a different task, generate a new
5981 // TaskInfo entry for what we have.
5982 if (next == null || next.task != curTask) {
5983 ActivityManager.RunningTaskInfo ci
5984 = new ActivityManager.RunningTaskInfo();
5985 ci.id = curTask.taskId;
5986 ci.baseActivity = r.intent.getComponent();
5987 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005988 if (top.thumbHolder != null) {
5989 ci.description = top.thumbHolder.lastDescription;
5990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 ci.numActivities = numActivities;
5992 ci.numRunning = numRunning;
5993 //System.out.println(
5994 // "#" + maxNum + ": " + " descr=" + ci.description);
5995 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005996 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 TAG, "State=" + top.state + "Idle=" + top.idle
5998 + " app=" + top.app
5999 + " thr=" + (top.app != null ? top.app.thread : null));
6000 if (top.state == ActivityState.RESUMED
6001 || top.state == ActivityState.PAUSING) {
6002 if (top.idle && top.app != null
6003 && top.app.thread != null) {
6004 topRecord = top;
6005 topThumbnail = top.app.thread;
6006 } else {
6007 top.thumbnailNeeded = true;
6008 }
6009 }
6010 if (pending == null) {
6011 pending = new PendingThumbnailsRecord(receiver);
6012 }
6013 pending.pendingRecords.add(top);
6014 }
6015 list.add(ci);
6016 maxNum--;
6017 top = null;
6018 }
6019 }
6020
6021 if (pending != null) {
6022 mPendingThumbnails.add(pending);
6023 }
6024 }
6025
Joe Onorato8a9b2202010-02-26 18:56:32 -08006026 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027
6028 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006029 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08006031 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006033 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006034 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 }
6036 }
6037
6038 if (pending == null && receiver != null) {
6039 // In this case all thumbnails were available and the client
6040 // is being asked to be told when the remaining ones come in...
6041 // which is unusually, since the top-most currently running
6042 // activity should never have a canned thumbnail! Oh well.
6043 try {
6044 receiver.finished();
6045 } catch (RemoteException ex) {
6046 }
6047 }
6048
6049 return list;
6050 }
6051
6052 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
6053 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006054 final int callingUid = Binder.getCallingUid();
6055 // If it's the system uid asking, then use the current user id.
6056 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
6057 // require the entire list.
6058 final int callingUserId = callingUid == Process.SYSTEM_UID
6059 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 synchronized (this) {
6061 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
6062 "getRecentTasks()");
6063
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006064 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07006065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 final int N = mRecentTasks.size();
6067 ArrayList<ActivityManager.RecentTaskInfo> res
6068 = new ArrayList<ActivityManager.RecentTaskInfo>(
6069 maxNum < N ? maxNum : N);
6070 for (int i=0; i<N && maxNum > 0; i++) {
6071 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07006072 // Only add calling user's recent tasks
6073 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07006074 // Return the entry if desired by the caller. We always return
6075 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07006076 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07006077 // not supplied RECENT_WITH_EXCLUDED and there is some reason
6078 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07006079
Dianne Hackborn905577f2011-09-07 18:31:28 -07006080 if (i == 0
6081 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 || (tr.intent == null)
6083 || ((tr.intent.getFlags()
6084 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
6085 ActivityManager.RecentTaskInfo rti
6086 = new ActivityManager.RecentTaskInfo();
6087 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08006088 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 rti.baseIntent = new Intent(
6090 tr.intent != null ? tr.intent : tr.affinityIntent);
6091 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08006092 rti.description = tr.lastDescription;
6093
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07006094 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
6095 // Check whether this activity is currently available.
6096 try {
6097 if (rti.origActivity != null) {
6098 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
6099 continue;
6100 }
6101 } else if (rti.baseIntent != null) {
6102 if (pm.queryIntentActivities(rti.baseIntent,
6103 null, 0) == null) {
6104 continue;
6105 }
6106 }
6107 } catch (RemoteException e) {
6108 // Will never happen.
6109 }
6110 }
6111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006112 res.add(rti);
6113 maxNum--;
6114 }
6115 }
6116 return res;
6117 }
6118 }
6119
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006120 private TaskRecord taskForIdLocked(int id) {
6121 final int N = mRecentTasks.size();
6122 for (int i=0; i<N; i++) {
6123 TaskRecord tr = mRecentTasks.get(i);
6124 if (tr.taskId == id) {
6125 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08006126 }
6127 }
6128 return null;
6129 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006130
6131 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
6132 synchronized (this) {
6133 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
6134 "getTaskThumbnails()");
6135 TaskRecord tr = taskForIdLocked(id);
6136 if (tr != null) {
6137 return mMainStack.getTaskThumbnailsLocked(tr);
6138 }
6139 }
6140 return null;
6141 }
6142
6143 public boolean removeSubTask(int taskId, int subTaskIndex) {
6144 synchronized (this) {
6145 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
6146 "removeSubTask()");
6147 long ident = Binder.clearCallingIdentity();
6148 try {
6149 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
6150 } finally {
6151 Binder.restoreCallingIdentity(ident);
6152 }
6153 }
6154 }
6155
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006156 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006157 TaskRecord tr = root.task;
6158 Intent baseIntent = new Intent(
6159 tr.intent != null ? tr.intent : tr.affinityIntent);
6160 ComponentName component = baseIntent.getComponent();
6161 if (component == null) {
6162 Slog.w(TAG, "Now component for base intent of task: " + tr);
6163 return;
6164 }
6165
6166 // Find any running services associated with this app.
6167 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07006168 for (ServiceRecord sr : mServiceMap.getAllServices(root.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006169 if (sr.packageName.equals(component.getPackageName())) {
6170 services.add(sr);
6171 }
6172 }
6173
6174 // Take care of any running services associated with the app.
6175 for (int i=0; i<services.size(); i++) {
6176 ServiceRecord sr = services.get(i);
6177 if (sr.startRequested) {
6178 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006179 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006180 stopServiceLocked(sr);
6181 } else {
6182 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
6183 sr.makeNextStartId(), baseIntent, -1));
6184 if (sr.app != null && sr.app.thread != null) {
6185 sendServiceArgsLocked(sr, false);
6186 }
6187 }
6188 }
6189 }
6190
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006191 if (killProcesses) {
6192 // Find any running processes associated with this app.
6193 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
6194 SparseArray<ProcessRecord> appProcs
6195 = mProcessNames.getMap().get(component.getPackageName());
6196 if (appProcs != null) {
6197 for (int i=0; i<appProcs.size(); i++) {
6198 procs.add(appProcs.valueAt(i));
6199 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006200 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006201
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006202 // Kill the running processes.
6203 for (int i=0; i<procs.size(); i++) {
6204 ProcessRecord pr = procs.get(i);
6205 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
6206 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
6207 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
6208 pr.processName, pr.setAdj, "remove task");
6209 Process.killProcessQuiet(pr.pid);
6210 } else {
6211 pr.waitingToKill = "remove task";
6212 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006213 }
6214 }
6215 }
6216
6217 public boolean removeTask(int taskId, int flags) {
6218 synchronized (this) {
6219 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
6220 "removeTask()");
6221 long ident = Binder.clearCallingIdentity();
6222 try {
6223 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
6224 if (r != null) {
6225 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006226 cleanUpRemovedTaskLocked(r,
6227 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006228 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07006229 } else {
6230 TaskRecord tr = null;
6231 int i=0;
6232 while (i < mRecentTasks.size()) {
6233 TaskRecord t = mRecentTasks.get(i);
6234 if (t.taskId == taskId) {
6235 tr = t;
6236 break;
6237 }
6238 i++;
6239 }
6240 if (tr != null) {
6241 if (tr.numActivities <= 0) {
6242 // Caller is just removing a recent task that is
6243 // not actively running. That is easy!
6244 mRecentTasks.remove(i);
6245 } else {
6246 Slog.w(TAG, "removeTask: task " + taskId
6247 + " does not have activities to remove, "
6248 + " but numActivities=" + tr.numActivities
6249 + ": " + tr);
6250 }
6251 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006252 }
6253 } finally {
6254 Binder.restoreCallingIdentity(ident);
6255 }
6256 }
6257 return false;
6258 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08006259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
6261 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006262 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 TaskRecord jt = startTask;
6264
6265 // First look backwards
6266 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006267 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 if (r.task != jt) {
6269 jt = r.task;
6270 if (affinity.equals(jt.affinity)) {
6271 return j;
6272 }
6273 }
6274 }
6275
6276 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006277 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 jt = startTask;
6279 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006280 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 if (r.task != jt) {
6282 if (affinity.equals(jt.affinity)) {
6283 return j;
6284 }
6285 jt = r.task;
6286 }
6287 }
6288
6289 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006290 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 return N-1;
6292 }
6293
6294 return -1;
6295 }
6296
6297 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006298 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006300 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006301 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6302 "moveTaskToFront()");
6303
6304 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006305 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6306 Binder.getCallingUid(), "Task to front")) {
6307 return;
6308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 final long origId = Binder.clearCallingIdentity();
6310 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006311 TaskRecord tr = taskForIdLocked(task);
6312 if (tr != null) {
6313 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6314 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006316 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6317 // Caller wants the home activity moved with it. To accomplish this,
6318 // we'll just move the home task to the top first.
6319 mMainStack.moveHomeToFrontLocked();
6320 }
6321 mMainStack.moveTaskToFrontLocked(tr, null);
6322 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006324 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6325 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006326 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006327 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6328 mMainStack.mUserLeaving = true;
6329 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006330 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6331 // Caller wants the home activity moved with it. To accomplish this,
6332 // we'll just move the home task to the top first.
6333 mMainStack.moveHomeToFrontLocked();
6334 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006335 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 return;
6337 }
6338 }
6339 } finally {
6340 Binder.restoreCallingIdentity(origId);
6341 }
6342 }
6343 }
6344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 public void moveTaskToBack(int task) {
6346 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6347 "moveTaskToBack()");
6348
6349 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006350 if (mMainStack.mResumedActivity != null
6351 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006352 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6353 Binder.getCallingUid(), "Task to back")) {
6354 return;
6355 }
6356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006358 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 Binder.restoreCallingIdentity(origId);
6360 }
6361 }
6362
6363 /**
6364 * Moves an activity, and all of the other activities within the same task, to the bottom
6365 * of the history stack. The activity's order within the task is unchanged.
6366 *
6367 * @param token A reference to the activity we wish to move
6368 * @param nonRoot If false then this only works if the activity is the root
6369 * of a task; if true it will work for any activity in a task.
6370 * @return Returns true if the move completed, false if not.
6371 */
6372 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
6373 synchronized(this) {
6374 final long origId = Binder.clearCallingIdentity();
6375 int taskId = getTaskForActivityLocked(token, !nonRoot);
6376 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006377 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 }
6379 Binder.restoreCallingIdentity(origId);
6380 }
6381 return false;
6382 }
6383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 public void moveTaskBackwards(int task) {
6385 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6386 "moveTaskBackwards()");
6387
6388 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006389 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6390 Binder.getCallingUid(), "Task backwards")) {
6391 return;
6392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 final long origId = Binder.clearCallingIdentity();
6394 moveTaskBackwardsLocked(task);
6395 Binder.restoreCallingIdentity(origId);
6396 }
6397 }
6398
6399 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006400 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 }
6402
6403 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6404 synchronized(this) {
6405 return getTaskForActivityLocked(token, onlyRoot);
6406 }
6407 }
6408
6409 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006410 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 TaskRecord lastTask = null;
6412 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006413 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006414 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 if (!onlyRoot || lastTask != r.task) {
6416 return r.task.taskId;
6417 }
6418 return -1;
6419 }
6420 lastTask = r.task;
6421 }
6422
6423 return -1;
6424 }
6425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 public void finishOtherInstances(IBinder token, ComponentName className) {
6427 synchronized(this) {
6428 final long origId = Binder.clearCallingIdentity();
6429
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006430 int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 TaskRecord lastTask = null;
6432 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006433 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 if (r.realActivity.equals(className)
Dianne Hackbornbe707852011-11-11 14:32:10 -08006435 && r.appToken != token && lastTask != r.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006436 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437 null, "others")) {
6438 i--;
6439 N--;
6440 }
6441 }
6442 lastTask = r.task;
6443 }
6444
6445 Binder.restoreCallingIdentity(origId);
6446 }
6447 }
6448
6449 // =========================================================
6450 // THUMBNAILS
6451 // =========================================================
6452
6453 public void reportThumbnail(IBinder token,
6454 Bitmap thumbnail, CharSequence description) {
6455 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6456 final long origId = Binder.clearCallingIdentity();
6457 sendPendingThumbnail(null, token, thumbnail, description, true);
6458 Binder.restoreCallingIdentity(origId);
6459 }
6460
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006461 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 Bitmap thumbnail, CharSequence description, boolean always) {
6463 TaskRecord task = null;
6464 ArrayList receivers = null;
6465
6466 //System.out.println("Send pending thumbnail: " + r);
6467
6468 synchronized(this) {
6469 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006470 r = mMainStack.isInStackLocked(token);
6471 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 return;
6473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006475 if (thumbnail == null && r.thumbHolder != null) {
6476 thumbnail = r.thumbHolder.lastThumbnail;
6477 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 }
6479 if (thumbnail == null && !always) {
6480 // If there is no thumbnail, and this entry is not actually
6481 // going away, then abort for now and pick up the next
6482 // thumbnail we get.
6483 return;
6484 }
6485 task = r.task;
6486
6487 int N = mPendingThumbnails.size();
6488 int i=0;
6489 while (i<N) {
6490 PendingThumbnailsRecord pr =
6491 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6492 //System.out.println("Looking in " + pr.pendingRecords);
6493 if (pr.pendingRecords.remove(r)) {
6494 if (receivers == null) {
6495 receivers = new ArrayList();
6496 }
6497 receivers.add(pr);
6498 if (pr.pendingRecords.size() == 0) {
6499 pr.finished = true;
6500 mPendingThumbnails.remove(i);
6501 N--;
6502 continue;
6503 }
6504 }
6505 i++;
6506 }
6507 }
6508
6509 if (receivers != null) {
6510 final int N = receivers.size();
6511 for (int i=0; i<N; i++) {
6512 try {
6513 PendingThumbnailsRecord pr =
6514 (PendingThumbnailsRecord)receivers.get(i);
6515 pr.receiver.newThumbnail(
6516 task != null ? task.taskId : -1, thumbnail, description);
6517 if (pr.finished) {
6518 pr.receiver.finished();
6519 }
6520 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006521 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 }
6523 }
6524 }
6525 }
6526
6527 // =========================================================
6528 // CONTENT PROVIDERS
6529 // =========================================================
6530
Jeff Brown10e89712011-07-08 18:52:57 -07006531 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6532 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006534 providers = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 queryContentProviders(app.processName, app.info.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006536 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 } catch (RemoteException ex) {
6538 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006539 if (DEBUG_MU)
6540 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.info.uid);
6541 int userId = UserId.getUserId(app.info.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006542 if (providers != null) {
6543 final int N = providers.size();
6544 for (int i=0; i<N; i++) {
6545 ProviderInfo cpi =
6546 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07006547
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006548 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006549 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 if (cpr == null) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006551 cpr = new ContentProviderRecord(cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07006552 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006553 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006554 if (DEBUG_MU)
6555 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006556 app.pubProviders.put(cpi.name, cpr);
6557 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006558 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559 }
6560 }
6561 return providers;
6562 }
6563
6564 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006565 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
6567 final int callingUid = (r != null) ? r.info.uid : Binder.getCallingUid();
6568 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006569 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006570 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 return null;
6572 }
6573 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006574 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006575 == PackageManager.PERMISSION_GRANTED) {
6576 return null;
6577 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006578
6579 PathPermission[] pps = cpi.pathPermissions;
6580 if (pps != null) {
6581 int i = pps.length;
6582 while (i > 0) {
6583 i--;
6584 PathPermission pp = pps[i];
6585 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006586 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006587 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006588 return null;
6589 }
6590 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006591 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006592 == PackageManager.PERMISSION_GRANTED) {
6593 return null;
6594 }
6595 }
6596 }
6597
Dianne Hackbornb424b632010-08-18 15:59:05 -07006598 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6599 if (perms != null) {
6600 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6601 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6602 return null;
6603 }
6604 }
6605 }
6606
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006607 String msg;
6608 if (!cpi.exported) {
6609 msg = "Permission Denial: opening provider " + cpi.name
6610 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6611 + ", uid=" + callingUid + ") that is not exported from uid "
6612 + cpi.applicationInfo.uid;
6613 } else {
6614 msg = "Permission Denial: opening provider " + cpi.name
6615 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6616 + ", uid=" + callingUid + ") requires "
6617 + cpi.readPermission + " or " + cpi.writePermission;
6618 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006619 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 return msg;
6621 }
6622
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006623 boolean incProviderCount(ProcessRecord r, ContentProviderRecord cpr) {
6624 if (r != null) {
6625 Integer cnt = r.conProviders.get(cpr);
6626 if (DEBUG_PROVIDER) Slog.v(TAG,
6627 "Adding provider requested by "
6628 + r.processName + " from process "
6629 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6630 + " cnt=" + (cnt == null ? 1 : cnt));
6631 if (cnt == null) {
6632 cpr.clients.add(r);
6633 r.conProviders.put(cpr, new Integer(1));
6634 return true;
6635 } else {
6636 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6637 }
6638 } else {
6639 cpr.externals++;
6640 }
6641 return false;
6642 }
6643
6644 boolean decProviderCount(ProcessRecord r, ContentProviderRecord cpr) {
6645 if (r != null) {
6646 Integer cnt = r.conProviders.get(cpr);
6647 if (DEBUG_PROVIDER) Slog.v(TAG,
6648 "Removing provider requested by "
6649 + r.processName + " from process "
6650 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6651 + " cnt=" + cnt);
6652 if (cnt == null || cnt.intValue() <= 1) {
6653 cpr.clients.remove(r);
6654 r.conProviders.remove(cpr);
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
Amith Yamasani742a6712011-05-04 14:49:28 -07006665 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
6666 String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 ContentProviderRecord cpr;
6668 ProviderInfo cpi = null;
6669
6670 synchronized(this) {
6671 ProcessRecord r = null;
6672 if (caller != null) {
6673 r = getRecordForAppLocked(caller);
6674 if (r == null) {
6675 throw new SecurityException(
6676 "Unable to find app for caller " + caller
6677 + " (pid=" + Binder.getCallingPid()
6678 + ") when getting content provider " + name);
6679 }
6680 }
6681
6682 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006683 int userId = UserId.getUserId(r != null ? r.info.uid : Binder.getCallingUid());
6684 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006685 boolean providerRunning = cpr != null;
6686 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006688 String msg;
6689 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6690 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006691 }
6692
6693 if (r != null && cpr.canRunHere(r)) {
6694 // This provider has been published or is in the process
6695 // of being published... but it is also allowed to run
6696 // in the caller's process, so don't make a connection
6697 // and just let the caller instantiate its own instance.
6698 if (cpr.provider != null) {
6699 // don't give caller the provider object, it needs
6700 // to make its own.
6701 cpr = new ContentProviderRecord(cpr);
6702 }
6703 return cpr;
6704 }
6705
6706 final long origId = Binder.clearCallingIdentity();
6707
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006708 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709 // return it right away.
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006710 final boolean countChanged = incProviderCount(r, cpr);
6711 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006712 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006713 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006714 // make sure to count it as being accessed and thus
6715 // back up on the LRU list. This is good because
6716 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006717 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006718 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006719 }
6720
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006721 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006722 if (false) {
6723 if (cpr.name.flattenToShortString().equals(
6724 "com.android.providers.calendar/.CalendarProvider2")) {
6725 Slog.v(TAG, "****************** KILLING "
6726 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006727 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006728 }
6729 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006730 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006731 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6732 // NOTE: there is still a race here where a signal could be
6733 // pending on the process even though we managed to update its
6734 // adj level. Not sure what to do about this, but at least
6735 // the race is now smaller.
6736 if (!success) {
6737 // Uh oh... it looks like the provider's process
6738 // has been killed on us. We need to wait for a new
6739 // process to be started, and make sure its death
6740 // doesn't kill our process.
6741 Slog.i(TAG,
6742 "Existing provider " + cpr.name.flattenToShortString()
6743 + " is crashing; detaching " + r);
6744 boolean lastRef = decProviderCount(r, cpr);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006745 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006746 if (!lastRef) {
6747 // This wasn't the last ref our process had on
6748 // the provider... we have now been killed, bail.
6749 return null;
6750 }
6751 providerRunning = false;
6752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006753 }
6754
6755 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006757
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006758 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006760 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006761 resolveContentProvider(name,
6762 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 } catch (RemoteException ex) {
6764 }
6765 if (cpi == null) {
6766 return null;
6767 }
6768
Amith Yamasani742a6712011-05-04 14:49:28 -07006769 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
6770 Binder.getOrigCallingUser());
6771
Dianne Hackbornb424b632010-08-18 15:59:05 -07006772 String msg;
6773 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6774 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 }
6776
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006777 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006778 && !cpi.processName.equals("system")) {
6779 // If this content provider does not run in the system
6780 // process, and the system is not yet ready to run other
6781 // processes, then fail fast instead of hanging.
6782 throw new IllegalArgumentException(
6783 "Attempt to launch content provider before system ready");
6784 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006785
6786 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006787 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006788 final boolean firstClass = cpr == null;
6789 if (firstClass) {
6790 try {
6791 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006792 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006793 getApplicationInfo(
6794 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006795 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006797 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006798 + cpi.name);
6799 return null;
6800 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006801 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006802 cpr = new ContentProviderRecord(cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006803 } catch (RemoteException ex) {
6804 // pm is in same process, this will never happen.
6805 }
6806 }
6807
6808 if (r != null && cpr.canRunHere(r)) {
6809 // If this is a multiprocess provider, then just return its
6810 // info and allow the caller to instantiate it. Only do
6811 // this if the provider is the same user as the caller's
6812 // process, or can run as root (so can be in any process).
6813 return cpr;
6814 }
6815
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006816 if (DEBUG_PROVIDER) {
6817 RuntimeException e = new RuntimeException("here");
Joe Onorato8a9b2202010-02-26 18:56:32 -08006818 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.info.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006819 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006820 }
6821
6822 // This is single process, and our app is now connecting to it.
6823 // See if we are already in the process of launching this
6824 // provider.
6825 final int N = mLaunchingProviders.size();
6826 int i;
6827 for (i=0; i<N; i++) {
6828 if (mLaunchingProviders.get(i) == cpr) {
6829 break;
6830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006831 }
6832
6833 // If the provider is not already being launched, then get it
6834 // started.
6835 if (i >= N) {
6836 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006837
6838 try {
6839 // Content provider is now in use, its package can't be stopped.
6840 try {
6841 AppGlobals.getPackageManager().setPackageStoppedState(
6842 cpr.appInfo.packageName, false);
6843 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006844 } catch (IllegalArgumentException e) {
6845 Slog.w(TAG, "Failed trying to unstop package "
6846 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006847 }
6848
6849 ProcessRecord proc = startProcessLocked(cpi.processName,
6850 cpr.appInfo, false, 0, "content provider",
6851 new ComponentName(cpi.applicationInfo.packageName,
6852 cpi.name), false);
6853 if (proc == null) {
6854 Slog.w(TAG, "Unable to launch app "
6855 + cpi.applicationInfo.packageName + "/"
6856 + cpi.applicationInfo.uid + " for provider "
6857 + name + ": process is bad");
6858 return null;
6859 }
6860 cpr.launchingApp = proc;
6861 mLaunchingProviders.add(cpr);
6862 } finally {
6863 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 }
6866
6867 // Make sure the provider is published (the same provider class
6868 // may be published under multiple names).
6869 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006870 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006871 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006872 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006873 incProviderCount(r, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 }
6875 }
6876
6877 // Wait for the provider to be published...
6878 synchronized (cpr) {
6879 while (cpr.provider == null) {
6880 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006881 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006882 + cpi.applicationInfo.packageName + "/"
6883 + cpi.applicationInfo.uid + " for provider "
6884 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006885 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 cpi.applicationInfo.packageName,
6887 cpi.applicationInfo.uid, name);
6888 return null;
6889 }
6890 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006891 if (DEBUG_MU) {
6892 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6893 + cpr.launchingApp);
6894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006895 cpr.wait();
6896 } catch (InterruptedException ex) {
6897 }
6898 }
6899 }
6900 return cpr;
6901 }
6902
6903 public final ContentProviderHolder getContentProvider(
6904 IApplicationThread caller, String name) {
6905 if (caller == null) {
6906 String msg = "null IApplicationThread when getting content provider "
6907 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006908 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 throw new SecurityException(msg);
6910 }
6911
Amith Yamasani742a6712011-05-04 14:49:28 -07006912 ContentProviderHolder contentProvider = getContentProviderImpl(caller, name);
6913 return contentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006914 }
6915
6916 private ContentProviderHolder getContentProviderExternal(String name) {
6917 return getContentProviderImpl(null, name);
6918 }
6919
6920 /**
6921 * Drop a content provider from a ProcessRecord's bookkeeping
6922 * @param cpr
6923 */
6924 public void removeContentProvider(IApplicationThread caller, String name) {
6925 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006926 int userId = UserId.getUserId(Binder.getCallingUid());
6927 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006928 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006929 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006930 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006931 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006932 return;
6933 }
6934 final ProcessRecord r = getRecordForAppLocked(caller);
6935 if (r == null) {
6936 throw new SecurityException(
6937 "Unable to find app for caller " + caller +
6938 " when removing content provider " + name);
6939 }
6940 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006941 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006942 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6943 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6944 + r.info.processName + " from process "
6945 + localCpr.appInfo.processName);
6946 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006948 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006949 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 return;
6951 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006952 if (decProviderCount(r, localCpr)) {
6953 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006956 }
6957 }
6958
6959 private void removeContentProviderExternal(String name) {
6960 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006961 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6962 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006963 if(cpr == null) {
6964 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006965 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006966 return;
6967 }
6968
6969 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006970 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006971 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6972 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973 localCpr.externals--;
6974 if (localCpr.externals < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006975 Slog.e(TAG, "Externals < 0 for content provider " + localCpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006976 }
6977 updateOomAdjLocked();
6978 }
6979 }
6980
6981 public final void publishContentProviders(IApplicationThread caller,
6982 List<ContentProviderHolder> providers) {
6983 if (providers == null) {
6984 return;
6985 }
6986
6987 synchronized(this) {
6988 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006989 if (DEBUG_MU)
6990 Slog.v(TAG_MU, "ProcessRecord uid = " + r.info.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006991 if (r == null) {
6992 throw new SecurityException(
6993 "Unable to find app for caller " + caller
6994 + " (pid=" + Binder.getCallingPid()
6995 + ") when publishing content providers");
6996 }
6997
6998 final long origId = Binder.clearCallingIdentity();
6999
7000 final int N = providers.size();
7001 for (int i=0; i<N; i++) {
7002 ContentProviderHolder src = providers.get(i);
7003 if (src == null || src.info == null || src.provider == null) {
7004 continue;
7005 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07007006 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07007007 if (DEBUG_MU)
7008 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007009 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07007010 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07007011 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007012 String names[] = dst.info.authority.split(";");
7013 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07007014 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 }
7016
7017 int NL = mLaunchingProviders.size();
7018 int j;
7019 for (j=0; j<NL; j++) {
7020 if (mLaunchingProviders.get(j) == dst) {
7021 mLaunchingProviders.remove(j);
7022 j--;
7023 NL--;
7024 }
7025 }
7026 synchronized (dst) {
7027 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07007028 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007029 dst.notifyAll();
7030 }
7031 updateOomAdjLocked(r);
7032 }
7033 }
7034
7035 Binder.restoreCallingIdentity(origId);
7036 }
7037 }
7038
7039 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07007040 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06007041 synchronized (mSelf) {
7042 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
7043 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08007044 if (providers != null) {
7045 for (int i=providers.size()-1; i>=0; i--) {
7046 ProviderInfo pi = (ProviderInfo)providers.get(i);
7047 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7048 Slog.w(TAG, "Not installing system proc provider " + pi.name
7049 + ": not system .apk");
7050 providers.remove(i);
7051 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08007052 }
7053 }
7054 }
Josh Bartel2ecce342010-02-25 10:55:48 -06007055 if (providers != null) {
7056 mSystemThread.installSystemProviders(providers);
7057 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007058
7059 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01007060
7061 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007062 }
7063
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007064 /**
7065 * Allows app to retrieve the MIME type of a URI without having permission
7066 * to access its content provider.
7067 *
7068 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
7069 *
7070 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
7071 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
7072 */
7073 public String getProviderMimeType(Uri uri) {
7074 final String name = uri.getAuthority();
7075 final long ident = Binder.clearCallingIdentity();
7076 ContentProviderHolder holder = null;
7077
7078 try {
7079 holder = getContentProviderExternal(name);
7080 if (holder != null) {
7081 return holder.provider.getType(uri);
7082 }
7083 } catch (RemoteException e) {
7084 Log.w(TAG, "Content provider dead retrieving " + uri, e);
7085 return null;
7086 } finally {
7087 if (holder != null) {
7088 removeContentProviderExternal(name);
7089 }
7090 Binder.restoreCallingIdentity(ident);
7091 }
7092
7093 return null;
7094 }
7095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007096 // =========================================================
7097 // GLOBAL MANAGEMENT
7098 // =========================================================
7099
7100 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
7101 ApplicationInfo info, String customProcess) {
7102 String proc = customProcess != null ? customProcess : info.processName;
7103 BatteryStatsImpl.Uid.Proc ps = null;
7104 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7105 synchronized (stats) {
7106 ps = stats.getProcessStatsLocked(info.uid, proc);
7107 }
7108 return new ProcessRecord(ps, thread, info, proc);
7109 }
7110
7111 final ProcessRecord addAppLocked(ApplicationInfo info) {
7112 ProcessRecord app = getProcessRecordLocked(info.processName, info.uid);
7113
7114 if (app == null) {
7115 app = newProcessRecordLocked(null, info, null);
7116 mProcessNames.put(info.processName, info.uid, app);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007117 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 }
7119
Dianne Hackborne7f97212011-02-24 14:40:20 -08007120 // This package really, really can not be stopped.
7121 try {
7122 AppGlobals.getPackageManager().setPackageStoppedState(
7123 info.packageName, false);
7124 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007125 } catch (IllegalArgumentException e) {
7126 Slog.w(TAG, "Failed trying to unstop package "
7127 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007128 }
7129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007130 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7131 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7132 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007133 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007134 }
7135 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7136 mPersistentStartingProcesses.add(app);
7137 startProcessLocked(app, "added application", app.processName);
7138 }
7139
7140 return app;
7141 }
7142
7143 public void unhandledBack() {
7144 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7145 "unhandledBack()");
7146
7147 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007148 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007149 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007150 TAG, "Performing unhandledBack(): stack size = " + count);
7151 if (count > 1) {
7152 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007153 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007154 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
7155 Binder.restoreCallingIdentity(origId);
7156 }
7157 }
7158 }
7159
7160 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
7161 String name = uri.getAuthority();
7162 ContentProviderHolder cph = getContentProviderExternal(name);
7163 ParcelFileDescriptor pfd = null;
7164 if (cph != null) {
7165 // We record the binder invoker's uid in thread-local storage before
7166 // going to the content provider to open the file. Later, in the code
7167 // that handles all permissions checks, we look for this uid and use
7168 // that rather than the Activity Manager's own uid. The effect is that
7169 // we do the check against the caller's permissions even though it looks
7170 // to the content provider like the Activity Manager itself is making
7171 // the request.
7172 sCallerIdentity.set(new Identity(
7173 Binder.getCallingPid(), Binder.getCallingUid()));
7174 try {
7175 pfd = cph.provider.openFile(uri, "r");
7176 } catch (FileNotFoundException e) {
7177 // do nothing; pfd will be returned null
7178 } finally {
7179 // Ensure that whatever happens, we clean up the identity state
7180 sCallerIdentity.remove();
7181 }
7182
7183 // We've got the fd now, so we're done with the provider.
7184 removeContentProviderExternal(name);
7185 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007186 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 }
7188 return pfd;
7189 }
7190
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007191 // Actually is sleeping or shutting down or whatever else in the future
7192 // is an inactive state.
7193 public boolean isSleeping() {
7194 return mSleeping || mShuttingDown;
7195 }
7196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 public void goingToSleep() {
7198 synchronized(this) {
7199 mSleeping = true;
7200 mWindowManager.setEventDispatching(false);
7201
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007202 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007203
7204 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07007205 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007206 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7207 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07007208 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007209 }
7210 }
7211
Dianne Hackborn55280a92009-05-07 15:53:46 -07007212 public boolean shutdown(int timeout) {
7213 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7214 != PackageManager.PERMISSION_GRANTED) {
7215 throw new SecurityException("Requires permission "
7216 + android.Manifest.permission.SHUTDOWN);
7217 }
7218
7219 boolean timedout = false;
7220
7221 synchronized(this) {
7222 mShuttingDown = true;
7223 mWindowManager.setEventDispatching(false);
7224
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007225 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007226 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007227 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007228 while (mMainStack.mResumedActivity != null
Dianne Hackborncbb722e2012-02-07 18:33:49 -08007229 || mMainStack.mPausingActivities.size() > 0) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007230 long delay = endTime - System.currentTimeMillis();
7231 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007232 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007233 timedout = true;
7234 break;
7235 }
7236 try {
7237 this.wait();
7238 } catch (InterruptedException e) {
7239 }
7240 }
7241 }
7242 }
7243
7244 mUsageStatsService.shutdown();
7245 mBatteryStatsService.shutdown();
7246
7247 return timedout;
7248 }
7249
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007250 public final void activitySlept(IBinder token) {
7251 if (localLOGV) Slog.v(
7252 TAG, "Activity slept: token=" + token);
7253
7254 ActivityRecord r = null;
7255
7256 final long origId = Binder.clearCallingIdentity();
7257
7258 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007259 r = mMainStack.isInStackLocked(token);
7260 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007261 mMainStack.activitySleptLocked(r);
7262 }
7263 }
7264
7265 Binder.restoreCallingIdentity(origId);
7266 }
7267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007268 public void wakingUp() {
7269 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007270 mWindowManager.setEventDispatching(true);
7271 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007272 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007273 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007274 }
7275 }
7276
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007277 public void stopAppSwitches() {
7278 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7279 != PackageManager.PERMISSION_GRANTED) {
7280 throw new SecurityException("Requires permission "
7281 + android.Manifest.permission.STOP_APP_SWITCHES);
7282 }
7283
7284 synchronized(this) {
7285 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7286 + APP_SWITCH_DELAY_TIME;
7287 mDidAppSwitch = false;
7288 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7289 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7290 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7291 }
7292 }
7293
7294 public void resumeAppSwitches() {
7295 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7296 != PackageManager.PERMISSION_GRANTED) {
7297 throw new SecurityException("Requires permission "
7298 + android.Manifest.permission.STOP_APP_SWITCHES);
7299 }
7300
7301 synchronized(this) {
7302 // Note that we don't execute any pending app switches... we will
7303 // let those wait until either the timeout, or the next start
7304 // activity request.
7305 mAppSwitchesAllowedTime = 0;
7306 }
7307 }
7308
7309 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7310 String name) {
7311 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7312 return true;
7313 }
7314
7315 final int perm = checkComponentPermission(
7316 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007317 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007318 if (perm == PackageManager.PERMISSION_GRANTED) {
7319 return true;
7320 }
7321
Joe Onorato8a9b2202010-02-26 18:56:32 -08007322 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007323 return false;
7324 }
7325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 public void setDebugApp(String packageName, boolean waitForDebugger,
7327 boolean persistent) {
7328 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7329 "setDebugApp()");
7330
7331 // Note that this is not really thread safe if there are multiple
7332 // callers into it at the same time, but that's not a situation we
7333 // care about.
7334 if (persistent) {
7335 final ContentResolver resolver = mContext.getContentResolver();
7336 Settings.System.putString(
7337 resolver, Settings.System.DEBUG_APP,
7338 packageName);
7339 Settings.System.putInt(
7340 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7341 waitForDebugger ? 1 : 0);
7342 }
7343
7344 synchronized (this) {
7345 if (!persistent) {
7346 mOrigDebugApp = mDebugApp;
7347 mOrigWaitForDebugger = mWaitForDebugger;
7348 }
7349 mDebugApp = packageName;
7350 mWaitForDebugger = waitForDebugger;
7351 mDebugTransient = !persistent;
7352 if (packageName != null) {
7353 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07007354 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007355 Binder.restoreCallingIdentity(origId);
7356 }
7357 }
7358 }
7359
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007360 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7361 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7362 synchronized (this) {
7363 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7364 if (!isDebuggable) {
7365 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7366 throw new SecurityException("Process not debuggable: " + app.packageName);
7367 }
7368 }
7369 mProfileApp = processName;
7370 mProfileFile = profileFile;
7371 if (mProfileFd != null) {
7372 try {
7373 mProfileFd.close();
7374 } catch (IOException e) {
7375 }
7376 mProfileFd = null;
7377 }
7378 mProfileFd = profileFd;
7379 mProfileType = 0;
7380 mAutoStopProfiler = autoStopProfiler;
7381 }
7382 }
7383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007384 public void setAlwaysFinish(boolean enabled) {
7385 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7386 "setAlwaysFinish()");
7387
7388 Settings.System.putInt(
7389 mContext.getContentResolver(),
7390 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7391
7392 synchronized (this) {
7393 mAlwaysFinishActivities = enabled;
7394 }
7395 }
7396
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007397 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007398 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007399 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007400 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007401 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007402 }
7403 }
7404
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007405 public boolean isUserAMonkey() {
7406 // For now the fact that there is a controller implies
7407 // we have a monkey.
7408 synchronized (this) {
7409 return mController != null;
7410 }
7411 }
7412
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007413 public void registerActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06007414 synchronized (this) {
7415 mWatchers.register(watcher);
7416 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007417 }
7418
7419 public void unregisterActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06007420 synchronized (this) {
7421 mWatchers.unregister(watcher);
7422 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007423 }
7424
Jeff Sharkeya4620792011-05-20 15:29:23 -07007425 public void registerProcessObserver(IProcessObserver observer) {
7426 mProcessObservers.register(observer);
7427 }
7428
7429 public void unregisterProcessObserver(IProcessObserver observer) {
7430 mProcessObservers.unregister(observer);
7431 }
7432
Daniel Sandler69a48172010-06-23 16:29:36 -04007433 public void setImmersive(IBinder token, boolean immersive) {
7434 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007435 ActivityRecord r = mMainStack.isInStackLocked(token);
7436 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007437 throw new IllegalArgumentException();
7438 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007439 r.immersive = immersive;
7440 }
7441 }
7442
7443 public boolean isImmersive(IBinder token) {
7444 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007445 ActivityRecord r = mMainStack.isInStackLocked(token);
7446 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007447 throw new IllegalArgumentException();
7448 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007449 return r.immersive;
7450 }
7451 }
7452
7453 public boolean isTopActivityImmersive() {
7454 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007455 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007456 return (r != null) ? r.immersive : false;
7457 }
7458 }
7459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007460 public final void enterSafeMode() {
7461 synchronized(this) {
7462 // It only makes sense to do this before the system is ready
7463 // and started launching other packages.
7464 if (!mSystemReady) {
7465 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007466 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007467 } catch (RemoteException e) {
7468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007469 }
7470 }
7471 }
7472
Jeff Brownb09abc12011-01-13 21:08:27 -08007473 public final void showSafeModeOverlay() {
7474 View v = LayoutInflater.from(mContext).inflate(
7475 com.android.internal.R.layout.safe_mode, null);
7476 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7477 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7478 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7479 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7480 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7481 lp.format = v.getBackground().getOpacity();
7482 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7483 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7484 ((WindowManager)mContext.getSystemService(
7485 Context.WINDOW_SERVICE)).addView(v, lp);
7486 }
7487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007488 public void noteWakeupAlarm(IIntentSender sender) {
7489 if (!(sender instanceof PendingIntentRecord)) {
7490 return;
7491 }
7492 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7493 synchronized (stats) {
7494 if (mBatteryStatsService.isOnBattery()) {
7495 mBatteryStatsService.enforceCallingPermission();
7496 PendingIntentRecord rec = (PendingIntentRecord)sender;
7497 int MY_UID = Binder.getCallingUid();
7498 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7499 BatteryStatsImpl.Uid.Pkg pkg =
7500 stats.getPackageStatsLocked(uid, rec.key.packageName);
7501 pkg.incWakeupsLocked();
7502 }
7503 }
7504 }
7505
Dianne Hackborn64825172011-03-02 21:32:58 -08007506 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007508 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007510 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007511 // XXX Note: don't acquire main activity lock here, because the window
7512 // manager calls in with its locks held.
7513
7514 boolean killed = false;
7515 synchronized (mPidsSelfLocked) {
7516 int[] types = new int[pids.length];
7517 int worstType = 0;
7518 for (int i=0; i<pids.length; i++) {
7519 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7520 if (proc != null) {
7521 int type = proc.setAdj;
7522 types[i] = type;
7523 if (type > worstType) {
7524 worstType = type;
7525 }
7526 }
7527 }
7528
Dianne Hackborn64825172011-03-02 21:32:58 -08007529 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007530 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007531 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7532 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007533 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007534 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007535
7536 // If this is not a secure call, don't let it kill processes that
7537 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007538 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7539 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007540 }
7541
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007542 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007543 for (int i=0; i<pids.length; i++) {
7544 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7545 if (proc == null) {
7546 continue;
7547 }
7548 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007549 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007550 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007551 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7552 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007553 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007554 proc.killedBackground = true;
7555 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007556 }
7557 }
7558 }
7559 return killed;
7560 }
7561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 public final void startRunning(String pkg, String cls, String action,
7563 String data) {
7564 synchronized(this) {
7565 if (mStartRunning) {
7566 return;
7567 }
7568 mStartRunning = true;
7569 mTopComponent = pkg != null && cls != null
7570 ? new ComponentName(pkg, cls) : null;
7571 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7572 mTopData = data;
7573 if (!mSystemReady) {
7574 return;
7575 }
7576 }
7577
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007578 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007579 }
7580
7581 private void retrieveSettings() {
7582 final ContentResolver resolver = mContext.getContentResolver();
7583 String debugApp = Settings.System.getString(
7584 resolver, Settings.System.DEBUG_APP);
7585 boolean waitForDebugger = Settings.System.getInt(
7586 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7587 boolean alwaysFinishActivities = Settings.System.getInt(
7588 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7589
7590 Configuration configuration = new Configuration();
7591 Settings.System.getConfiguration(resolver, configuration);
7592
7593 synchronized (this) {
7594 mDebugApp = mOrigDebugApp = debugApp;
7595 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7596 mAlwaysFinishActivities = alwaysFinishActivities;
7597 // This happens before any activities are started, so we can
7598 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007599 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007600 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601 }
7602 }
7603
7604 public boolean testIsSystemReady() {
7605 // no need to synchronize(this) just to read & return the value
7606 return mSystemReady;
7607 }
7608
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007609 private static File getCalledPreBootReceiversFile() {
7610 File dataDir = Environment.getDataDirectory();
7611 File systemDir = new File(dataDir, "system");
7612 File fname = new File(systemDir, "called_pre_boots.dat");
7613 return fname;
7614 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007615
7616 static final int LAST_DONE_VERSION = 10000;
7617
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007618 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7619 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7620 File file = getCalledPreBootReceiversFile();
7621 FileInputStream fis = null;
7622 try {
7623 fis = new FileInputStream(file);
7624 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007625 int fvers = dis.readInt();
7626 if (fvers == LAST_DONE_VERSION) {
7627 String vers = dis.readUTF();
7628 String codename = dis.readUTF();
7629 String build = dis.readUTF();
7630 if (android.os.Build.VERSION.RELEASE.equals(vers)
7631 && android.os.Build.VERSION.CODENAME.equals(codename)
7632 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7633 int num = dis.readInt();
7634 while (num > 0) {
7635 num--;
7636 String pkg = dis.readUTF();
7637 String cls = dis.readUTF();
7638 lastDoneReceivers.add(new ComponentName(pkg, cls));
7639 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007640 }
7641 }
7642 } catch (FileNotFoundException e) {
7643 } catch (IOException e) {
7644 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7645 } finally {
7646 if (fis != null) {
7647 try {
7648 fis.close();
7649 } catch (IOException e) {
7650 }
7651 }
7652 }
7653 return lastDoneReceivers;
7654 }
7655
7656 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7657 File file = getCalledPreBootReceiversFile();
7658 FileOutputStream fos = null;
7659 DataOutputStream dos = null;
7660 try {
7661 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7662 fos = new FileOutputStream(file);
7663 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007664 dos.writeInt(LAST_DONE_VERSION);
7665 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007666 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007667 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007668 dos.writeInt(list.size());
7669 for (int i=0; i<list.size(); i++) {
7670 dos.writeUTF(list.get(i).getPackageName());
7671 dos.writeUTF(list.get(i).getClassName());
7672 }
7673 } catch (IOException e) {
7674 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7675 file.delete();
7676 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007677 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007678 if (dos != null) {
7679 try {
7680 dos.close();
7681 } catch (IOException e) {
7682 // TODO Auto-generated catch block
7683 e.printStackTrace();
7684 }
7685 }
7686 }
7687 }
7688
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007689 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 synchronized(this) {
7691 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007692 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007693 return;
7694 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007695
7696 // Check to see if there are any update receivers to run.
7697 if (!mDidUpdate) {
7698 if (mWaitingUpdate) {
7699 return;
7700 }
7701 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7702 List<ResolveInfo> ris = null;
7703 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007704 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007705 intent, null, 0);
7706 } catch (RemoteException e) {
7707 }
7708 if (ris != null) {
7709 for (int i=ris.size()-1; i>=0; i--) {
7710 if ((ris.get(i).activityInfo.applicationInfo.flags
7711 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7712 ris.remove(i);
7713 }
7714 }
7715 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007716
7717 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7718
7719 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007720 for (int i=0; i<ris.size(); i++) {
7721 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007722 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7723 if (lastDoneReceivers.contains(comp)) {
7724 ris.remove(i);
7725 i--;
7726 }
7727 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007728
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007729 for (int i=0; i<ris.size(); i++) {
7730 ActivityInfo ai = ris.get(i).activityInfo;
7731 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7732 doneReceivers.add(comp);
7733 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007734 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007735 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007736 finisher = new IIntentReceiver.Stub() {
7737 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007738 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007739 boolean sticky) {
7740 // The raw IIntentReceiver interface is called
7741 // with the AM lock held, so redispatch to
7742 // execute our code without the lock.
7743 mHandler.post(new Runnable() {
7744 public void run() {
7745 synchronized (ActivityManagerService.this) {
7746 mDidUpdate = true;
7747 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007748 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007749 showBootMessage(mContext.getText(
7750 R.string.android_upgrading_complete),
7751 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007752 systemReady(goingCallback);
7753 }
7754 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007755 }
7756 };
7757 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007758 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007759 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007760 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007761 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7762 Process.SYSTEM_UID);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007763 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007764 mWaitingUpdate = true;
7765 }
7766 }
7767 }
7768 if (mWaitingUpdate) {
7769 return;
7770 }
7771 mDidUpdate = true;
7772 }
7773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 mSystemReady = true;
7775 if (!mStartRunning) {
7776 return;
7777 }
7778 }
7779
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007780 ArrayList<ProcessRecord> procsToKill = null;
7781 synchronized(mPidsSelfLocked) {
7782 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7783 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7784 if (!isAllowedWhileBooting(proc.info)){
7785 if (procsToKill == null) {
7786 procsToKill = new ArrayList<ProcessRecord>();
7787 }
7788 procsToKill.add(proc);
7789 }
7790 }
7791 }
7792
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007793 synchronized(this) {
7794 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007795 for (int i=procsToKill.size()-1; i>=0; i--) {
7796 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007797 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007798 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007799 }
7800 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007801
7802 // Now that we have cleaned up any update processes, we
7803 // are ready to start launching real processes and know that
7804 // we won't trample on them any more.
7805 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007806 }
7807
Joe Onorato8a9b2202010-02-26 18:56:32 -08007808 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007809 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007810 SystemClock.uptimeMillis());
7811
7812 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007813 // Make sure we have no pre-ready processes sitting around.
7814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7816 ResolveInfo ri = mContext.getPackageManager()
7817 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007818 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007819 CharSequence errorMsg = null;
7820 if (ri != null) {
7821 ActivityInfo ai = ri.activityInfo;
7822 ApplicationInfo app = ai.applicationInfo;
7823 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7824 mTopAction = Intent.ACTION_FACTORY_TEST;
7825 mTopData = null;
7826 mTopComponent = new ComponentName(app.packageName,
7827 ai.name);
7828 } else {
7829 errorMsg = mContext.getResources().getText(
7830 com.android.internal.R.string.factorytest_not_system);
7831 }
7832 } else {
7833 errorMsg = mContext.getResources().getText(
7834 com.android.internal.R.string.factorytest_no_action);
7835 }
7836 if (errorMsg != null) {
7837 mTopAction = null;
7838 mTopData = null;
7839 mTopComponent = null;
7840 Message msg = Message.obtain();
7841 msg.what = SHOW_FACTORY_ERROR_MSG;
7842 msg.getData().putCharSequence("msg", errorMsg);
7843 mHandler.sendMessage(msg);
7844 }
7845 }
7846 }
7847
7848 retrieveSettings();
7849
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007850 if (goingCallback != null) goingCallback.run();
7851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 synchronized (this) {
7853 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7854 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007855 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007856 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 if (apps != null) {
7858 int N = apps.size();
7859 int i;
7860 for (i=0; i<N; i++) {
7861 ApplicationInfo info
7862 = (ApplicationInfo)apps.get(i);
7863 if (info != null &&
7864 !info.packageName.equals("android")) {
7865 addAppLocked(info);
7866 }
7867 }
7868 }
7869 } catch (RemoteException ex) {
7870 // pm is in same process, this will never happen.
7871 }
7872 }
7873
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007874 // Start up initial activity.
7875 mBooting = true;
7876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007877 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007878 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 Message msg = Message.obtain();
7880 msg.what = SHOW_UID_ERROR_MSG;
7881 mHandler.sendMessage(msg);
7882 }
7883 } catch (RemoteException e) {
7884 }
7885
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007886 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 }
7888 }
7889
Dan Egnorb7f03672009-12-09 16:22:32 -08007890 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007891 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007893 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007894 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 startAppProblemLocked(app);
7896 app.stopFreezingAllLocked();
7897 return handleAppCrashLocked(app);
7898 }
7899
Dan Egnorb7f03672009-12-09 16:22:32 -08007900 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007901 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007902 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007903 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007904 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7905 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 startAppProblemLocked(app);
7907 app.stopFreezingAllLocked();
7908 }
7909
7910 /**
7911 * Generate a process error record, suitable for attachment to a ProcessRecord.
7912 *
7913 * @param app The ProcessRecord in which the error occurred.
7914 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7915 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007916 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 * @param shortMsg Short message describing the crash.
7918 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007919 * @param stackTrace Full crash stack trace, may be null.
7920 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 * @return Returns a fully-formed AppErrorStateInfo record.
7922 */
7923 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007924 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007925 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927 report.condition = condition;
7928 report.processName = app.processName;
7929 report.pid = app.pid;
7930 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007931 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007932 report.shortMsg = shortMsg;
7933 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007934 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007935
7936 return report;
7937 }
7938
Dan Egnor42471dd2010-01-07 17:25:22 -08007939 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007940 synchronized (this) {
7941 app.crashing = false;
7942 app.crashingReport = null;
7943 app.notResponding = false;
7944 app.notRespondingReport = null;
7945 if (app.anrDialog == fromDialog) {
7946 app.anrDialog = null;
7947 }
7948 if (app.waitDialog == fromDialog) {
7949 app.waitDialog = null;
7950 }
7951 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007952 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007953 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007954 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7955 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007956 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007958 }
7959 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007960
Dan Egnorb7f03672009-12-09 16:22:32 -08007961 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007962 long now = SystemClock.uptimeMillis();
7963
7964 Long crashTime = mProcessCrashTimes.get(app.info.processName,
7965 app.info.uid);
Dianne Hackborn7d608422011-08-07 16:24:18 -07007966 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007967 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007968 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007969 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007970 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 app.info.processName, app.info.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007972 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7973 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007975 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007976 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007977 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007978 }
7979 }
7980 if (!app.persistent) {
7981 // We don't want to start this process again until the user
7982 // explicitly does so... but for persistent process, we really
7983 // need to keep it running. If a persistent process is actually
7984 // repeatedly crashing, then badness for everyone.
Doug Zongker2bec3d42009-12-04 12:52:44 -08007985 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 app.info.processName);
7987 mBadProcesses.put(app.info.processName, app.info.uid, now);
7988 app.bad = true;
7989 mProcessCrashTimes.remove(app.info.processName, app.info.uid);
7990 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007991 // Don't let services in this process be restarted and potentially
7992 // annoy the user repeatedly. Unless it is persistent, since those
7993 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007994 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007995 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 return false;
7997 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007998 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007999 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008000 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008001 if (r.app == app) {
8002 // If the top running activity is from this crashing
8003 // process, then terminate it to avoid getting in a loop.
8004 Slog.w(TAG, " Force finishing activity "
8005 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008006 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008007 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008008 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08008009 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008010 // stopped, to avoid a situation where one will get
8011 // re-start our crashing activity once it gets resumed again.
8012 index--;
8013 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008014 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008015 if (r.state == ActivityState.RESUMED
8016 || r.state == ActivityState.PAUSING
8017 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008018 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008019 Slog.w(TAG, " Force finishing activity "
8020 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008021 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008022 Activity.RESULT_CANCELED, null, "crashed");
8023 }
8024 }
8025 }
8026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 }
8028
8029 // Bump up the crash count of any services currently running in the proc.
8030 if (app.services.size() != 0) {
8031 // Any services running in the application need to be placed
8032 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008033 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008035 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008036 sr.crashCount++;
8037 }
8038 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008039
8040 // If the crashing process is what we consider to be the "home process" and it has been
8041 // replaced by a third-party app, clear the package preferred activities from packages
8042 // with a home activity running in the process to prevent a repeatedly crashing app
8043 // from blocking the user to manually clear the list.
8044 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8045 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8046 Iterator it = mHomeProcess.activities.iterator();
8047 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008048 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008049 if (r.isHomeActivity) {
8050 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8051 try {
8052 ActivityThread.getPackageManager()
8053 .clearPackagePreferredActivities(r.packageName);
8054 } catch (RemoteException c) {
8055 // pm is in same process, this will never happen.
8056 }
8057 }
8058 }
8059 }
8060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008061 mProcessCrashTimes.put(app.info.processName, app.info.uid, now);
8062 return true;
8063 }
8064
8065 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008066 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8067 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008068 skipCurrentReceiverLocked(app);
8069 }
8070
8071 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008072 for (BroadcastQueue queue : mBroadcastQueues) {
8073 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 }
8075 }
8076
Dan Egnor60d87622009-12-16 16:32:58 -08008077 /**
8078 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8079 * The application process will exit immediately after this call returns.
8080 * @param app object of the crashing app, null for the system server
8081 * @param crashInfo describing the exception
8082 */
8083 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008084 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008085 final String processName = app == null ? "system_server"
8086 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008087
8088 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008089 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008090 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008091 crashInfo.exceptionClassName,
8092 crashInfo.exceptionMessage,
8093 crashInfo.throwFileName,
8094 crashInfo.throwLineNumber);
8095
Jeff Sharkeya353d262011-10-28 11:12:06 -07008096 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008097
8098 crashApplication(r, crashInfo);
8099 }
8100
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008101 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008102 IBinder app,
8103 int violationMask,
8104 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008105 ProcessRecord r = findAppProcess(app, "StrictMode");
8106 if (r == null) {
8107 return;
8108 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008109
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008110 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008111 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008112 boolean logIt = true;
8113 synchronized (mAlreadyLoggedViolatedStacks) {
8114 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8115 logIt = false;
8116 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008117 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008118 // the relative pain numbers, without logging all
8119 // the stack traces repeatedly. We'd want to do
8120 // likewise in the client code, which also does
8121 // dup suppression, before the Binder call.
8122 } else {
8123 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8124 mAlreadyLoggedViolatedStacks.clear();
8125 }
8126 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8127 }
8128 }
8129 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008130 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008131 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008132 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008133
8134 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8135 AppErrorResult result = new AppErrorResult();
8136 synchronized (this) {
8137 final long origId = Binder.clearCallingIdentity();
8138
8139 Message msg = Message.obtain();
8140 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8141 HashMap<String, Object> data = new HashMap<String, Object>();
8142 data.put("result", result);
8143 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008144 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008145 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008146 msg.obj = data;
8147 mHandler.sendMessage(msg);
8148
8149 Binder.restoreCallingIdentity(origId);
8150 }
8151 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008152 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008153 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008154 }
8155
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008156 // Depending on the policy in effect, there could be a bunch of
8157 // these in quick succession so we try to batch these together to
8158 // minimize disk writes, number of dropbox entries, and maximize
8159 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008160 private void logStrictModeViolationToDropBox(
8161 ProcessRecord process,
8162 StrictMode.ViolationInfo info) {
8163 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008164 return;
8165 }
8166 final boolean isSystemApp = process == null ||
8167 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8168 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008169 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008170 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8171 final DropBoxManager dbox = (DropBoxManager)
8172 mContext.getSystemService(Context.DROPBOX_SERVICE);
8173
8174 // Exit early if the dropbox isn't configured to accept this report type.
8175 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8176
8177 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008178 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008179 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8180 synchronized (sb) {
8181 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008182 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008183 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8184 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008185 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8186 if (info.violationNumThisLoop != 0) {
8187 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8188 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008189 if (info.numAnimationsRunning != 0) {
8190 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8191 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008192 if (info.broadcastIntentAction != null) {
8193 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8194 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008195 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008196 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008197 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008198 if (info.numInstances != -1) {
8199 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8200 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008201 if (info.tags != null) {
8202 for (String tag : info.tags) {
8203 sb.append("Span-Tag: ").append(tag).append("\n");
8204 }
8205 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008206 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008207 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8208 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008209 }
8210 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008211
8212 // Only buffer up to ~64k. Various logging bits truncate
8213 // things at 128k.
8214 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008215 }
8216
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008217 // Flush immediately if the buffer's grown too large, or this
8218 // is a non-system app. Non-system apps are isolated with a
8219 // different tag & policy and not batched.
8220 //
8221 // Batching is useful during internal testing with
8222 // StrictMode settings turned up high. Without batching,
8223 // thousands of separate files could be created on boot.
8224 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008225 new Thread("Error dump: " + dropboxTag) {
8226 @Override
8227 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008228 String report;
8229 synchronized (sb) {
8230 report = sb.toString();
8231 sb.delete(0, sb.length());
8232 sb.trimToSize();
8233 }
8234 if (report.length() != 0) {
8235 dbox.addText(dropboxTag, report);
8236 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008237 }
8238 }.start();
8239 return;
8240 }
8241
8242 // System app batching:
8243 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008244 // An existing dropbox-writing thread is outstanding, so
8245 // we don't need to start it up. The existing thread will
8246 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008247 return;
8248 }
8249
8250 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8251 // (After this point, we shouldn't access AMS internal data structures.)
8252 new Thread("Error dump: " + dropboxTag) {
8253 @Override
8254 public void run() {
8255 // 5 second sleep to let stacks arrive and be batched together
8256 try {
8257 Thread.sleep(5000); // 5 seconds
8258 } catch (InterruptedException e) {}
8259
8260 String errorReport;
8261 synchronized (mStrictModeBuffer) {
8262 errorReport = mStrictModeBuffer.toString();
8263 if (errorReport.length() == 0) {
8264 return;
8265 }
8266 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8267 mStrictModeBuffer.trimToSize();
8268 }
8269 dbox.addText(dropboxTag, errorReport);
8270 }
8271 }.start();
8272 }
8273
Dan Egnor60d87622009-12-16 16:32:58 -08008274 /**
8275 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8276 * @param app object of the crashing app, null for the system server
8277 * @param tag reported by the caller
8278 * @param crashInfo describing the context of the error
8279 * @return true if the process should exit immediately (WTF is fatal)
8280 */
8281 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008282 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008283 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008284 final String processName = app == null ? "system_server"
8285 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008286
8287 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008288 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008289 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008290 tag, crashInfo.exceptionMessage);
8291
Jeff Sharkeya353d262011-10-28 11:12:06 -07008292 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008293
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008294 if (r != null && r.pid != Process.myPid() &&
8295 Settings.Secure.getInt(mContext.getContentResolver(),
8296 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008297 crashApplication(r, crashInfo);
8298 return true;
8299 } else {
8300 return false;
8301 }
8302 }
8303
8304 /**
8305 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8306 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8307 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008308 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008309 if (app == null) {
8310 return null;
8311 }
8312
8313 synchronized (this) {
8314 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8315 final int NA = apps.size();
8316 for (int ia=0; ia<NA; ia++) {
8317 ProcessRecord p = apps.valueAt(ia);
8318 if (p.thread != null && p.thread.asBinder() == app) {
8319 return p;
8320 }
8321 }
8322 }
8323
Dianne Hackborncb44d962011-03-10 17:02:27 -08008324 Slog.w(TAG, "Can't find mystery application for " + reason
8325 + " from pid=" + Binder.getCallingPid()
8326 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008327 return null;
8328 }
8329 }
8330
8331 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008332 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8333 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008334 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008335 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8336 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008337 // Watchdog thread ends up invoking this function (with
8338 // a null ProcessRecord) to add the stack file to dropbox.
8339 // Do not acquire a lock on this (am) in such cases, as it
8340 // could cause a potential deadlock, if and when watchdog
8341 // is invoked due to unavailability of lock on am and it
8342 // would prevent watchdog from killing system_server.
8343 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008344 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008345 return;
8346 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008347 // Note: ProcessRecord 'process' is guarded by the service
8348 // instance. (notably process.pkgList, which could otherwise change
8349 // concurrently during execution of this method)
8350 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008351 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008352 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008353 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008354 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8355 for (String pkg : process.pkgList) {
8356 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008357 try {
Dan Egnora455d192010-03-12 08:52:28 -08008358 PackageInfo pi = pm.getPackageInfo(pkg, 0);
8359 if (pi != null) {
8360 sb.append(" v").append(pi.versionCode);
8361 if (pi.versionName != null) {
8362 sb.append(" (").append(pi.versionName).append(")");
8363 }
8364 }
8365 } catch (RemoteException e) {
8366 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008367 }
Dan Egnora455d192010-03-12 08:52:28 -08008368 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008369 }
Dan Egnora455d192010-03-12 08:52:28 -08008370 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008371 }
8372
8373 private static String processClass(ProcessRecord process) {
8374 if (process == null || process.pid == MY_PID) {
8375 return "system_server";
8376 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8377 return "system_app";
8378 } else {
8379 return "data_app";
8380 }
8381 }
8382
8383 /**
8384 * Write a description of an error (crash, WTF, ANR) to the drop box.
8385 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8386 * @param process which caused the error, null means the system server
8387 * @param activity which triggered the error, null if unknown
8388 * @param parent activity related to the error, null if unknown
8389 * @param subject line related to the error, null if absent
8390 * @param report in long form describing the error, null if absent
8391 * @param logFile to include in the report, null if none
8392 * @param crashInfo giving an application stack trace, null if absent
8393 */
8394 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008395 ProcessRecord process, String processName, ActivityRecord activity,
8396 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008397 final String report, final File logFile,
8398 final ApplicationErrorReport.CrashInfo crashInfo) {
8399 // NOTE -- this must never acquire the ActivityManagerService lock,
8400 // otherwise the watchdog may be prevented from resetting the system.
8401
8402 final String dropboxTag = processClass(process) + "_" + eventType;
8403 final DropBoxManager dbox = (DropBoxManager)
8404 mContext.getSystemService(Context.DROPBOX_SERVICE);
8405
8406 // Exit early if the dropbox isn't configured to accept this report type.
8407 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8408
8409 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008410 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008411 if (activity != null) {
8412 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8413 }
8414 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8415 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8416 }
8417 if (parent != null && parent != activity) {
8418 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8419 }
8420 if (subject != null) {
8421 sb.append("Subject: ").append(subject).append("\n");
8422 }
8423 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008424 if (Debug.isDebuggerConnected()) {
8425 sb.append("Debugger: Connected\n");
8426 }
Dan Egnora455d192010-03-12 08:52:28 -08008427 sb.append("\n");
8428
8429 // Do the rest in a worker thread to avoid blocking the caller on I/O
8430 // (After this point, we shouldn't access AMS internal data structures.)
8431 Thread worker = new Thread("Error dump: " + dropboxTag) {
8432 @Override
8433 public void run() {
8434 if (report != null) {
8435 sb.append(report);
8436 }
8437 if (logFile != null) {
8438 try {
8439 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8440 } catch (IOException e) {
8441 Slog.e(TAG, "Error reading " + logFile, e);
8442 }
8443 }
8444 if (crashInfo != null && crashInfo.stackTrace != null) {
8445 sb.append(crashInfo.stackTrace);
8446 }
8447
8448 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8449 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8450 if (lines > 0) {
8451 sb.append("\n");
8452
8453 // Merge several logcat streams, and take the last N lines
8454 InputStreamReader input = null;
8455 try {
8456 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8457 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8458 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8459
8460 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8461 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8462 input = new InputStreamReader(logcat.getInputStream());
8463
8464 int num;
8465 char[] buf = new char[8192];
8466 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8467 } catch (IOException e) {
8468 Slog.e(TAG, "Error running logcat", e);
8469 } finally {
8470 if (input != null) try { input.close(); } catch (IOException e) {}
8471 }
8472 }
8473
8474 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008475 }
Dan Egnora455d192010-03-12 08:52:28 -08008476 };
8477
8478 if (process == null || process.pid == MY_PID) {
8479 worker.run(); // We may be about to die -- need to run this synchronously
8480 } else {
8481 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008482 }
8483 }
8484
8485 /**
8486 * Bring up the "unexpected error" dialog box for a crashing app.
8487 * Deal with edge cases (intercepts from instrumented applications,
8488 * ActivityController, error intent receivers, that sort of thing).
8489 * @param r the application crashing
8490 * @param crashInfo describing the failure
8491 */
8492 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008493 long timeMillis = System.currentTimeMillis();
8494 String shortMsg = crashInfo.exceptionClassName;
8495 String longMsg = crashInfo.exceptionMessage;
8496 String stackTrace = crashInfo.stackTrace;
8497 if (shortMsg != null && longMsg != null) {
8498 longMsg = shortMsg + ": " + longMsg;
8499 } else if (shortMsg != null) {
8500 longMsg = shortMsg;
8501 }
8502
Dan Egnor60d87622009-12-16 16:32:58 -08008503 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008505 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 try {
8507 String name = r != null ? r.processName : null;
8508 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008509 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008510 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008511 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008512 + " at watcher's request");
8513 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008514 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008515 }
8516 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008517 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008518 }
8519 }
8520
8521 final long origId = Binder.clearCallingIdentity();
8522
8523 // If this process is running instrumentation, finish it.
8524 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008525 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008526 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008527 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8528 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008529 Bundle info = new Bundle();
8530 info.putString("shortMsg", shortMsg);
8531 info.putString("longMsg", longMsg);
8532 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8533 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008534 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008535 }
8536
Dan Egnor60d87622009-12-16 16:32:58 -08008537 // If we can't identify the process or it's already exceeded its crash quota,
8538 // quit right away without showing a crash dialog.
8539 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008540 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008541 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008542 }
8543
8544 Message msg = Message.obtain();
8545 msg.what = SHOW_ERROR_MSG;
8546 HashMap data = new HashMap();
8547 data.put("result", result);
8548 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008549 msg.obj = data;
8550 mHandler.sendMessage(msg);
8551
8552 Binder.restoreCallingIdentity(origId);
8553 }
8554
8555 int res = result.get();
8556
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008557 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008558 synchronized (this) {
8559 if (r != null) {
8560 mProcessCrashTimes.put(r.info.processName, r.info.uid,
8561 SystemClock.uptimeMillis());
8562 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008563 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008564 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008565 }
8566 }
8567
8568 if (appErrorIntent != null) {
8569 try {
8570 mContext.startActivity(appErrorIntent);
8571 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008572 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008575 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008576
8577 Intent createAppErrorIntentLocked(ProcessRecord r,
8578 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8579 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008580 if (report == null) {
8581 return null;
8582 }
8583 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8584 result.setComponent(r.errorReportReceiver);
8585 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8586 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8587 return result;
8588 }
8589
Dan Egnorb7f03672009-12-09 16:22:32 -08008590 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8591 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008592 if (r.errorReportReceiver == null) {
8593 return null;
8594 }
8595
8596 if (!r.crashing && !r.notResponding) {
8597 return null;
8598 }
8599
Dan Egnorb7f03672009-12-09 16:22:32 -08008600 ApplicationErrorReport report = new ApplicationErrorReport();
8601 report.packageName = r.info.packageName;
8602 report.installerPackageName = r.errorReportReceiver.getPackageName();
8603 report.processName = r.processName;
8604 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008605 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008606
Dan Egnorb7f03672009-12-09 16:22:32 -08008607 if (r.crashing) {
8608 report.type = ApplicationErrorReport.TYPE_CRASH;
8609 report.crashInfo = crashInfo;
8610 } else if (r.notResponding) {
8611 report.type = ApplicationErrorReport.TYPE_ANR;
8612 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008613
Dan Egnorb7f03672009-12-09 16:22:32 -08008614 report.anrInfo.activity = r.notRespondingReport.tag;
8615 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8616 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008617 }
8618
Dan Egnorb7f03672009-12-09 16:22:32 -08008619 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008620 }
8621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
8623 // assume our apps are happy - lazy create the list
8624 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8625
8626 synchronized (this) {
8627
8628 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008629 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8630 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008631 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8632 // This one's in trouble, so we'll generate a report for it
8633 // crashes are higher priority (in case there's a crash *and* an anr)
8634 ActivityManager.ProcessErrorStateInfo report = null;
8635 if (app.crashing) {
8636 report = app.crashingReport;
8637 } else if (app.notResponding) {
8638 report = app.notRespondingReport;
8639 }
8640
8641 if (report != null) {
8642 if (errList == null) {
8643 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8644 }
8645 errList.add(report);
8646 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008647 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008648 " crashing = " + app.crashing +
8649 " notResponding = " + app.notResponding);
8650 }
8651 }
8652 }
8653 }
8654
8655 return errList;
8656 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008657
8658 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008659 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008660 if (currApp != null) {
8661 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8662 }
8663 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008664 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8665 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008666 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8667 if (currApp != null) {
8668 currApp.lru = 0;
8669 }
8670 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008671 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008672 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8673 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8674 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8675 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8676 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8677 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8678 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8679 } else {
8680 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8681 }
8682 }
8683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
8685 // Lazy instantiation of list
8686 List<ActivityManager.RunningAppProcessInfo> runList = null;
8687 synchronized (this) {
8688 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008689 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8690 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008691 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8692 // Generate process state info for running application
8693 ActivityManager.RunningAppProcessInfo currApp =
8694 new ActivityManager.RunningAppProcessInfo(app.processName,
8695 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07008696 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07008697 if (mHeavyWeightProcess == app) {
Dianne Hackborn482566e2010-09-03 12:51:28 -07008698 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07008699 }
Dianne Hackborn42499172010-10-15 18:45:07 -07008700 if (app.persistent) {
8701 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008703 int adj = app.curAdj;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008704 currApp.importance = oomAdjToImportance(adj, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008705 currApp.importanceReasonCode = app.adjTypeCode;
8706 if (app.adjSource instanceof ProcessRecord) {
8707 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008708 currApp.importanceReasonImportance = oomAdjToImportance(
8709 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008710 } else if (app.adjSource instanceof ActivityRecord) {
8711 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008712 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8713 }
8714 if (app.adjTarget instanceof ComponentName) {
8715 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8716 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008717 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718 // + " lru=" + currApp.lru);
8719 if (runList == null) {
8720 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8721 }
8722 runList.add(currApp);
8723 }
8724 }
8725 }
8726 return runList;
8727 }
8728
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008729 public List<ApplicationInfo> getRunningExternalApplications() {
8730 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8731 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8732 if (runningApps != null && runningApps.size() > 0) {
8733 Set<String> extList = new HashSet<String>();
8734 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8735 if (app.pkgList != null) {
8736 for (String pkg : app.pkgList) {
8737 extList.add(pkg);
8738 }
8739 }
8740 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008741 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008742 for (String pkg : extList) {
8743 try {
8744 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8745 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8746 retList.add(info);
8747 }
8748 } catch (RemoteException e) {
8749 }
8750 }
8751 }
8752 return retList;
8753 }
8754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008755 @Override
8756 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008757 if (checkCallingPermission(android.Manifest.permission.DUMP)
8758 != PackageManager.PERMISSION_GRANTED) {
8759 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8760 + Binder.getCallingPid()
8761 + ", uid=" + Binder.getCallingUid()
8762 + " without permission "
8763 + android.Manifest.permission.DUMP);
8764 return;
8765 }
8766
8767 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008768 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008769 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008770
8771 int opti = 0;
8772 while (opti < args.length) {
8773 String opt = args[opti];
8774 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8775 break;
8776 }
8777 opti++;
8778 if ("-a".equals(opt)) {
8779 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008780 } else if ("-c".equals(opt)) {
8781 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008782 } else if ("-h".equals(opt)) {
8783 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008784 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008785 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008786 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008787 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8788 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8789 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008790 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008791 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008792 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008793 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008794 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008795 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008796 pw.println(" all: dump all activities");
8797 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008798 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008799 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8800 pw.println(" a partial substring in a component name, a");
8801 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008802 pw.println(" -a: include all available server state.");
8803 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008804 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008805 } else {
8806 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008807 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008808 }
8809
8810 // Is the caller requesting to dump a particular piece of data?
8811 if (opti < args.length) {
8812 String cmd = args[opti];
8813 opti++;
8814 if ("activities".equals(cmd) || "a".equals(cmd)) {
8815 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008816 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008817 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008818 return;
8819 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008820 String[] newArgs;
8821 String name;
8822 if (opti >= args.length) {
8823 name = null;
8824 newArgs = EMPTY_STRING_ARRAY;
8825 } else {
8826 name = args[opti];
8827 opti++;
8828 newArgs = new String[args.length - opti];
8829 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8830 args.length - opti);
8831 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008832 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008833 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008834 }
8835 return;
8836 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008837 String[] newArgs;
8838 String name;
8839 if (opti >= args.length) {
8840 name = null;
8841 newArgs = EMPTY_STRING_ARRAY;
8842 } else {
8843 name = args[opti];
8844 opti++;
8845 newArgs = new String[args.length - opti];
8846 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8847 args.length - opti);
8848 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008849 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008850 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008851 }
8852 return;
8853 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008854 String[] newArgs;
8855 String name;
8856 if (opti >= args.length) {
8857 name = null;
8858 newArgs = EMPTY_STRING_ARRAY;
8859 } else {
8860 name = args[opti];
8861 opti++;
8862 newArgs = new String[args.length - opti];
8863 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8864 args.length - opti);
8865 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008866 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008867 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008868 }
8869 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008870 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8871 synchronized (this) {
8872 dumpOomLocked(fd, pw, args, opti, true);
8873 }
8874 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008875 } else if ("provider".equals(cmd)) {
8876 String[] newArgs;
8877 String name;
8878 if (opti >= args.length) {
8879 name = null;
8880 newArgs = EMPTY_STRING_ARRAY;
8881 } else {
8882 name = args[opti];
8883 opti++;
8884 newArgs = new String[args.length - opti];
8885 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8886 }
8887 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8888 pw.println("No providers match: " + name);
8889 pw.println("Use -h for help.");
8890 }
8891 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008892 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8893 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008894 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008895 }
8896 return;
8897 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008898 String[] newArgs;
8899 String name;
8900 if (opti >= args.length) {
8901 name = null;
8902 newArgs = EMPTY_STRING_ARRAY;
8903 } else {
8904 name = args[opti];
8905 opti++;
8906 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008907 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8908 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008909 }
8910 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8911 pw.println("No services match: " + name);
8912 pw.println("Use -h for help.");
8913 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008914 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008915 } else if ("package".equals(cmd)) {
8916 String[] newArgs;
8917 if (opti >= args.length) {
8918 pw.println("package: no package name specified");
8919 pw.println("Use -h for help.");
8920 return;
8921 } else {
8922 dumpPackage = args[opti];
8923 opti++;
8924 newArgs = new String[args.length - opti];
8925 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8926 args.length - opti);
8927 args = newArgs;
8928 opti = 0;
8929 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008930 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8931 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008932 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008933 }
8934 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008935 } else {
8936 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008937 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8938 pw.println("Bad activity command, or no activities match: " + cmd);
8939 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008940 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008941 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008942 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008943 }
8944
8945 // No piece of data specified, dump everything.
8946 synchronized (this) {
8947 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008948 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008949 if (needSep) {
8950 pw.println(" ");
8951 }
8952 if (dumpAll) {
8953 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008954 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008955 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008956 if (needSep) {
8957 pw.println(" ");
8958 }
8959 if (dumpAll) {
8960 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008961 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008962 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008963 if (needSep) {
8964 pw.println(" ");
8965 }
8966 if (dumpAll) {
8967 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008968 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008969 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008970 if (needSep) {
8971 pw.println(" ");
8972 }
8973 if (dumpAll) {
8974 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008975 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008976 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008977 if (needSep) {
8978 pw.println(" ");
8979 }
8980 if (dumpAll) {
8981 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008982 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008983 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008984 }
8985 }
8986
8987 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008988 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008989 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8990 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008991 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8992 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008993 pw.println(" ");
8994 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008995 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8996 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008997 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008999 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009000 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009001 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009002 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009003 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009004 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009005 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009006 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009007 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009008 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009009 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9010 pw.println(" ");
9011 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009012 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009013 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009014 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009015 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009016 pw.println(" ");
9017 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009018 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009019 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009021
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009022 pw.println(" ");
Dianne Hackborncbb722e2012-02-07 18:33:49 -08009023 if (mMainStack.mPausingActivities.size() > 0) {
9024 pw.println(" mPausingActivities: " + Arrays.toString(
9025 mMainStack.mPausingActivities.toArray()));
9026 }
9027 if (mMainStack.mInputPausedActivities.size() > 0) {
9028 pw.println(" mInputPausedActivities: " + Arrays.toString(
9029 mMainStack.mInputPausedActivities.toArray()));
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009030 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009031 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009032 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009033 if (dumpAll) {
9034 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9035 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009036 pw.println(" mDismissKeyguardOnNextActivity: "
9037 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009039
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009040 if (mRecentTasks.size() > 0) {
9041 pw.println();
9042 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009043
9044 final int N = mRecentTasks.size();
9045 for (int i=0; i<N; i++) {
9046 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009047 if (dumpPackage != null) {
9048 if (tr.realActivity == null ||
9049 !dumpPackage.equals(tr.realActivity)) {
9050 continue;
9051 }
9052 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009053 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9054 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009055 if (dumpAll) {
9056 mRecentTasks.get(i).dump(pw, " ");
9057 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009058 }
9059 }
9060
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009061 if (dumpAll) {
9062 pw.println(" ");
9063 pw.println(" mCurTask: " + mCurTask);
9064 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009065
9066 return true;
9067 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009068
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009069 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009070 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009071 boolean needSep = false;
9072 int numPers = 0;
9073
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009074 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9075
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009076 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009077 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9078 final int NA = procs.size();
9079 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009080 ProcessRecord r = procs.valueAt(ia);
9081 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9082 continue;
9083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 if (!needSep) {
9085 pw.println(" All known processes:");
9086 needSep = true;
9087 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009088 pw.print(r.persistent ? " *PERS*" : " *APP*");
9089 pw.print(" UID "); pw.print(procs.keyAt(ia));
9090 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 r.dump(pw, " ");
9092 if (r.persistent) {
9093 numPers++;
9094 }
9095 }
9096 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009097 }
9098
9099 if (mLruProcesses.size() > 0) {
9100 if (needSep) pw.println(" ");
9101 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009102 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009103 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009104 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009105 needSep = true;
9106 }
9107
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009108 if (dumpAll) {
9109 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009110 boolean printed = false;
9111 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9112 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9113 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9114 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009115 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009116 if (!printed) {
9117 if (needSep) pw.println(" ");
9118 needSep = true;
9119 pw.println(" PID mappings:");
9120 printed = true;
9121 }
9122 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9123 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009124 }
9125 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009126 }
9127
9128 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009129 synchronized (mPidsSelfLocked) {
9130 boolean printed = false;
9131 for (int i=0; i<mForegroundProcesses.size(); i++) {
9132 ProcessRecord r = mPidsSelfLocked.get(
9133 mForegroundProcesses.valueAt(i).pid);
9134 if (dumpPackage != null && (r == null
9135 || !dumpPackage.equals(r.info.packageName))) {
9136 continue;
9137 }
9138 if (!printed) {
9139 if (needSep) pw.println(" ");
9140 needSep = true;
9141 pw.println(" Foreground Processes:");
9142 printed = true;
9143 }
9144 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9145 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009148 }
9149
9150 if (mPersistentStartingProcesses.size() > 0) {
9151 if (needSep) pw.println(" ");
9152 needSep = true;
9153 pw.println(" Persisent processes that are starting:");
9154 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009155 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009157
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009158 if (mRemovedProcesses.size() > 0) {
9159 if (needSep) pw.println(" ");
9160 needSep = true;
9161 pw.println(" Processes that are being removed:");
9162 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009163 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009164 }
9165
9166 if (mProcessesOnHold.size() > 0) {
9167 if (needSep) pw.println(" ");
9168 needSep = true;
9169 pw.println(" Processes that are on old until the system is ready:");
9170 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009171 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009173
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009174 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009175
9176 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009177 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009178 long now = SystemClock.uptimeMillis();
9179 for (Map.Entry<String, SparseArray<Long>> procs
9180 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009181 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009182 SparseArray<Long> uids = procs.getValue();
9183 final int N = uids.size();
9184 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009185 int puid = uids.keyAt(i);
9186 ProcessRecord r = mProcessNames.get(pname, puid);
9187 if (dumpPackage != null && (r == null
9188 || !dumpPackage.equals(r.info.packageName))) {
9189 continue;
9190 }
9191 if (!printed) {
9192 if (needSep) pw.println(" ");
9193 needSep = true;
9194 pw.println(" Time since processes crashed:");
9195 printed = true;
9196 }
9197 pw.print(" Process "); pw.print(pname);
9198 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009199 pw.print(": last crashed ");
9200 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009201 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009202 }
9203 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009205
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009206 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009207 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009208 for (Map.Entry<String, SparseArray<Long>> procs
9209 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009210 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009211 SparseArray<Long> uids = procs.getValue();
9212 final int N = uids.size();
9213 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009214 int puid = uids.keyAt(i);
9215 ProcessRecord r = mProcessNames.get(pname, puid);
9216 if (dumpPackage != null && (r == null
9217 || !dumpPackage.equals(r.info.packageName))) {
9218 continue;
9219 }
9220 if (!printed) {
9221 if (needSep) pw.println(" ");
9222 needSep = true;
9223 pw.println(" Bad processes:");
9224 }
9225 pw.print(" Bad process "); pw.print(pname);
9226 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009227 pw.print(": crashed at time ");
9228 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009229 }
9230 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009232
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009233 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009234 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009235 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009236 if (dumpAll) {
9237 StringBuilder sb = new StringBuilder(128);
9238 sb.append(" mPreviousProcessVisibleTime: ");
9239 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9240 pw.println(sb);
9241 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009242 if (mHeavyWeightProcess != null) {
9243 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9244 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009245 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009246 if (dumpAll) {
9247 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009248 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009249 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009250 for (Map.Entry<String, Integer> entry
9251 : mCompatModePackages.getPackages().entrySet()) {
9252 String pkg = entry.getKey();
9253 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009254 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9255 continue;
9256 }
9257 if (!printed) {
9258 pw.println(" mScreenCompatPackages:");
9259 printed = true;
9260 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009261 pw.print(" "); pw.print(pkg); pw.print(": ");
9262 pw.print(mode); pw.println();
9263 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009264 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009265 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009266 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
9267 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9268 || mOrigWaitForDebugger) {
9269 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9270 + " mDebugTransient=" + mDebugTransient
9271 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9272 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009273 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9274 || mProfileFd != null) {
9275 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9276 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9277 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9278 + mAutoStopProfiler);
9279 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009280 if (mAlwaysFinishActivities || mController != null) {
9281 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9282 + " mController=" + mController);
9283 }
9284 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009285 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009287 + " mProcessesReady=" + mProcessesReady
9288 + " mSystemReady=" + mSystemReady);
9289 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009290 + " mBooted=" + mBooted
9291 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009292 pw.print(" mLastPowerCheckRealtime=");
9293 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9294 pw.println("");
9295 pw.print(" mLastPowerCheckUptime=");
9296 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9297 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009298 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9299 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009300 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009301 pw.println(" mNumServiceProcs=" + mNumServiceProcs
9302 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009304
9305 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009306 }
9307
Dianne Hackborn287952c2010-09-22 22:34:31 -07009308 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009309 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009310 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009311 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009312 long now = SystemClock.uptimeMillis();
9313 for (int i=0; i<mProcessesToGc.size(); i++) {
9314 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009315 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9316 continue;
9317 }
9318 if (!printed) {
9319 if (needSep) pw.println(" ");
9320 needSep = true;
9321 pw.println(" Processes that are waiting to GC:");
9322 printed = true;
9323 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009324 pw.print(" Process "); pw.println(proc);
9325 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9326 pw.print(", last gced=");
9327 pw.print(now-proc.lastRequestedGc);
9328 pw.print(" ms ago, last lowMem=");
9329 pw.print(now-proc.lastLowMemory);
9330 pw.println(" ms ago");
9331
9332 }
9333 }
9334 return needSep;
9335 }
9336
9337 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9338 int opti, boolean dumpAll) {
9339 boolean needSep = false;
9340
9341 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009342 if (needSep) pw.println(" ");
9343 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009344 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009345 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009346 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009347 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9348 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9349 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9350 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9351 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009352 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009353 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009354 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009355 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009356 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009357 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009358
9359 if (needSep) pw.println(" ");
9360 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009361 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009362 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009363 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009364 needSep = true;
9365 }
9366
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009367 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009368
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009369 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009370 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009371 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009372 if (mHeavyWeightProcess != null) {
9373 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9374 }
9375
9376 return true;
9377 }
9378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009379 /**
9380 * There are three ways to call this:
9381 * - no service specified: dump all the services
9382 * - a flattened component name that matched an existing service was specified as the
9383 * first arg: dump that one service
9384 * - the first arg isn't the flattened component name of an existing service:
9385 * dump all services whose component contains the first arg as a substring
9386 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009387 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9388 int opti, boolean dumpAll) {
9389 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009390
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009391 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009392 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009393 try {
9394 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9395 for (UserInfo user : users) {
9396 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9397 services.add(r1);
9398 }
9399 }
9400 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009401 }
9402 }
9403 } else {
9404 ComponentName componentName = name != null
9405 ? ComponentName.unflattenFromString(name) : null;
9406 int objectId = 0;
9407 if (componentName == null) {
9408 // Not a '/' separated full component name; maybe an object ID?
9409 try {
9410 objectId = Integer.parseInt(name, 16);
9411 name = null;
9412 componentName = null;
9413 } catch (RuntimeException e) {
9414 }
9415 }
9416
9417 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009418 try {
9419 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9420 for (UserInfo user : users) {
9421 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9422 if (componentName != null) {
9423 if (r1.name.equals(componentName)) {
9424 services.add(r1);
9425 }
9426 } else if (name != null) {
9427 if (r1.name.flattenToString().contains(name)) {
9428 services.add(r1);
9429 }
9430 } else if (System.identityHashCode(r1) == objectId) {
9431 services.add(r1);
9432 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009433 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009434 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009435 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436 }
9437 }
9438 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009439
9440 if (services.size() <= 0) {
9441 return false;
9442 }
9443
9444 boolean needSep = false;
9445 for (int i=0; i<services.size(); i++) {
9446 if (needSep) {
9447 pw.println();
9448 }
9449 needSep = true;
9450 dumpService("", fd, pw, services.get(i), args, dumpAll);
9451 }
9452 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009453 }
9454
9455 /**
9456 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9457 * there is a thread associated with the service.
9458 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009459 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9460 final ServiceRecord r, String[] args, boolean dumpAll) {
9461 String innerPrefix = prefix + " ";
9462 synchronized (this) {
9463 pw.print(prefix); pw.print("SERVICE ");
9464 pw.print(r.shortName); pw.print(" ");
9465 pw.print(Integer.toHexString(System.identityHashCode(r)));
9466 pw.print(" pid=");
9467 if (r.app != null) pw.println(r.app.pid);
9468 else pw.println("(not running)");
9469 if (dumpAll) {
9470 r.dump(pw, innerPrefix);
9471 }
9472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009473 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009474 pw.print(prefix); pw.println(" Client:");
9475 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009477 TransferPipe tp = new TransferPipe();
9478 try {
9479 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9480 tp.setBufferPrefix(prefix + " ");
9481 tp.go(fd);
9482 } finally {
9483 tp.kill();
9484 }
9485 } catch (IOException e) {
9486 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009487 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009488 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009489 }
9490 }
9491 }
9492
Marco Nelissen18cb2872011-11-15 11:19:53 -08009493 /**
9494 * There are three ways to call this:
9495 * - no provider specified: dump all the providers
9496 * - a flattened component name that matched an existing provider was specified as the
9497 * first arg: dump that one provider
9498 * - the first arg isn't the flattened component name of an existing provider:
9499 * dump all providers whose component contains the first arg as a substring
9500 */
9501 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9502 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009503 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009504 }
9505
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009506 static class ItemMatcher {
9507 ArrayList<ComponentName> components;
9508 ArrayList<String> strings;
9509 ArrayList<Integer> objects;
9510 boolean all;
9511
9512 ItemMatcher() {
9513 all = true;
9514 }
9515
9516 void build(String name) {
9517 ComponentName componentName = ComponentName.unflattenFromString(name);
9518 if (componentName != null) {
9519 if (components == null) {
9520 components = new ArrayList<ComponentName>();
9521 }
9522 components.add(componentName);
9523 all = false;
9524 } else {
9525 int objectId = 0;
9526 // Not a '/' separated full component name; maybe an object ID?
9527 try {
9528 objectId = Integer.parseInt(name, 16);
9529 if (objects == null) {
9530 objects = new ArrayList<Integer>();
9531 }
9532 objects.add(objectId);
9533 all = false;
9534 } catch (RuntimeException e) {
9535 // Not an integer; just do string match.
9536 if (strings == null) {
9537 strings = new ArrayList<String>();
9538 }
9539 strings.add(name);
9540 all = false;
9541 }
9542 }
9543 }
9544
9545 int build(String[] args, int opti) {
9546 for (; opti<args.length; opti++) {
9547 String name = args[opti];
9548 if ("--".equals(name)) {
9549 return opti+1;
9550 }
9551 build(name);
9552 }
9553 return opti;
9554 }
9555
9556 boolean match(Object object, ComponentName comp) {
9557 if (all) {
9558 return true;
9559 }
9560 if (components != null) {
9561 for (int i=0; i<components.size(); i++) {
9562 if (components.get(i).equals(comp)) {
9563 return true;
9564 }
9565 }
9566 }
9567 if (objects != null) {
9568 for (int i=0; i<objects.size(); i++) {
9569 if (System.identityHashCode(object) == objects.get(i)) {
9570 return true;
9571 }
9572 }
9573 }
9574 if (strings != null) {
9575 String flat = comp.flattenToString();
9576 for (int i=0; i<strings.size(); i++) {
9577 if (flat.contains(strings.get(i))) {
9578 return true;
9579 }
9580 }
9581 }
9582 return false;
9583 }
9584 }
9585
Dianne Hackborn625ac272010-09-17 18:29:22 -07009586 /**
9587 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009588 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009589 * - the cmd arg isn't the flattened component name of an existing activity:
9590 * dump all activity whose component contains the cmd as a substring
9591 * - A hex number of the ActivityRecord object instance.
9592 */
9593 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9594 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009595 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009596
9597 if ("all".equals(name)) {
9598 synchronized (this) {
9599 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009600 activities.add(r1);
9601 }
9602 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009603 } else if ("top".equals(name)) {
9604 synchronized (this) {
9605 final int N = mMainStack.mHistory.size();
9606 if (N > 0) {
9607 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9608 }
9609 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009610 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009611 ItemMatcher matcher = new ItemMatcher();
9612 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009613
9614 synchronized (this) {
9615 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009616 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009617 activities.add(r1);
9618 }
9619 }
9620 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009621 }
9622
9623 if (activities.size() <= 0) {
9624 return false;
9625 }
9626
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009627 String[] newArgs = new String[args.length - opti];
9628 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9629
Dianne Hackborn30d71892010-12-11 10:37:55 -08009630 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009631 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009632 for (int i=activities.size()-1; i>=0; i--) {
9633 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009634 if (needSep) {
9635 pw.println();
9636 }
9637 needSep = true;
9638 synchronized (this) {
9639 if (lastTask != r.task) {
9640 lastTask = r.task;
9641 pw.print("TASK "); pw.print(lastTask.affinity);
9642 pw.print(" id="); pw.println(lastTask.taskId);
9643 if (dumpAll) {
9644 lastTask.dump(pw, " ");
9645 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009646 }
9647 }
9648 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009649 }
9650 return true;
9651 }
9652
9653 /**
9654 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9655 * there is a thread associated with the activity.
9656 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009657 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009658 final ActivityRecord r, String[] args, boolean dumpAll) {
9659 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009660 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009661 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9662 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9663 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009664 if (r.app != null) pw.println(r.app.pid);
9665 else pw.println("(not running)");
9666 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009667 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009668 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009669 }
9670 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009671 // flush anything that is already in the PrintWriter since the thread is going
9672 // to write to the file descriptor directly
9673 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009674 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009675 TransferPipe tp = new TransferPipe();
9676 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009677 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9678 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009679 tp.go(fd);
9680 } finally {
9681 tp.kill();
9682 }
9683 } catch (IOException e) {
9684 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009685 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009686 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009687 }
9688 }
9689 }
9690
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009691 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009692 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009693 boolean needSep = false;
9694
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009695 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009696 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009697 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009698 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009699 Iterator it = mRegisteredReceivers.values().iterator();
9700 while (it.hasNext()) {
9701 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009702 if (dumpPackage != null && (r.app == null ||
9703 !dumpPackage.equals(r.app.info.packageName))) {
9704 continue;
9705 }
9706 if (!printed) {
9707 pw.println(" Registered Receivers:");
9708 needSep = true;
9709 printed = true;
9710 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009711 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009712 r.dump(pw, " ");
9713 }
9714 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009715
9716 if (mReceiverResolver.dump(pw, needSep ?
9717 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9718 " ", dumpPackage, false)) {
9719 needSep = true;
9720 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009721 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009722
9723 for (BroadcastQueue q : mBroadcastQueues) {
9724 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009726
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009727 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009728
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009729 if (mStickyBroadcasts != null && dumpPackage == null) {
9730 if (needSep) {
9731 pw.println();
9732 }
9733 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009734 pw.println(" Sticky broadcasts:");
9735 StringBuilder sb = new StringBuilder(128);
9736 for (Map.Entry<String, ArrayList<Intent>> ent
9737 : mStickyBroadcasts.entrySet()) {
9738 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009739 if (dumpAll) {
9740 pw.println(":");
9741 ArrayList<Intent> intents = ent.getValue();
9742 final int N = intents.size();
9743 for (int i=0; i<N; i++) {
9744 sb.setLength(0);
9745 sb.append(" Intent: ");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009746 intents.get(i).toShortString(sb, false, true, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009747 pw.println(sb.toString());
9748 Bundle bundle = intents.get(i).getExtras();
9749 if (bundle != null) {
9750 pw.print(" ");
9751 pw.println(bundle.toString());
9752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009753 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009754 } else {
9755 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009756 }
9757 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009758 needSep = true;
9759 }
9760
9761 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009762 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009763 for (BroadcastQueue queue : mBroadcastQueues) {
9764 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9765 + queue.mBroadcastsScheduled);
9766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009767 pw.println(" mHandler:");
9768 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009769 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009770 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009771
9772 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009773 }
9774
Marco Nelissen18cb2872011-11-15 11:19:53 -08009775 /**
9776 * Prints a list of ServiceRecords (dumpsys activity services)
9777 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009778 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009779 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009780 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009781
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009782 ItemMatcher matcher = new ItemMatcher();
9783 matcher.build(args, opti);
9784
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009785 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009786 try {
9787 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9788 for (UserInfo user : users) {
9789 if (mServiceMap.getAllServices(user.id).size() > 0) {
9790 boolean printed = false;
9791 long nowReal = SystemClock.elapsedRealtime();
9792 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9793 user.id).iterator();
9794 needSep = false;
9795 while (it.hasNext()) {
9796 ServiceRecord r = it.next();
9797 if (!matcher.match(r, r.name)) {
9798 continue;
9799 }
9800 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9801 continue;
9802 }
9803 if (!printed) {
9804 pw.println(" Active services:");
9805 printed = true;
9806 }
9807 if (needSep) {
9808 pw.println();
9809 }
9810 pw.print(" * ");
9811 pw.println(r);
9812 if (dumpAll) {
9813 r.dump(pw, " ");
9814 needSep = true;
9815 } else {
9816 pw.print(" app=");
9817 pw.println(r.app);
9818 pw.print(" created=");
9819 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9820 pw.print(" started=");
9821 pw.print(r.startRequested);
9822 pw.print(" connections=");
9823 pw.println(r.connections.size());
9824 if (r.connections.size() > 0) {
9825 pw.println(" Connections:");
9826 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9827 for (int i = 0; i < clist.size(); i++) {
9828 ConnectionRecord conn = clist.get(i);
9829 pw.print(" ");
9830 pw.print(conn.binding.intent.intent.getIntent()
9831 .toShortString(false, false, false));
9832 pw.print(" -> ");
9833 ProcessRecord proc = conn.binding.client;
9834 pw.println(proc != null ? proc.toShortString() : "null");
9835 }
9836 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009837 }
9838 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009839 if (dumpClient && r.app != null && r.app.thread != null) {
9840 pw.println(" Client:");
9841 pw.flush();
9842 try {
9843 TransferPipe tp = new TransferPipe();
9844 try {
9845 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9846 r, args);
9847 tp.setBufferPrefix(" ");
9848 // Short timeout, since blocking here can
9849 // deadlock with the application.
9850 tp.go(fd, 2000);
9851 } finally {
9852 tp.kill();
9853 }
9854 } catch (IOException e) {
9855 pw.println(" Failure while dumping the service: " + e);
9856 } catch (RemoteException e) {
9857 pw.println(" Got a RemoteException while dumping the service");
9858 }
9859 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009860 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009861 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009862 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009864 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009865 } catch (RemoteException re) {
9866
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009868
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009869 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009870 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009871 for (int i=0; i<mPendingServices.size(); i++) {
9872 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009873 if (!matcher.match(r, r.name)) {
9874 continue;
9875 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009876 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9877 continue;
9878 }
9879 if (!printed) {
9880 if (needSep) pw.println(" ");
9881 needSep = true;
9882 pw.println(" Pending services:");
9883 printed = true;
9884 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009885 pw.print(" * Pending "); pw.println(r);
9886 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009887 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009888 needSep = true;
9889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009890
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009891 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009892 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009893 for (int i=0; i<mRestartingServices.size(); i++) {
9894 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009895 if (!matcher.match(r, r.name)) {
9896 continue;
9897 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009898 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9899 continue;
9900 }
9901 if (!printed) {
9902 if (needSep) pw.println(" ");
9903 needSep = true;
9904 pw.println(" Restarting services:");
9905 printed = true;
9906 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009907 pw.print(" * Restarting "); pw.println(r);
9908 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009909 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009910 needSep = true;
9911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009912
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009913 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009914 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009915 for (int i=0; i<mStoppingServices.size(); i++) {
9916 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009917 if (!matcher.match(r, r.name)) {
9918 continue;
9919 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009920 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9921 continue;
9922 }
9923 if (!printed) {
9924 if (needSep) pw.println(" ");
9925 needSep = true;
9926 pw.println(" Stopping services:");
9927 printed = true;
9928 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009929 pw.print(" * Stopping "); pw.println(r);
9930 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009931 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009932 needSep = true;
9933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009934
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009935 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009936 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009937 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009938 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009939 = mServiceConnections.values().iterator();
9940 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009941 ArrayList<ConnectionRecord> r = it.next();
9942 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009943 ConnectionRecord cr = r.get(i);
9944 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9945 continue;
9946 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009947 if (dumpPackage != null && (cr.binding.client == null
9948 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9949 continue;
9950 }
9951 if (!printed) {
9952 if (needSep) pw.println(" ");
9953 needSep = true;
9954 pw.println(" Connection bindings to services:");
9955 printed = true;
9956 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009957 pw.print(" * "); pw.println(cr);
9958 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009960 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009961 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009962 }
9963 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009964
9965 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009966 }
9967
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009968 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009969 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009970 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009971
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009972 ItemMatcher matcher = new ItemMatcher();
9973 matcher.build(args, opti);
9974
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009975 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009976
9977 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009978
9979 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009980 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009981 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009982 ContentProviderRecord r = mLaunchingProviders.get(i);
9983 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9984 continue;
9985 }
9986 if (!printed) {
9987 if (needSep) pw.println(" ");
9988 needSep = true;
9989 pw.println(" Launching content providers:");
9990 printed = true;
9991 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009992 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009993 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009994 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009995 }
9996
9997 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009998 if (needSep) pw.println();
9999 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010000 pw.println("Granted Uri Permissions:");
10001 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
10002 int uid = mGrantedUriPermissions.keyAt(i);
10003 HashMap<Uri, UriPermission> perms
10004 = mGrantedUriPermissions.valueAt(i);
10005 pw.print(" * UID "); pw.print(uid);
10006 pw.println(" holds:");
10007 for (UriPermission perm : perms.values()) {
10008 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010009 if (dumpAll) {
10010 perm.dump(pw, " ");
10011 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010012 }
10013 }
10014 needSep = true;
10015 }
10016
10017 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010018 }
10019
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010020 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010021 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010022 boolean needSep = false;
10023
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010024 if (mIntentSenderRecords.size() > 0) {
10025 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010026 Iterator<WeakReference<PendingIntentRecord>> it
10027 = mIntentSenderRecords.values().iterator();
10028 while (it.hasNext()) {
10029 WeakReference<PendingIntentRecord> ref = it.next();
10030 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010031 if (dumpPackage != null && (rec == null
10032 || !dumpPackage.equals(rec.key.packageName))) {
10033 continue;
10034 }
10035 if (!printed) {
10036 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
10037 printed = true;
10038 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010039 needSep = true;
10040 if (rec != null) {
10041 pw.print(" * "); pw.println(rec);
10042 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010043 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010044 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010045 } else {
10046 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010047 }
10048 }
10049 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010050
10051 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010052 }
10053
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010054 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010055 String prefix, String label, boolean complete, boolean brief, boolean client,
10056 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010057 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010058 boolean needNL = false;
10059 final String innerPrefix = prefix + " ";
10060 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010061 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010062 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010063 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
10064 continue;
10065 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -070010066 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010067 if (needNL) {
10068 pw.println(" ");
10069 needNL = false;
10070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010071 if (lastTask != r.task) {
10072 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010073 pw.print(prefix);
10074 pw.print(full ? "* " : " ");
10075 pw.println(lastTask);
10076 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010077 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010078 } else if (complete) {
10079 // Complete + brief == give a summary. Isn't that obvious?!?
10080 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010081 pw.print(prefix); pw.print(" ");
10082 pw.println(lastTask.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010083 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010085 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010086 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
10087 pw.print(" #"); pw.print(i); pw.print(": ");
10088 pw.println(r);
10089 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010090 r.dump(pw, innerPrefix);
10091 } else if (complete) {
10092 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010093 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010094 if (r.app != null) {
10095 pw.print(innerPrefix); pw.println(r.app);
10096 }
10097 }
10098 if (client && r.app != null && r.app.thread != null) {
10099 // flush anything that is already in the PrintWriter since the thread is going
10100 // to write to the file descriptor directly
10101 pw.flush();
10102 try {
10103 TransferPipe tp = new TransferPipe();
10104 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -080010105 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
10106 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010107 // Short timeout, since blocking here can
10108 // deadlock with the application.
10109 tp.go(fd, 2000);
10110 } finally {
10111 tp.kill();
10112 }
10113 } catch (IOException e) {
10114 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
10115 } catch (RemoteException e) {
10116 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
10117 }
10118 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010120 }
10121 }
10122
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010123 private static String buildOomTag(String prefix, String space, int val, int base) {
10124 if (val == base) {
10125 if (space == null) return prefix;
10126 return prefix + " ";
10127 }
10128 return prefix + "+" + Integer.toString(val-base);
10129 }
10130
10131 private static final int dumpProcessList(PrintWriter pw,
10132 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010133 String prefix, String normalLabel, String persistentLabel,
10134 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010135 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010136 final int N = list.size()-1;
10137 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010138 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010139 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10140 continue;
10141 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010142 pw.println(String.format("%s%s #%2d: %s",
10143 prefix, (r.persistent ? persistentLabel : normalLabel),
10144 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010145 if (r.persistent) {
10146 numPers++;
10147 }
10148 }
10149 return numPers;
10150 }
10151
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010152 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010153 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010154 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010155 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010156
Dianne Hackborn905577f2011-09-07 18:31:28 -070010157 ArrayList<Pair<ProcessRecord, Integer>> list
10158 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10159 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010160 ProcessRecord r = origList.get(i);
10161 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10162 continue;
10163 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010164 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10165 }
10166
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010167 if (list.size() <= 0) {
10168 return false;
10169 }
10170
Dianne Hackborn905577f2011-09-07 18:31:28 -070010171 Comparator<Pair<ProcessRecord, Integer>> comparator
10172 = new Comparator<Pair<ProcessRecord, Integer>>() {
10173 @Override
10174 public int compare(Pair<ProcessRecord, Integer> object1,
10175 Pair<ProcessRecord, Integer> object2) {
10176 if (object1.first.setAdj != object2.first.setAdj) {
10177 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10178 }
10179 if (object1.second.intValue() != object2.second.intValue()) {
10180 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10181 }
10182 return 0;
10183 }
10184 };
10185
10186 Collections.sort(list, comparator);
10187
Dianne Hackborn287952c2010-09-22 22:34:31 -070010188 final long curRealtime = SystemClock.elapsedRealtime();
10189 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10190 final long curUptime = SystemClock.uptimeMillis();
10191 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10192
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010193 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010194 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010195 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010196 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010197 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010198 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10199 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010200 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10201 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010202 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10203 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010204 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10205 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010206 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010207 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010208 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10209 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10210 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10211 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10212 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10213 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10214 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10215 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010216 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10217 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010218 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10219 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010220 } else {
10221 oomAdj = Integer.toString(r.setAdj);
10222 }
10223 String schedGroup;
10224 switch (r.setSchedGroup) {
10225 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10226 schedGroup = "B";
10227 break;
10228 case Process.THREAD_GROUP_DEFAULT:
10229 schedGroup = "F";
10230 break;
10231 default:
10232 schedGroup = Integer.toString(r.setSchedGroup);
10233 break;
10234 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010235 String foreground;
10236 if (r.foregroundActivities) {
10237 foreground = "A";
10238 } else if (r.foregroundServices) {
10239 foreground = "S";
10240 } else {
10241 foreground = " ";
10242 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010243 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010244 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010245 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10246 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010247 if (r.adjSource != null || r.adjTarget != null) {
10248 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010249 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010250 if (r.adjTarget instanceof ComponentName) {
10251 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10252 } else if (r.adjTarget != null) {
10253 pw.print(r.adjTarget.toString());
10254 } else {
10255 pw.print("{null}");
10256 }
10257 pw.print("<=");
10258 if (r.adjSource instanceof ProcessRecord) {
10259 pw.print("Proc{");
10260 pw.print(((ProcessRecord)r.adjSource).toShortString());
10261 pw.println("}");
10262 } else if (r.adjSource != null) {
10263 pw.println(r.adjSource.toString());
10264 } else {
10265 pw.println("{null}");
10266 }
10267 }
10268 if (inclDetails) {
10269 pw.print(prefix);
10270 pw.print(" ");
10271 pw.print("oom: max="); pw.print(r.maxAdj);
10272 pw.print(" hidden="); pw.print(r.hiddenAdj);
10273 pw.print(" curRaw="); pw.print(r.curRawAdj);
10274 pw.print(" setRaw="); pw.print(r.setRawAdj);
10275 pw.print(" cur="); pw.print(r.curAdj);
10276 pw.print(" set="); pw.println(r.setAdj);
10277 pw.print(prefix);
10278 pw.print(" ");
10279 pw.print("keeping="); pw.print(r.keeping);
10280 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010281 pw.print(" empty="); pw.print(r.empty);
10282 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010283
10284 if (!r.keeping) {
10285 if (r.lastWakeTime != 0) {
10286 long wtime;
10287 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10288 synchronized (stats) {
10289 wtime = stats.getProcessWakeTime(r.info.uid,
10290 r.pid, curRealtime);
10291 }
10292 long timeUsed = wtime - r.lastWakeTime;
10293 pw.print(prefix);
10294 pw.print(" ");
10295 pw.print("keep awake over ");
10296 TimeUtils.formatDuration(realtimeSince, pw);
10297 pw.print(" used ");
10298 TimeUtils.formatDuration(timeUsed, pw);
10299 pw.print(" (");
10300 pw.print((timeUsed*100)/realtimeSince);
10301 pw.println("%)");
10302 }
10303 if (r.lastCpuTime != 0) {
10304 long timeUsed = r.curCpuTime - r.lastCpuTime;
10305 pw.print(prefix);
10306 pw.print(" ");
10307 pw.print("run cpu over ");
10308 TimeUtils.formatDuration(uptimeSince, pw);
10309 pw.print(" used ");
10310 TimeUtils.formatDuration(timeUsed, pw);
10311 pw.print(" (");
10312 pw.print((timeUsed*100)/uptimeSince);
10313 pw.println("%)");
10314 }
10315 }
10316 }
10317 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010318 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010319 }
10320
Dianne Hackbornb437e092011-08-05 17:50:29 -070010321 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010322 ArrayList<ProcessRecord> procs;
10323 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010324 if (args != null && args.length > start
10325 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010326 procs = new ArrayList<ProcessRecord>();
10327 int pid = -1;
10328 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010329 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010330 } catch (NumberFormatException e) {
10331
10332 }
10333 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10334 ProcessRecord proc = mLruProcesses.get(i);
10335 if (proc.pid == pid) {
10336 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010337 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010338 procs.add(proc);
10339 }
10340 }
10341 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010342 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010343 return null;
10344 }
10345 } else {
10346 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10347 }
10348 }
10349 return procs;
10350 }
10351
10352 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10353 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010354 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010355 if (procs == null) {
10356 return;
10357 }
10358
10359 long uptime = SystemClock.uptimeMillis();
10360 long realtime = SystemClock.elapsedRealtime();
10361 pw.println("Applications Graphics Acceleration Info:");
10362 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10363
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010364 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10365 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010366 if (r.thread != null) {
10367 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10368 pw.flush();
10369 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010370 TransferPipe tp = new TransferPipe();
10371 try {
10372 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10373 tp.go(fd);
10374 } finally {
10375 tp.kill();
10376 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010377 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010378 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010379 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010380 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010381 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010382 pw.flush();
10383 }
10384 }
10385 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010386 }
10387
Jeff Brown6754ba22011-12-14 20:20:01 -080010388 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10389 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10390 if (procs == null) {
10391 return;
10392 }
10393
10394 pw.println("Applications Database Info:");
10395
10396 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10397 ProcessRecord r = procs.get(i);
10398 if (r.thread != null) {
10399 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10400 pw.flush();
10401 try {
10402 TransferPipe tp = new TransferPipe();
10403 try {
10404 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10405 tp.go(fd);
10406 } finally {
10407 tp.kill();
10408 }
10409 } catch (IOException e) {
10410 pw.println("Failure while dumping the app: " + r);
10411 pw.flush();
10412 } catch (RemoteException e) {
10413 pw.println("Got a RemoteException while dumping the app " + r);
10414 pw.flush();
10415 }
10416 }
10417 }
10418 }
10419
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010420 final static class MemItem {
10421 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010422 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010423 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010424 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010425 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010426
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010427 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010428 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010429 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010430 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010431 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010432 }
10433 }
10434
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010435 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010436 boolean sort) {
10437 if (sort) {
10438 Collections.sort(items, new Comparator<MemItem>() {
10439 @Override
10440 public int compare(MemItem lhs, MemItem rhs) {
10441 if (lhs.pss < rhs.pss) {
10442 return 1;
10443 } else if (lhs.pss > rhs.pss) {
10444 return -1;
10445 }
10446 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010447 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010448 });
10449 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010450
10451 for (int i=0; i<items.size(); i++) {
10452 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010453 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010454 if (mi.subitems != null) {
10455 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10456 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010457 }
10458 }
10459
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010460 // These are in KB.
10461 static final long[] DUMP_MEM_BUCKETS = new long[] {
10462 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10463 120*1024, 160*1024, 200*1024,
10464 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10465 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10466 };
10467
Dianne Hackborn672342c2011-11-29 11:29:02 -080010468 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10469 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010470 int start = label.lastIndexOf('.');
10471 if (start >= 0) start++;
10472 else start = 0;
10473 int end = label.length();
10474 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10475 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10476 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10477 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010478 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010479 out.append(label, start, end);
10480 return;
10481 }
10482 }
10483 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010484 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010485 out.append(label, start, end);
10486 }
10487
10488 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10489 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10490 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10491 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10492 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10493 };
10494 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10495 "System", "Persistent", "Foreground",
10496 "Visible", "Perceptible", "Heavy Weight",
10497 "Backup", "A Services", "Home", "Previous",
10498 "B Services", "Background"
10499 };
10500
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010501 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010502 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010503 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010504 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010505 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010506
10507 int opti = 0;
10508 while (opti < args.length) {
10509 String opt = args[opti];
10510 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10511 break;
10512 }
10513 opti++;
10514 if ("-a".equals(opt)) {
10515 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010516 } else if ("--oom".equals(opt)) {
10517 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010518 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010519 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010520 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010521 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010522 pw.println("If [process] is specified it can be the name or ");
10523 pw.println("pid of a specific process to dump.");
10524 return;
10525 } else {
10526 pw.println("Unknown argument: " + opt + "; use -h for help");
10527 }
10528 }
10529
10530 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010531 if (procs == null) {
10532 return;
10533 }
10534
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010535 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010536 long uptime = SystemClock.uptimeMillis();
10537 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010538
10539 if (procs.size() == 1 || isCheckinRequest) {
10540 dumpAll = true;
10541 }
10542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010543 if (isCheckinRequest) {
10544 // short checkin version
10545 pw.println(uptime + "," + realtime);
10546 pw.flush();
10547 } else {
10548 pw.println("Applications Memory Usage (kB):");
10549 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10550 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010551
Dianne Hackbornb437e092011-08-05 17:50:29 -070010552 String[] innerArgs = new String[args.length-opti];
10553 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10554
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010555 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10556 long nativePss=0, dalvikPss=0, otherPss=0;
10557 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10558
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010559 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10560 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10561 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010562
10563 long totalPss = 0;
10564
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010565 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10566 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010567 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010568 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010569 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10570 pw.flush();
10571 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010572 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010573 if (dumpAll) {
10574 try {
10575 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10576 } catch (RemoteException e) {
10577 if (!isCheckinRequest) {
10578 pw.println("Got RemoteException!");
10579 pw.flush();
10580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010581 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010582 } else {
10583 mi = new Debug.MemoryInfo();
10584 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010585 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010586
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010587 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010588 long myTotalPss = mi.getTotalPss();
10589 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010590 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010591 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010592 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010593
10594 nativePss += mi.nativePss;
10595 dalvikPss += mi.dalvikPss;
10596 otherPss += mi.otherPss;
10597 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10598 long mem = mi.getOtherPss(j);
10599 miscPss[j] += mem;
10600 otherPss -= mem;
10601 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010602
10603 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010604 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10605 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010606 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010607 if (oomProcs[oomIndex] == null) {
10608 oomProcs[oomIndex] = new ArrayList<MemItem>();
10609 }
10610 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010611 break;
10612 }
10613 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010615 }
10616 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010617
10618 if (!isCheckinRequest && procs.size() > 1) {
10619 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10620
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010621 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10622 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10623 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010624 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010625 String label = Debug.MemoryInfo.getOtherLabel(j);
10626 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010627 }
10628
Dianne Hackbornb437e092011-08-05 17:50:29 -070010629 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10630 for (int j=0; j<oomPss.length; j++) {
10631 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010632 String label = DUMP_MEM_OOM_LABEL[j];
10633 MemItem item = new MemItem(label, label, oomPss[j],
10634 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010635 item.subitems = oomProcs[j];
10636 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010637 }
10638 }
10639
Dianne Hackborn672342c2011-11-29 11:29:02 -080010640 if (outTag != null || outStack != null) {
10641 if (outTag != null) {
10642 appendMemBucket(outTag, totalPss, "total", false);
10643 }
10644 if (outStack != null) {
10645 appendMemBucket(outStack, totalPss, "total", true);
10646 }
10647 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010648 for (int i=0; i<oomMems.size(); i++) {
10649 MemItem miCat = oomMems.get(i);
10650 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10651 continue;
10652 }
10653 if (miCat.id < ProcessList.SERVICE_ADJ
10654 || miCat.id == ProcessList.HOME_APP_ADJ
10655 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010656 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10657 outTag.append(" / ");
10658 }
10659 if (outStack != null) {
10660 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10661 if (firstLine) {
10662 outStack.append(":");
10663 firstLine = false;
10664 }
10665 outStack.append("\n\t at ");
10666 } else {
10667 outStack.append("$");
10668 }
10669 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010670 for (int j=0; j<miCat.subitems.size(); j++) {
10671 MemItem mi = miCat.subitems.get(j);
10672 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010673 if (outTag != null) {
10674 outTag.append(" ");
10675 }
10676 if (outStack != null) {
10677 outStack.append("$");
10678 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010679 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010680 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10681 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10682 }
10683 if (outStack != null) {
10684 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10685 }
10686 }
10687 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10688 outStack.append("(");
10689 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10690 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10691 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10692 outStack.append(":");
10693 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10694 }
10695 }
10696 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010697 }
10698 }
10699 }
10700 }
10701
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010702 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010703 pw.println();
10704 pw.println("Total PSS by process:");
10705 dumpMemItems(pw, " ", procMems, true);
10706 pw.println();
10707 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010708 pw.println("Total PSS by OOM adjustment:");
10709 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010710 if (!oomOnly) {
10711 PrintWriter out = categoryPw != null ? categoryPw : pw;
10712 out.println();
10713 out.println("Total PSS by category:");
10714 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010715 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010716 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010717 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010719 }
10720
10721 /**
10722 * Searches array of arguments for the specified string
10723 * @param args array of argument strings
10724 * @param value value to search for
10725 * @return true if the value is contained in the array
10726 */
10727 private static boolean scanArgs(String[] args, String value) {
10728 if (args != null) {
10729 for (String arg : args) {
10730 if (value.equals(arg)) {
10731 return true;
10732 }
10733 }
10734 }
10735 return false;
10736 }
10737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010738 private final void killServicesLocked(ProcessRecord app,
10739 boolean allowRestart) {
10740 // Report disconnected services.
10741 if (false) {
10742 // XXX we are letting the client link to the service for
10743 // death notifications.
10744 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010745 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010746 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010747 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010748 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010749 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010750 = r.connections.values().iterator();
10751 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010752 ArrayList<ConnectionRecord> cl = jt.next();
10753 for (int i=0; i<cl.size(); i++) {
10754 ConnectionRecord c = cl.get(i);
10755 if (c.binding.client != app) {
10756 try {
10757 //c.conn.connected(r.className, null);
10758 } catch (Exception e) {
10759 // todo: this should be asynchronous!
10760 Slog.w(TAG, "Exception thrown disconnected servce "
10761 + r.shortName
10762 + " from app " + app.processName, e);
10763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010764 }
10765 }
10766 }
10767 }
10768 }
10769 }
10770 }
10771
10772 // Clean up any connections this application has to other services.
10773 if (app.connections.size() > 0) {
10774 Iterator<ConnectionRecord> it = app.connections.iterator();
10775 while (it.hasNext()) {
10776 ConnectionRecord r = it.next();
10777 removeConnectionLocked(r, app, null);
10778 }
10779 }
10780 app.connections.clear();
10781
10782 if (app.services.size() != 0) {
10783 // Any services running in the application need to be placed
10784 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010785 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010786 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010787 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010788 synchronized (sr.stats.getBatteryStats()) {
10789 sr.stats.stopLaunchedLocked();
10790 }
10791 sr.app = null;
10792 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010793 if (mStoppingServices.remove(sr)) {
10794 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10795 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010796
10797 boolean hasClients = sr.bindings.size() > 0;
10798 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010799 Iterator<IntentBindRecord> bindings
10800 = sr.bindings.values().iterator();
10801 while (bindings.hasNext()) {
10802 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010803 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010804 + ": shouldUnbind=" + b.hasBound);
10805 b.binder = null;
10806 b.requested = b.received = b.hasBound = false;
10807 }
10808 }
10809
Dianne Hackborn070783f2010-12-29 16:46:28 -080010810 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10811 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010812 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010813 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010814 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010815 sr.crashCount, sr.shortName, app.pid);
10816 bringDownServiceLocked(sr, true);
10817 } else if (!allowRestart) {
10818 bringDownServiceLocked(sr, true);
10819 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010820 boolean canceled = scheduleServiceRestartLocked(sr, true);
10821
10822 // Should the service remain running? Note that in the
10823 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010824 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010825 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10826 if (sr.pendingStarts.size() == 0) {
10827 sr.startRequested = false;
10828 if (!hasClients) {
10829 // Whoops, no reason to restart!
10830 bringDownServiceLocked(sr, true);
10831 }
10832 }
10833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010834 }
10835 }
10836
10837 if (!allowRestart) {
10838 app.services.clear();
10839 }
10840 }
10841
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010842 // Make sure we have no more records on the stopping list.
10843 int i = mStoppingServices.size();
10844 while (i > 0) {
10845 i--;
10846 ServiceRecord sr = mStoppingServices.get(i);
10847 if (sr.app == app) {
10848 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010849 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010850 }
10851 }
10852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010853 app.executingServices.clear();
10854 }
10855
10856 private final void removeDyingProviderLocked(ProcessRecord proc,
10857 ContentProviderRecord cpr) {
10858 synchronized (cpr) {
10859 cpr.launchingApp = null;
10860 cpr.notifyAll();
10861 }
10862
Amith Yamasani742a6712011-05-04 14:49:28 -070010863 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010864 String names[] = cpr.info.authority.split(";");
10865 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010866 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010867 }
10868
10869 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10870 while (cit.hasNext()) {
10871 ProcessRecord capp = cit.next();
10872 if (!capp.persistent && capp.thread != null
10873 && capp.pid != 0
10874 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010875 Slog.i(TAG, "Kill " + capp.processName
10876 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010877 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010878 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010879 capp.processName, capp.setAdj, "dying provider "
10880 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010881 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010882 }
10883 }
10884
10885 mLaunchingProviders.remove(cpr);
10886 }
10887
10888 /**
10889 * Main code for cleaning up a process when it has gone away. This is
10890 * called both as a result of the process dying, or directly when stopping
10891 * a process when running in single process mode.
10892 */
10893 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010894 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010895 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010896 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010897 }
10898
Dianne Hackborn36124872009-10-08 16:22:03 -070010899 mProcessesToGc.remove(app);
10900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010901 // Dismiss any open dialogs.
10902 if (app.crashDialog != null) {
10903 app.crashDialog.dismiss();
10904 app.crashDialog = null;
10905 }
10906 if (app.anrDialog != null) {
10907 app.anrDialog.dismiss();
10908 app.anrDialog = null;
10909 }
10910 if (app.waitDialog != null) {
10911 app.waitDialog.dismiss();
10912 app.waitDialog = null;
10913 }
10914
10915 app.crashing = false;
10916 app.notResponding = false;
10917
10918 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010919 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010920 app.thread = null;
10921 app.forcingToForeground = null;
10922 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010923 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010924 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010925 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010926
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010927 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010928
10929 boolean restart = false;
10930
10931 int NL = mLaunchingProviders.size();
10932
10933 // Remove published content providers.
10934 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010935 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010936 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010937 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010938 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010939 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010940
10941 // See if someone is waiting for this provider... in which
10942 // case we don't remove it, but just let it restart.
10943 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010944 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010945 for (; i<NL; i++) {
10946 if (mLaunchingProviders.get(i) == cpr) {
10947 restart = true;
10948 break;
10949 }
10950 }
10951 } else {
10952 i = NL;
10953 }
10954
10955 if (i >= NL) {
10956 removeDyingProviderLocked(app, cpr);
10957 NL = mLaunchingProviders.size();
10958 }
10959 }
10960 app.pubProviders.clear();
10961 }
10962
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010963 // Take care of any launching providers waiting for this process.
10964 if (checkAppInLaunchingProvidersLocked(app, false)) {
10965 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010966 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010968 // Unregister from connected content providers.
10969 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010970 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010971 while (it.hasNext()) {
10972 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10973 cpr.clients.remove(app);
10974 }
10975 app.conProviders.clear();
10976 }
10977
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010978 // At this point there may be remaining entries in mLaunchingProviders
10979 // where we were the only one waiting, so they are no longer of use.
10980 // Look for these and clean up if found.
10981 // XXX Commented out for now. Trying to figure out a way to reproduce
10982 // the actual situation to identify what is actually going on.
10983 if (false) {
10984 for (int i=0; i<NL; i++) {
10985 ContentProviderRecord cpr = (ContentProviderRecord)
10986 mLaunchingProviders.get(i);
10987 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
10988 synchronized (cpr) {
10989 cpr.launchingApp = null;
10990 cpr.notifyAll();
10991 }
10992 }
10993 }
10994 }
10995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010996 skipCurrentReceiverLocked(app);
10997
10998 // Unregister any receivers.
10999 if (app.receivers.size() > 0) {
11000 Iterator<ReceiverList> it = app.receivers.iterator();
11001 while (it.hasNext()) {
11002 removeReceiverLocked(it.next());
11003 }
11004 app.receivers.clear();
11005 }
11006
Christopher Tate181fafa2009-05-14 11:12:14 -070011007 // If the app is undergoing backup, tell the backup manager about it
11008 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011009 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070011010 try {
11011 IBackupManager bm = IBackupManager.Stub.asInterface(
11012 ServiceManager.getService(Context.BACKUP_SERVICE));
11013 bm.agentDisconnected(app.info.packageName);
11014 } catch (RemoteException e) {
11015 // can't happen; backup manager is local
11016 }
11017 }
11018
Jeff Sharkey287bd832011-05-28 19:36:26 -070011019 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070011020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011021 // If the caller is restarting this app, then leave it in its
11022 // current lists and let the caller take care of it.
11023 if (restarting) {
11024 return;
11025 }
11026
11027 if (!app.persistent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011028 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011029 "Removing non-persistent process during cleanup: " + app);
11030 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070011031 if (mHeavyWeightProcess == app) {
11032 mHeavyWeightProcess = null;
11033 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
11034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011035 } else if (!app.removed) {
11036 // This app is persistent, so we need to keep its record around.
11037 // If it is not already on the pending app list, add it there
11038 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039 if (mPersistentStartingProcesses.indexOf(app) < 0) {
11040 mPersistentStartingProcesses.add(app);
11041 restart = true;
11042 }
11043 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011044 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
11045 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011046 mProcessesOnHold.remove(app);
11047
The Android Open Source Project4df24232009-03-05 14:34:35 -080011048 if (app == mHomeProcess) {
11049 mHomeProcess = null;
11050 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070011051 if (app == mPreviousProcess) {
11052 mPreviousProcess = null;
11053 }
11054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011055 if (restart) {
11056 // We have components that still need to be running in the
11057 // process, so re-launch it.
11058 mProcessNames.put(app.processName, app.info.uid, app);
11059 startProcessLocked(app, "restart", app.processName);
11060 } else if (app.pid > 0 && app.pid != MY_PID) {
11061 // Goodbye!
11062 synchronized (mPidsSelfLocked) {
11063 mPidsSelfLocked.remove(app.pid);
11064 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
11065 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070011066 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011067 }
11068 }
11069
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011070 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
11071 // Look through the content providers we are waiting to have launched,
11072 // and if any run in this process then either schedule a restart of
11073 // the process or kill the client waiting for it if this process has
11074 // gone bad.
11075 int NL = mLaunchingProviders.size();
11076 boolean restart = false;
11077 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011078 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011079 if (cpr.launchingApp == app) {
11080 if (!alwaysBad && !app.bad) {
11081 restart = true;
11082 } else {
11083 removeDyingProviderLocked(app, cpr);
11084 NL = mLaunchingProviders.size();
11085 }
11086 }
11087 }
11088 return restart;
11089 }
11090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011091 // =========================================================
11092 // SERVICES
11093 // =========================================================
11094
11095 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
11096 ActivityManager.RunningServiceInfo info =
11097 new ActivityManager.RunningServiceInfo();
11098 info.service = r.name;
11099 if (r.app != null) {
11100 info.pid = r.app.pid;
11101 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070011102 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011103 info.process = r.processName;
11104 info.foreground = r.isForeground;
11105 info.activeSince = r.createTime;
11106 info.started = r.startRequested;
11107 info.clientCount = r.connections.size();
11108 info.crashCount = r.crashCount;
11109 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070011110 if (r.isForeground) {
11111 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
11112 }
11113 if (r.startRequested) {
11114 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
11115 }
Dan Egnor42471dd2010-01-07 17:25:22 -080011116 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070011117 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
11118 }
11119 if (r.app != null && r.app.persistent) {
11120 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
11121 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011122
11123 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
11124 for (int i=0; i<connl.size(); i++) {
11125 ConnectionRecord conn = connl.get(i);
11126 if (conn.clientLabel != 0) {
11127 info.clientPackage = conn.binding.client.info.packageName;
11128 info.clientLabel = conn.clientLabel;
11129 return info;
11130 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011131 }
11132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011133 return info;
11134 }
11135
11136 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
11137 int flags) {
11138 synchronized (this) {
11139 ArrayList<ActivityManager.RunningServiceInfo> res
11140 = new ArrayList<ActivityManager.RunningServiceInfo>();
11141
Amith Yamasani742a6712011-05-04 14:49:28 -070011142 int userId = UserId.getUserId(Binder.getCallingUid());
11143 if (mServiceMap.getAllServices(userId).size() > 0) {
11144 Iterator<ServiceRecord> it
11145 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011146 while (it.hasNext() && res.size() < maxNum) {
11147 res.add(makeRunningServiceInfoLocked(it.next()));
11148 }
11149 }
11150
11151 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
11152 ServiceRecord r = mRestartingServices.get(i);
11153 ActivityManager.RunningServiceInfo info =
11154 makeRunningServiceInfoLocked(r);
11155 info.restarting = r.nextRestartTime;
11156 res.add(info);
11157 }
11158
11159 return res;
11160 }
11161 }
11162
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011163 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
11164 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011165 int userId = UserId.getUserId(Binder.getCallingUid());
11166 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011167 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011168 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
11169 for (int i=0; i<conn.size(); i++) {
11170 if (conn.get(i).clientIntent != null) {
11171 return conn.get(i).clientIntent;
11172 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011173 }
11174 }
11175 }
11176 }
11177 return null;
11178 }
11179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011180 private final ServiceRecord findServiceLocked(ComponentName name,
11181 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011182 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011183 return r == token ? r : null;
11184 }
11185
11186 private final class ServiceLookupResult {
11187 final ServiceRecord record;
11188 final String permission;
11189
11190 ServiceLookupResult(ServiceRecord _record, String _permission) {
11191 record = _record;
11192 permission = _permission;
11193 }
11194 };
11195
11196 private ServiceLookupResult findServiceLocked(Intent service,
11197 String resolvedType) {
11198 ServiceRecord r = null;
11199 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011200 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011201 }
11202 if (r == null) {
11203 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070011204 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011205 }
11206
11207 if (r == null) {
11208 try {
11209 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011210 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 service, resolvedType, 0);
11212 ServiceInfo sInfo =
11213 rInfo != null ? rInfo.serviceInfo : null;
11214 if (sInfo == null) {
11215 return null;
11216 }
11217
11218 ComponentName name = new ComponentName(
11219 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070011220 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011221 } catch (RemoteException ex) {
11222 // pm is in same process, this will never happen.
11223 }
11224 }
11225 if (r != null) {
11226 int callingPid = Binder.getCallingPid();
11227 int callingUid = Binder.getCallingUid();
11228 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011229 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011230 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011231 if (!r.exported) {
11232 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11233 + " from pid=" + callingPid
11234 + ", uid=" + callingUid
11235 + " that is not exported from uid " + r.appInfo.uid);
11236 return new ServiceLookupResult(null, "not exported from uid "
11237 + r.appInfo.uid);
11238 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011239 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011240 + " from pid=" + callingPid
11241 + ", uid=" + callingUid
11242 + " requires " + r.permission);
11243 return new ServiceLookupResult(null, r.permission);
11244 }
11245 return new ServiceLookupResult(r, null);
11246 }
11247 return null;
11248 }
11249
11250 private class ServiceRestarter implements Runnable {
11251 private ServiceRecord mService;
11252
11253 void setService(ServiceRecord service) {
11254 mService = service;
11255 }
11256
11257 public void run() {
11258 synchronized(ActivityManagerService.this) {
11259 performServiceRestartLocked(mService);
11260 }
11261 }
11262 }
11263
11264 private ServiceLookupResult retrieveServiceLocked(Intent service,
11265 String resolvedType, int callingPid, int callingUid) {
11266 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070011267 if (DEBUG_SERVICE)
11268 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
11269 + " origCallingUid=" + callingUid);
11270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011271 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011272 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011273 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011274 if (r == null) {
11275 Intent.FilterComparison filter = new Intent.FilterComparison(service);
11276 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
11277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011278 if (r == null) {
11279 try {
11280 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011281 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011282 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011283 ServiceInfo sInfo =
11284 rInfo != null ? rInfo.serviceInfo : null;
11285 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011286 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 ": not found");
11288 return null;
11289 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011290 if (Binder.getOrigCallingUser() > 0) {
11291 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo,
11292 Binder.getOrigCallingUser());
11293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011294 ComponentName name = new ComponentName(
11295 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070011296 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011298 Intent.FilterComparison filter = new Intent.FilterComparison(
11299 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011300 ServiceRestarter res = new ServiceRestarter();
11301 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11302 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11303 synchronized (stats) {
11304 ss = stats.getServiceStatsLocked(
11305 sInfo.applicationInfo.uid, sInfo.packageName,
11306 sInfo.name);
11307 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080011308 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011309 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070011310 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
11311 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011312
11313 // Make sure this component isn't in the pending list.
11314 int N = mPendingServices.size();
11315 for (int i=0; i<N; i++) {
11316 ServiceRecord pr = mPendingServices.get(i);
11317 if (pr.name.equals(name)) {
11318 mPendingServices.remove(i);
11319 i--;
11320 N--;
11321 }
11322 }
11323 }
11324 } catch (RemoteException ex) {
11325 // pm is in same process, this will never happen.
11326 }
11327 }
11328 if (r != null) {
11329 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011330 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011332 if (!r.exported) {
11333 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11334 + " from pid=" + callingPid
11335 + ", uid=" + callingUid
11336 + " that is not exported from uid " + r.appInfo.uid);
11337 return new ServiceLookupResult(null, "not exported from uid "
11338 + r.appInfo.uid);
11339 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011340 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011341 + " from pid=" + callingPid
11342 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011343 + " requires " + r.permission);
11344 return new ServiceLookupResult(null, r.permission);
11345 }
11346 return new ServiceLookupResult(r, null);
11347 }
11348 return null;
11349 }
11350
Dianne Hackborn287952c2010-09-22 22:34:31 -070011351 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11352 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11353 + why + " of " + r + " in app " + r.app);
11354 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11355 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011356 long now = SystemClock.uptimeMillis();
11357 if (r.executeNesting == 0 && r.app != null) {
11358 if (r.app.executingServices.size() == 0) {
11359 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11360 msg.obj = r.app;
11361 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11362 }
11363 r.app.executingServices.add(r);
11364 }
11365 r.executeNesting++;
11366 r.executingStart = now;
11367 }
11368
11369 private final void sendServiceArgsLocked(ServiceRecord r,
11370 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011371 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011372 if (N == 0) {
11373 return;
11374 }
11375
Dianne Hackborn39792d22010-08-19 18:01:52 -070011376 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011377 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011378 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011379 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11380 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011381 if (si.intent == null && N > 1) {
11382 // If somehow we got a dummy null intent in the middle,
11383 // then skip it. DO NOT skip a null intent when it is
11384 // the only one in the list -- this is to support the
11385 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011386 continue;
11387 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011388 si.deliveredTime = SystemClock.uptimeMillis();
11389 r.deliveredStarts.add(si);
11390 si.deliveryCount++;
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011391 if (si.targetPermissionUid >= 0 && si.intent != null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011392 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -070011393 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011394 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011395 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011396 if (!oomAdjusted) {
11397 oomAdjusted = true;
11398 updateOomAdjLocked(r.app);
11399 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011400 int flags = 0;
11401 if (si.deliveryCount > 0) {
11402 flags |= Service.START_FLAG_RETRY;
11403 }
11404 if (si.doneExecutingCount > 0) {
11405 flags |= Service.START_FLAG_REDELIVERY;
11406 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011407 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011408 } catch (RemoteException e) {
11409 // Remote process gone... we'll let the normal cleanup take
11410 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011411 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011412 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011413 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011414 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011415 break;
11416 }
11417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 }
11419
11420 private final boolean requestServiceBindingLocked(ServiceRecord r,
11421 IntentBindRecord i, boolean rebind) {
11422 if (r.app == null || r.app.thread == null) {
11423 // If service is not currently running, can't yet bind.
11424 return false;
11425 }
11426 if ((!i.requested || rebind) && i.apps.size() > 0) {
11427 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011428 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011429 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11430 if (!rebind) {
11431 i.requested = true;
11432 }
11433 i.hasBound = true;
11434 i.doRebind = false;
11435 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011436 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011437 return false;
11438 }
11439 }
11440 return true;
11441 }
11442
11443 private final void requestServiceBindingsLocked(ServiceRecord r) {
11444 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11445 while (bindings.hasNext()) {
11446 IntentBindRecord i = bindings.next();
11447 if (!requestServiceBindingLocked(r, i, false)) {
11448 break;
11449 }
11450 }
11451 }
11452
11453 private final void realStartServiceLocked(ServiceRecord r,
11454 ProcessRecord app) throws RemoteException {
11455 if (app.thread == null) {
11456 throw new RemoteException();
11457 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011458 if (DEBUG_MU)
11459 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
11460 + ", ProcessRecord.uid = " + app.info.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011461 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011462 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011463
11464 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011465 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011466 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011467
11468 boolean created = false;
11469 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011470 mStringBuilder.setLength(0);
Dianne Hackborn90c52de2011-09-23 12:57:44 -070011471 r.intent.getIntent().toShortString(mStringBuilder, true, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011472 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011474 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011475 synchronized (r.stats.getBatteryStats()) {
11476 r.stats.startLaunchedLocked();
11477 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011478 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011479 app.thread.scheduleCreateService(r, r.serviceInfo,
11480 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011481 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011482 created = true;
11483 } finally {
11484 if (!created) {
11485 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011486 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011487 }
11488 }
11489
11490 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011491
11492 // If the service is in the started state, and there are no
11493 // pending arguments, then fake up one so its onStartCommand() will
11494 // be called.
11495 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011496 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
11497 null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011498 }
11499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011500 sendServiceArgsLocked(r, true);
11501 }
11502
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011503 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11504 boolean allowCancel) {
11505 boolean canceled = false;
11506
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011507 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011508 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011509 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011510
Dianne Hackborn070783f2010-12-29 16:46:28 -080011511 if ((r.serviceInfo.applicationInfo.flags
11512 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11513 minDuration /= 4;
11514 }
11515
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011516 // Any delivered but not yet finished starts should be put back
11517 // on the pending list.
11518 final int N = r.deliveredStarts.size();
11519 if (N > 0) {
11520 for (int i=N-1; i>=0; i--) {
11521 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011522 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011523 if (si.intent == null) {
11524 // We'll generate this again if needed.
11525 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11526 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11527 r.pendingStarts.add(0, si);
11528 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11529 dur *= 2;
11530 if (minDuration < dur) minDuration = dur;
11531 if (resetTime < dur) resetTime = dur;
11532 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011533 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011534 + r.name);
11535 canceled = true;
11536 }
11537 }
11538 r.deliveredStarts.clear();
11539 }
11540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011541 r.totalRestartCount++;
11542 if (r.restartDelay == 0) {
11543 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011544 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011545 } else {
11546 // If it has been a "reasonably long time" since the service
11547 // was started, then reset our restart duration back to
11548 // the beginning, so we don't infinitely increase the duration
11549 // on a service that just occasionally gets killed (which is
11550 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011551 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011552 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011553 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011554 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011555 if ((r.serviceInfo.applicationInfo.flags
11556 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11557 // Services in peristent processes will restart much more
11558 // quickly, since they are pretty important. (Think SystemUI).
11559 r.restartDelay += minDuration/2;
11560 } else {
11561 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11562 if (r.restartDelay < minDuration) {
11563 r.restartDelay = minDuration;
11564 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011566 }
11567 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011568
11569 r.nextRestartTime = now + r.restartDelay;
11570
11571 // Make sure that we don't end up restarting a bunch of services
11572 // all at the same time.
11573 boolean repeat;
11574 do {
11575 repeat = false;
11576 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11577 ServiceRecord r2 = mRestartingServices.get(i);
11578 if (r2 != r && r.nextRestartTime
11579 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11580 && r.nextRestartTime
11581 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11582 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11583 r.restartDelay = r.nextRestartTime - now;
11584 repeat = true;
11585 break;
11586 }
11587 }
11588 } while (repeat);
11589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011590 if (!mRestartingServices.contains(r)) {
11591 mRestartingServices.add(r);
11592 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011593
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011594 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011596 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011597 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011598 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011599 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011600 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011601 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011602 r.shortName, r.restartDelay);
11603
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011604 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011605 }
11606
11607 final void performServiceRestartLocked(ServiceRecord r) {
11608 if (!mRestartingServices.contains(r)) {
11609 return;
11610 }
11611 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11612 }
11613
11614 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11615 if (r.restartDelay == 0) {
11616 return false;
11617 }
11618 r.resetRestartCounter();
11619 mRestartingServices.remove(r);
11620 mHandler.removeCallbacks(r.restarter);
11621 return true;
11622 }
11623
11624 private final boolean bringUpServiceLocked(ServiceRecord r,
11625 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011626 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011627 //r.dump(" ");
11628
Dianne Hackborn36124872009-10-08 16:22:03 -070011629 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011630 sendServiceArgsLocked(r, false);
11631 return true;
11632 }
11633
11634 if (!whileRestarting && r.restartDelay > 0) {
11635 // If waiting for a restart, then do nothing.
11636 return true;
11637 }
11638
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011639 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011640
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011641 // We are now bringing the service up, so no longer in the
11642 // restarting state.
11643 mRestartingServices.remove(r);
11644
Dianne Hackborne7f97212011-02-24 14:40:20 -080011645 // Service is now being launched, its package can't be stopped.
11646 try {
11647 AppGlobals.getPackageManager().setPackageStoppedState(
11648 r.packageName, false);
11649 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011650 } catch (IllegalArgumentException e) {
11651 Slog.w(TAG, "Failed trying to unstop package "
11652 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011653 }
11654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 final String appName = r.processName;
11656 ProcessRecord app = getProcessRecordLocked(appName, r.appInfo.uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070011657 if (DEBUG_MU)
11658 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011659 if (app != null && app.thread != null) {
11660 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011661 app.addPackage(r.appInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011662 realStartServiceLocked(r, app);
11663 return true;
11664 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011665 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011666 }
11667
11668 // If a dead object exception was thrown -- fall through to
11669 // restart the application.
11670 }
11671
Dianne Hackborn36124872009-10-08 16:22:03 -070011672 // Not running -- get it started, and enqueue this service record
11673 // to be executed when the app comes up.
11674 if (startProcessLocked(appName, r.appInfo, true, intentFlags,
11675 "service", r.name, false) == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011676 Slog.w(TAG, "Unable to launch app "
Dianne Hackborn36124872009-10-08 16:22:03 -070011677 + r.appInfo.packageName + "/"
11678 + r.appInfo.uid + " for service "
11679 + r.intent.getIntent() + ": process is bad");
11680 bringDownServiceLocked(r, true);
11681 return false;
11682 }
11683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011684 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011685 mPendingServices.add(r);
11686 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011688 return true;
11689 }
11690
11691 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011692 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011693 //r.dump(" ");
11694
11695 // Does it still need to run?
11696 if (!force && r.startRequested) {
11697 return;
11698 }
11699 if (r.connections.size() > 0) {
11700 if (!force) {
11701 // XXX should probably keep a count of the number of auto-create
11702 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011703 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011704 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011705 ArrayList<ConnectionRecord> cr = it.next();
11706 for (int i=0; i<cr.size(); i++) {
11707 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11708 return;
11709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011710 }
11711 }
11712 }
11713
11714 // Report to all of the connections that the service is no longer
11715 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011716 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011717 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011718 ArrayList<ConnectionRecord> c = it.next();
11719 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011720 ConnectionRecord cr = c.get(i);
11721 // There is still a connection to the service that is
11722 // being brought down. Mark it as dead.
11723 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011724 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011725 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011726 } catch (Exception e) {
11727 Slog.w(TAG, "Failure disconnecting service " + r.name +
11728 " to connection " + c.get(i).conn.asBinder() +
11729 " (in " + c.get(i).binding.client.processName + ")", e);
11730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011731 }
11732 }
11733 }
11734
11735 // Tell the service that it has been unbound.
11736 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11737 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11738 while (it.hasNext()) {
11739 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011740 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011741 + ": hasBound=" + ibr.hasBound);
11742 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11743 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011744 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011745 updateOomAdjLocked(r.app);
11746 ibr.hasBound = false;
11747 r.app.thread.scheduleUnbindService(r,
11748 ibr.intent.getIntent());
11749 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011750 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011751 + r.shortName, e);
11752 serviceDoneExecutingLocked(r, true);
11753 }
11754 }
11755 }
11756 }
11757
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011758 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011759 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011760 System.identityHashCode(r), r.shortName,
11761 (r.app != null) ? r.app.pid : -1);
11762
Amith Yamasani742a6712011-05-04 14:49:28 -070011763 mServiceMap.removeServiceByName(r.name, r.userId);
11764 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011765 r.totalRestartCount = 0;
11766 unscheduleServiceRestartLocked(r);
11767
11768 // Also make sure it is not on the pending list.
11769 int N = mPendingServices.size();
11770 for (int i=0; i<N; i++) {
11771 if (mPendingServices.get(i) == r) {
11772 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011773 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011774 i--;
11775 N--;
11776 }
11777 }
11778
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011779 r.cancelNotification();
11780 r.isForeground = false;
11781 r.foregroundId = 0;
11782 r.foregroundNoti = null;
11783
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011784 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011785 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011786 r.pendingStarts.clear();
11787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011788 if (r.app != null) {
11789 synchronized (r.stats.getBatteryStats()) {
11790 r.stats.stopLaunchedLocked();
11791 }
11792 r.app.services.remove(r);
11793 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011794 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011795 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011796 mStoppingServices.add(r);
11797 updateOomAdjLocked(r.app);
11798 r.app.thread.scheduleStopService(r);
11799 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011800 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011801 + r.shortName, e);
11802 serviceDoneExecutingLocked(r, true);
11803 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011804 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011805 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011806 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011807 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011808 }
11809 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011810 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011811 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011812 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011813
11814 if (r.bindings.size() > 0) {
11815 r.bindings.clear();
11816 }
11817
11818 if (r.restarter instanceof ServiceRestarter) {
11819 ((ServiceRestarter)r.restarter).setService(null);
11820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821 }
11822
11823 ComponentName startServiceLocked(IApplicationThread caller,
11824 Intent service, String resolvedType,
11825 int callingPid, int callingUid) {
11826 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011827 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 + " type=" + resolvedType + " args=" + service.getExtras());
11829
11830 if (caller != null) {
11831 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11832 if (callerApp == null) {
11833 throw new SecurityException(
11834 "Unable to find app for caller " + caller
11835 + " (pid=" + Binder.getCallingPid()
11836 + ") when starting service " + service);
11837 }
11838 }
11839
11840 ServiceLookupResult res =
11841 retrieveServiceLocked(service, resolvedType,
11842 callingPid, callingUid);
11843 if (res == null) {
11844 return null;
11845 }
11846 if (res.record == null) {
11847 return new ComponentName("!", res.permission != null
11848 ? res.permission : "private to package");
11849 }
11850 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -070011851 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
11852 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011853 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011854 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011855 }
11856 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011857 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011858 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn39792d22010-08-19 18:01:52 -070011859 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011860 r.lastActivity = SystemClock.uptimeMillis();
11861 synchronized (r.stats.getBatteryStats()) {
11862 r.stats.startRunningLocked();
11863 }
11864 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11865 return new ComponentName("!", "Service process is bad");
11866 }
11867 return r.name;
11868 }
11869 }
11870
11871 public ComponentName startService(IApplicationThread caller, Intent service,
11872 String resolvedType) {
11873 // Refuse possible leaked file descriptors
11874 if (service != null && service.hasFileDescriptors() == true) {
11875 throw new IllegalArgumentException("File descriptors passed in Intent");
11876 }
11877
Amith Yamasani742a6712011-05-04 14:49:28 -070011878 if (DEBUG_SERVICE)
11879 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011880 synchronized(this) {
11881 final int callingPid = Binder.getCallingPid();
11882 final int callingUid = Binder.getCallingUid();
11883 final long origId = Binder.clearCallingIdentity();
11884 ComponentName res = startServiceLocked(caller, service,
11885 resolvedType, callingPid, callingUid);
11886 Binder.restoreCallingIdentity(origId);
11887 return res;
11888 }
11889 }
11890
11891 ComponentName startServiceInPackage(int uid,
11892 Intent service, String resolvedType) {
11893 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011894 if (DEBUG_SERVICE)
11895 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 final long origId = Binder.clearCallingIdentity();
11897 ComponentName res = startServiceLocked(null, service,
11898 resolvedType, -1, uid);
11899 Binder.restoreCallingIdentity(origId);
11900 return res;
11901 }
11902 }
11903
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011904 private void stopServiceLocked(ServiceRecord service) {
11905 synchronized (service.stats.getBatteryStats()) {
11906 service.stats.stopRunningLocked();
11907 }
11908 service.startRequested = false;
11909 service.callStart = false;
11910 bringDownServiceLocked(service, false);
11911 }
11912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011913 public int stopService(IApplicationThread caller, Intent service,
11914 String resolvedType) {
11915 // Refuse possible leaked file descriptors
11916 if (service != null && service.hasFileDescriptors() == true) {
11917 throw new IllegalArgumentException("File descriptors passed in Intent");
11918 }
11919
11920 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011921 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 + " type=" + resolvedType);
11923
11924 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11925 if (caller != null && callerApp == null) {
11926 throw new SecurityException(
11927 "Unable to find app for caller " + caller
11928 + " (pid=" + Binder.getCallingPid()
11929 + ") when stopping service " + service);
11930 }
11931
11932 // If this service is active, make sure it is stopped.
11933 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11934 if (r != null) {
11935 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011936 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011937 try {
11938 stopServiceLocked(r.record);
11939 } finally {
11940 Binder.restoreCallingIdentity(origId);
11941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011942 return 1;
11943 }
11944 return -1;
11945 }
11946 }
11947
11948 return 0;
11949 }
11950
11951 public IBinder peekService(Intent service, String resolvedType) {
11952 // Refuse possible leaked file descriptors
11953 if (service != null && service.hasFileDescriptors() == true) {
11954 throw new IllegalArgumentException("File descriptors passed in Intent");
11955 }
11956
11957 IBinder ret = null;
11958
11959 synchronized(this) {
11960 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11961
11962 if (r != null) {
11963 // r.record is null if findServiceLocked() failed the caller permission check
11964 if (r.record == null) {
11965 throw new SecurityException(
11966 "Permission Denial: Accessing service " + r.record.name
11967 + " from pid=" + Binder.getCallingPid()
11968 + ", uid=" + Binder.getCallingUid()
11969 + " requires " + r.permission);
11970 }
11971 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11972 if (ib != null) {
11973 ret = ib.binder;
11974 }
11975 }
11976 }
11977
11978 return ret;
11979 }
11980
11981 public boolean stopServiceToken(ComponentName className, IBinder token,
11982 int startId) {
11983 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011984 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011985 + " " + token + " startId=" + startId);
11986 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011987 if (r != null) {
11988 if (startId >= 0) {
11989 // Asked to only stop if done with all work. Note that
11990 // to avoid leaks, we will take this as dropping all
11991 // start items up to and including this one.
11992 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11993 if (si != null) {
11994 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011995 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11996 cur.removeUriPermissionsLocked();
11997 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011998 break;
11999 }
12000 }
12001 }
12002
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012003 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012004 return false;
12005 }
12006
12007 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012008 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012009 + " is last, but have " + r.deliveredStarts.size()
12010 + " remaining args");
12011 }
12012 }
12013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012014 synchronized (r.stats.getBatteryStats()) {
12015 r.stats.stopRunningLocked();
12016 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012017 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012018 }
12019 final long origId = Binder.clearCallingIdentity();
12020 bringDownServiceLocked(r, false);
12021 Binder.restoreCallingIdentity(origId);
12022 return true;
12023 }
12024 }
12025 return false;
12026 }
12027
12028 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012029 int id, Notification notification, boolean removeNotification) {
12030 final long origId = Binder.clearCallingIdentity();
12031 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012032 synchronized(this) {
12033 ServiceRecord r = findServiceLocked(className, token);
12034 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012035 if (id != 0) {
12036 if (notification == null) {
12037 throw new IllegalArgumentException("null notification");
12038 }
12039 if (r.foregroundId != id) {
12040 r.cancelNotification();
12041 r.foregroundId = id;
12042 }
12043 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
12044 r.foregroundNoti = notification;
12045 r.isForeground = true;
12046 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012047 if (r.app != null) {
12048 updateServiceForegroundLocked(r.app, true);
12049 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012050 } else {
12051 if (r.isForeground) {
12052 r.isForeground = false;
12053 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070012054 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012055 updateServiceForegroundLocked(r.app, true);
12056 }
12057 }
12058 if (removeNotification) {
12059 r.cancelNotification();
12060 r.foregroundId = 0;
12061 r.foregroundNoti = null;
12062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012063 }
12064 }
12065 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070012066 } finally {
12067 Binder.restoreCallingIdentity(origId);
12068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012069 }
12070
12071 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
12072 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070012073 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012074 if (sr.isForeground) {
12075 anyForeground = true;
12076 break;
12077 }
12078 }
12079 if (anyForeground != proc.foregroundServices) {
12080 proc.foregroundServices = anyForeground;
12081 if (oomAdj) {
12082 updateOomAdjLocked();
12083 }
12084 }
12085 }
12086
12087 public int bindService(IApplicationThread caller, IBinder token,
12088 Intent service, String resolvedType,
12089 IServiceConnection connection, int flags) {
12090 // Refuse possible leaked file descriptors
12091 if (service != null && service.hasFileDescriptors() == true) {
12092 throw new IllegalArgumentException("File descriptors passed in Intent");
12093 }
12094
12095 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012096 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012097 + " type=" + resolvedType + " conn=" + connection.asBinder()
12098 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070012099 if (DEBUG_MU)
12100 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
12101 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012102 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12103 if (callerApp == null) {
12104 throw new SecurityException(
12105 "Unable to find app for caller " + caller
12106 + " (pid=" + Binder.getCallingPid()
12107 + ") when binding service " + service);
12108 }
12109
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012110 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012111 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012112 activity = mMainStack.isInStackLocked(token);
12113 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012114 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012115 return 0;
12116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012117 }
12118
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012119 int clientLabel = 0;
12120 PendingIntent clientIntent = null;
12121
12122 if (callerApp.info.uid == Process.SYSTEM_UID) {
12123 // Hacky kind of thing -- allow system stuff to tell us
12124 // what they are, so we can report this elsewhere for
12125 // others to know why certain services are running.
12126 try {
12127 clientIntent = (PendingIntent)service.getParcelableExtra(
12128 Intent.EXTRA_CLIENT_INTENT);
12129 } catch (RuntimeException e) {
12130 }
12131 if (clientIntent != null) {
12132 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
12133 if (clientLabel != 0) {
12134 // There are no useful extras in the intent, trash them.
12135 // System code calling with this stuff just needs to know
12136 // this will happen.
12137 service = service.cloneFilter();
12138 }
12139 }
12140 }
12141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012142 ServiceLookupResult res =
12143 retrieveServiceLocked(service, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -070012144 Binder.getCallingPid(), Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012145 if (res == null) {
12146 return 0;
12147 }
12148 if (res.record == null) {
12149 return -1;
12150 }
12151 ServiceRecord s = res.record;
12152
12153 final long origId = Binder.clearCallingIdentity();
12154
12155 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012156 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012157 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012158 }
12159
12160 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
12161 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012162 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012163
12164 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012165 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12166 if (clist == null) {
12167 clist = new ArrayList<ConnectionRecord>();
12168 s.connections.put(binder, clist);
12169 }
12170 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012171 b.connections.add(c);
12172 if (activity != null) {
12173 if (activity.connections == null) {
12174 activity.connections = new HashSet<ConnectionRecord>();
12175 }
12176 activity.connections.add(c);
12177 }
12178 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012179 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12180 b.client.hasAboveClient = true;
12181 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012182 clist = mServiceConnections.get(binder);
12183 if (clist == null) {
12184 clist = new ArrayList<ConnectionRecord>();
12185 mServiceConnections.put(binder, clist);
12186 }
12187 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012188
12189 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
12190 s.lastActivity = SystemClock.uptimeMillis();
12191 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
12192 return 0;
12193 }
12194 }
12195
12196 if (s.app != null) {
12197 // This could have made the service more important.
12198 updateOomAdjLocked(s.app);
12199 }
12200
Joe Onorato8a9b2202010-02-26 18:56:32 -080012201 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012202 + ": received=" + b.intent.received
12203 + " apps=" + b.intent.apps.size()
12204 + " doRebind=" + b.intent.doRebind);
12205
12206 if (s.app != null && b.intent.received) {
12207 // Service is already running, so we can immediately
12208 // publish the connection.
12209 try {
12210 c.conn.connected(s.name, b.intent.binder);
12211 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012212 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012213 + " to connection " + c.conn.asBinder()
12214 + " (in " + c.binding.client.processName + ")", e);
12215 }
12216
12217 // If this is the first app connected back to this binding,
12218 // and the service had previously asked to be told when
12219 // rebound, then do so.
12220 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
12221 requestServiceBindingLocked(s, b.intent, true);
12222 }
12223 } else if (!b.intent.requested) {
12224 requestServiceBindingLocked(s, b.intent, false);
12225 }
12226
12227 Binder.restoreCallingIdentity(origId);
12228 }
12229
12230 return 1;
12231 }
12232
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012233 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012234 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012235 IBinder binder = c.conn.asBinder();
12236 AppBindRecord b = c.binding;
12237 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012238 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12239 if (clist != null) {
12240 clist.remove(c);
12241 if (clist.size() == 0) {
12242 s.connections.remove(binder);
12243 }
12244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012245 b.connections.remove(c);
12246 if (c.activity != null && c.activity != skipAct) {
12247 if (c.activity.connections != null) {
12248 c.activity.connections.remove(c);
12249 }
12250 }
12251 if (b.client != skipApp) {
12252 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012253 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12254 b.client.updateHasAboveClientLocked();
12255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012256 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012257 clist = mServiceConnections.get(binder);
12258 if (clist != null) {
12259 clist.remove(c);
12260 if (clist.size() == 0) {
12261 mServiceConnections.remove(binder);
12262 }
12263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012264
12265 if (b.connections.size() == 0) {
12266 b.intent.apps.remove(b.client);
12267 }
12268
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012269 if (!c.serviceDead) {
12270 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
12271 + ": shouldUnbind=" + b.intent.hasBound);
12272 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
12273 && b.intent.hasBound) {
12274 try {
12275 bumpServiceExecutingLocked(s, "unbind");
12276 updateOomAdjLocked(s.app);
12277 b.intent.hasBound = false;
12278 // Assume the client doesn't want to know about a rebind;
12279 // we will deal with that later if it asks for one.
12280 b.intent.doRebind = false;
12281 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
12282 } catch (Exception e) {
12283 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
12284 serviceDoneExecutingLocked(s, true);
12285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012286 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012287
12288 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
12289 bringDownServiceLocked(s, false);
12290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012291 }
12292 }
12293
12294 public boolean unbindService(IServiceConnection connection) {
12295 synchronized (this) {
12296 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012297 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012298 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
12299 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012300 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012301 + connection.asBinder());
12302 return false;
12303 }
12304
12305 final long origId = Binder.clearCallingIdentity();
12306
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012307 while (clist.size() > 0) {
12308 ConnectionRecord r = clist.get(0);
12309 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012310
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012311 if (r.binding.service.app != null) {
12312 // This could have made the service less important.
12313 updateOomAdjLocked(r.binding.service.app);
12314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012315 }
12316
12317 Binder.restoreCallingIdentity(origId);
12318 }
12319
12320 return true;
12321 }
12322
12323 public void publishService(IBinder token, Intent intent, IBinder service) {
12324 // Refuse possible leaked file descriptors
12325 if (intent != null && intent.hasFileDescriptors() == true) {
12326 throw new IllegalArgumentException("File descriptors passed in Intent");
12327 }
12328
12329 synchronized(this) {
12330 if (!(token instanceof ServiceRecord)) {
12331 throw new IllegalArgumentException("Invalid service token");
12332 }
12333 ServiceRecord r = (ServiceRecord)token;
12334
12335 final long origId = Binder.clearCallingIdentity();
12336
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012337 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012338 + " " + intent + ": " + service);
12339 if (r != null) {
12340 Intent.FilterComparison filter
12341 = new Intent.FilterComparison(intent);
12342 IntentBindRecord b = r.bindings.get(filter);
12343 if (b != null && !b.received) {
12344 b.binder = service;
12345 b.requested = true;
12346 b.received = true;
12347 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012348 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012349 = r.connections.values().iterator();
12350 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012351 ArrayList<ConnectionRecord> clist = it.next();
12352 for (int i=0; i<clist.size(); i++) {
12353 ConnectionRecord c = clist.get(i);
12354 if (!filter.equals(c.binding.intent.intent)) {
12355 if (DEBUG_SERVICE) Slog.v(
12356 TAG, "Not publishing to: " + c);
12357 if (DEBUG_SERVICE) Slog.v(
12358 TAG, "Bound intent: " + c.binding.intent.intent);
12359 if (DEBUG_SERVICE) Slog.v(
12360 TAG, "Published intent: " + intent);
12361 continue;
12362 }
12363 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12364 try {
12365 c.conn.connected(r.name, service);
12366 } catch (Exception e) {
12367 Slog.w(TAG, "Failure sending service " + r.name +
12368 " to connection " + c.conn.asBinder() +
12369 " (in " + c.binding.client.processName + ")", e);
12370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012371 }
12372 }
12373 }
12374 }
12375
12376 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12377
12378 Binder.restoreCallingIdentity(origId);
12379 }
12380 }
12381 }
12382
12383 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12384 // Refuse possible leaked file descriptors
12385 if (intent != null && intent.hasFileDescriptors() == true) {
12386 throw new IllegalArgumentException("File descriptors passed in Intent");
12387 }
12388
12389 synchronized(this) {
12390 if (!(token instanceof ServiceRecord)) {
12391 throw new IllegalArgumentException("Invalid service token");
12392 }
12393 ServiceRecord r = (ServiceRecord)token;
12394
12395 final long origId = Binder.clearCallingIdentity();
12396
12397 if (r != null) {
12398 Intent.FilterComparison filter
12399 = new Intent.FilterComparison(intent);
12400 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012401 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012402 + " at " + b + ": apps="
12403 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012404
12405 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012406 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012407 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012408 // Applications have already bound since the last
12409 // unbind, so just rebind right here.
12410 requestServiceBindingLocked(r, b, true);
12411 } else {
12412 // Note to tell the service the next time there is
12413 // a new client.
12414 b.doRebind = true;
12415 }
12416 }
12417
Per Edelberg78f9fff2010-08-30 20:01:35 +020012418 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419
12420 Binder.restoreCallingIdentity(origId);
12421 }
12422 }
12423 }
12424
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012425 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012426 synchronized(this) {
12427 if (!(token instanceof ServiceRecord)) {
12428 throw new IllegalArgumentException("Invalid service token");
12429 }
12430 ServiceRecord r = (ServiceRecord)token;
12431 boolean inStopping = mStoppingServices.contains(token);
12432 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012433 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012434 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012435 + " with incorrect token: given " + token
12436 + ", expected " + r);
12437 return;
12438 }
12439
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012440 if (type == 1) {
12441 // This is a call from a service start... take care of
12442 // book-keeping.
12443 r.callStart = true;
12444 switch (res) {
12445 case Service.START_STICKY_COMPATIBILITY:
12446 case Service.START_STICKY: {
12447 // We are done with the associated start arguments.
12448 r.findDeliveredStart(startId, true);
12449 // Don't stop if killed.
12450 r.stopIfKilled = false;
12451 break;
12452 }
12453 case Service.START_NOT_STICKY: {
12454 // We are done with the associated start arguments.
12455 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012456 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012457 // There is no more work, and this service
12458 // doesn't want to hang around if killed.
12459 r.stopIfKilled = true;
12460 }
12461 break;
12462 }
12463 case Service.START_REDELIVER_INTENT: {
12464 // We'll keep this item until they explicitly
12465 // call stop for it, but keep track of the fact
12466 // that it was delivered.
12467 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12468 if (si != null) {
12469 si.deliveryCount = 0;
12470 si.doneExecutingCount++;
12471 // Don't stop if killed.
12472 r.stopIfKilled = true;
12473 }
12474 break;
12475 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012476 case Service.START_TASK_REMOVED_COMPLETE: {
12477 // Special processing for onTaskRemoved(). Don't
12478 // impact normal onStartCommand() processing.
12479 r.findDeliveredStart(startId, true);
12480 break;
12481 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012482 default:
12483 throw new IllegalArgumentException(
12484 "Unknown service start result: " + res);
12485 }
12486 if (res == Service.START_STICKY_COMPATIBILITY) {
12487 r.callStart = false;
12488 }
12489 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012490 if (DEBUG_MU)
12491 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12492 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012493 final long origId = Binder.clearCallingIdentity();
12494 serviceDoneExecutingLocked(r, inStopping);
12495 Binder.restoreCallingIdentity(origId);
12496 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012497 Slog.w(TAG, "Done executing unknown service from pid "
12498 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012499 }
12500 }
12501 }
12502
12503 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012504 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12505 + ": nesting=" + r.executeNesting
12506 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012507 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012508 r.executeNesting--;
12509 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012510 if (DEBUG_SERVICE) Slog.v(TAG,
12511 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012512 r.app.executingServices.remove(r);
12513 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012514 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12515 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012516 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12517 }
12518 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012519 if (DEBUG_SERVICE) Slog.v(TAG,
12520 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012521 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012522 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012523 }
12524 updateOomAdjLocked(r.app);
12525 }
12526 }
12527
12528 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012529 String anrMessage = null;
12530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012531 synchronized(this) {
12532 if (proc.executingServices.size() == 0 || proc.thread == null) {
12533 return;
12534 }
12535 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12536 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12537 ServiceRecord timeout = null;
12538 long nextTime = 0;
12539 while (it.hasNext()) {
12540 ServiceRecord sr = it.next();
12541 if (sr.executingStart < maxTime) {
12542 timeout = sr;
12543 break;
12544 }
12545 if (sr.executingStart > nextTime) {
12546 nextTime = sr.executingStart;
12547 }
12548 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012549 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012550 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012551 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012552 } else {
12553 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12554 msg.obj = proc;
12555 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12556 }
12557 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012558
12559 if (anrMessage != null) {
12560 appNotResponding(proc, null, null, anrMessage);
12561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012562 }
12563
12564 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012565 // BACKUP AND RESTORE
12566 // =========================================================
12567
12568 // Cause the target app to be launched if necessary and its backup agent
12569 // instantiated. The backup agent will invoke backupAgentCreated() on the
12570 // activity manager to announce its creation.
12571 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012572 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012573 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12574
12575 synchronized(this) {
12576 // !!! TODO: currently no check here that we're already bound
12577 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12578 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12579 synchronized (stats) {
12580 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12581 }
12582
Dianne Hackborne7f97212011-02-24 14:40:20 -080012583 // Backup agent is now in use, its package can't be stopped.
12584 try {
12585 AppGlobals.getPackageManager().setPackageStoppedState(
12586 app.packageName, false);
12587 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012588 } catch (IllegalArgumentException e) {
12589 Slog.w(TAG, "Failed trying to unstop package "
12590 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012591 }
12592
Christopher Tate181fafa2009-05-14 11:12:14 -070012593 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012594 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12595 ? new ComponentName(app.packageName, app.backupAgentName)
12596 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012597 // startProcessLocked() returns existing proc's record if it's already running
12598 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012599 false, 0, "backup", hostingName, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012600 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012601 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012602 return false;
12603 }
12604
12605 r.app = proc;
12606 mBackupTarget = r;
12607 mBackupAppName = app.packageName;
12608
Christopher Tate6fa95972009-06-05 18:43:55 -070012609 // Try not to kill the process during backup
12610 updateOomAdjLocked(proc);
12611
Christopher Tate181fafa2009-05-14 11:12:14 -070012612 // If the process is already attached, schedule the creation of the backup agent now.
12613 // If it is not yet live, this will be done when it attaches to the framework.
12614 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012615 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012616 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012617 proc.thread.scheduleCreateBackupAgent(app,
12618 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012619 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012620 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012621 }
12622 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012623 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012624 }
12625 // Invariants: at this point, the target app process exists and the application
12626 // is either already running or in the process of coming up. mBackupTarget and
12627 // mBackupAppName describe the app, so that when it binds back to the AM we
12628 // know that it's scheduled for a backup-agent operation.
12629 }
12630
12631 return true;
12632 }
12633
12634 // A backup agent has just come up
12635 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012636 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012637 + " = " + agent);
12638
12639 synchronized(this) {
12640 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012641 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012642 return;
12643 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012644 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012645
Dianne Hackborn06740692010-09-22 22:46:21 -070012646 long oldIdent = Binder.clearCallingIdentity();
12647 try {
12648 IBackupManager bm = IBackupManager.Stub.asInterface(
12649 ServiceManager.getService(Context.BACKUP_SERVICE));
12650 bm.agentConnected(agentPackageName, agent);
12651 } catch (RemoteException e) {
12652 // can't happen; the backup manager service is local
12653 } catch (Exception e) {
12654 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12655 e.printStackTrace();
12656 } finally {
12657 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012658 }
12659 }
12660
12661 // done with this agent
12662 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012663 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012664 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012665 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012666 return;
12667 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012668
12669 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012670 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012671 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012672 return;
12673 }
12674
Christopher Tate181fafa2009-05-14 11:12:14 -070012675 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012676 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012677 return;
12678 }
12679
Christopher Tate6fa95972009-06-05 18:43:55 -070012680 ProcessRecord proc = mBackupTarget.app;
12681 mBackupTarget = null;
12682 mBackupAppName = null;
12683
12684 // Not backing this app up any more; reset its OOM adjustment
12685 updateOomAdjLocked(proc);
12686
Christopher Tatec7b31e32009-06-10 15:49:30 -070012687 // If the app crashed during backup, 'thread' will be null here
12688 if (proc.thread != null) {
12689 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012690 proc.thread.scheduleDestroyBackupAgent(appInfo,
12691 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012692 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012693 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012694 e.printStackTrace();
12695 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012696 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012697 }
12698 }
12699 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012700 // BROADCASTS
12701 // =========================================================
12702
Josh Bartel7f208742010-02-25 11:01:44 -060012703 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012704 List cur) {
12705 final ContentResolver resolver = mContext.getContentResolver();
12706 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12707 if (list == null) {
12708 return cur;
12709 }
12710 int N = list.size();
12711 for (int i=0; i<N; i++) {
12712 Intent intent = list.get(i);
12713 if (filter.match(resolver, intent, true, TAG) >= 0) {
12714 if (cur == null) {
12715 cur = new ArrayList<Intent>();
12716 }
12717 cur.add(intent);
12718 }
12719 }
12720 return cur;
12721 }
12722
Christopher Tatef46723b2012-01-26 14:19:24 -080012723 boolean isPendingBroadcastProcessLocked(int pid) {
12724 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12725 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012727
Christopher Tatef46723b2012-01-26 14:19:24 -080012728 void skipPendingBroadcastLocked(int pid) {
12729 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12730 for (BroadcastQueue queue : mBroadcastQueues) {
12731 queue.skipPendingBroadcastLocked(pid);
12732 }
12733 }
12734
12735 // The app just attached; send any pending broadcasts that it should receive
12736 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12737 boolean didSomething = false;
12738 for (BroadcastQueue queue : mBroadcastQueues) {
12739 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012740 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012741 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012742 }
12743
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012744 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012745 IIntentReceiver receiver, IntentFilter filter, String permission) {
12746 synchronized(this) {
12747 ProcessRecord callerApp = null;
12748 if (caller != null) {
12749 callerApp = getRecordForAppLocked(caller);
12750 if (callerApp == null) {
12751 throw new SecurityException(
12752 "Unable to find app for caller " + caller
12753 + " (pid=" + Binder.getCallingPid()
12754 + ") when registering receiver " + receiver);
12755 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012756 if (callerApp.info.uid != Process.SYSTEM_UID &&
12757 !callerApp.pkgList.contains(callerPackage)) {
12758 throw new SecurityException("Given caller package " + callerPackage
12759 + " is not running in process " + callerApp);
12760 }
12761 } else {
12762 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012763 }
12764
12765 List allSticky = null;
12766
12767 // Look for any matching sticky broadcasts...
12768 Iterator actions = filter.actionsIterator();
12769 if (actions != null) {
12770 while (actions.hasNext()) {
12771 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012772 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012773 }
12774 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012775 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012776 }
12777
12778 // The first sticky in the list is returned directly back to
12779 // the client.
12780 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12781
Joe Onorato8a9b2202010-02-26 18:56:32 -080012782 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012783 + ": " + sticky);
12784
12785 if (receiver == null) {
12786 return sticky;
12787 }
12788
12789 ReceiverList rl
12790 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12791 if (rl == null) {
12792 rl = new ReceiverList(this, callerApp,
12793 Binder.getCallingPid(),
12794 Binder.getCallingUid(), receiver);
12795 if (rl.app != null) {
12796 rl.app.receivers.add(rl);
12797 } else {
12798 try {
12799 receiver.asBinder().linkToDeath(rl, 0);
12800 } catch (RemoteException e) {
12801 return sticky;
12802 }
12803 rl.linkedToDeath = true;
12804 }
12805 mRegisteredReceivers.put(receiver.asBinder(), rl);
12806 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012807 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012808 rl.add(bf);
12809 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012810 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012811 }
12812 mReceiverResolver.addFilter(bf);
12813
12814 // Enqueue broadcasts for all existing stickies that match
12815 // this filter.
12816 if (allSticky != null) {
12817 ArrayList receivers = new ArrayList();
12818 receivers.add(bf);
12819
12820 int N = allSticky.size();
12821 for (int i=0; i<N; i++) {
12822 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012823 BroadcastQueue queue = broadcastQueueForIntent(intent);
12824 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012825 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012826 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012827 queue.enqueueParallelBroadcastLocked(r);
12828 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012829 }
12830 }
12831
12832 return sticky;
12833 }
12834 }
12835
12836 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012837 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012838
Christopher Tatef46723b2012-01-26 14:19:24 -080012839 final long origId = Binder.clearCallingIdentity();
12840 try {
12841 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012842
Christopher Tatef46723b2012-01-26 14:19:24 -080012843 synchronized(this) {
12844 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012845 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012846 if (rl != null) {
12847 if (rl.curBroadcast != null) {
12848 BroadcastRecord r = rl.curBroadcast;
12849 final boolean doNext = finishReceiverLocked(
12850 receiver.asBinder(), r.resultCode, r.resultData,
12851 r.resultExtras, r.resultAbort, true);
12852 if (doNext) {
12853 doTrim = true;
12854 r.queue.processNextBroadcast(false);
12855 }
12856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012857
Christopher Tatef46723b2012-01-26 14:19:24 -080012858 if (rl.app != null) {
12859 rl.app.receivers.remove(rl);
12860 }
12861 removeReceiverLocked(rl);
12862 if (rl.linkedToDeath) {
12863 rl.linkedToDeath = false;
12864 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012866 }
12867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012868
Christopher Tatef46723b2012-01-26 14:19:24 -080012869 // If we actually concluded any broadcasts, we might now be able
12870 // to trim the recipients' apps from our working set
12871 if (doTrim) {
12872 trimApplications();
12873 return;
12874 }
12875
12876 } finally {
12877 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012879 }
12880
12881 void removeReceiverLocked(ReceiverList rl) {
12882 mRegisteredReceivers.remove(rl.receiver.asBinder());
12883 int N = rl.size();
12884 for (int i=0; i<N; i++) {
12885 mReceiverResolver.removeFilter(rl.get(i));
12886 }
12887 }
12888
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012889 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12890 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12891 ProcessRecord r = mLruProcesses.get(i);
12892 if (r.thread != null) {
12893 try {
12894 r.thread.dispatchPackageBroadcast(cmd, packages);
12895 } catch (RemoteException ex) {
12896 }
12897 }
12898 }
12899 }
12900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012901 private final int broadcastIntentLocked(ProcessRecord callerApp,
12902 String callerPackage, Intent intent, String resolvedType,
12903 IIntentReceiver resultTo, int resultCode, String resultData,
12904 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012905 boolean ordered, boolean sticky, int callingPid, int callingUid,
12906 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012907 intent = new Intent(intent);
12908
Dianne Hackborne7f97212011-02-24 14:40:20 -080012909 // By default broadcasts do not go to stopped apps.
12910 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12911
Joe Onorato8a9b2202010-02-26 18:56:32 -080012912 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012913 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12914 + " ordered=" + ordered);
12915 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012916 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012917 }
12918
12919 // Handle special intents: if this broadcast is from the package
12920 // manager about a package being removed, we need to remove all of
12921 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012922 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012923 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012924 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12925 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012926 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012927 || uidRemoved) {
12928 if (checkComponentPermission(
12929 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012930 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012931 == PackageManager.PERMISSION_GRANTED) {
12932 if (uidRemoved) {
12933 final Bundle intentExtras = intent.getExtras();
12934 final int uid = intentExtras != null
12935 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12936 if (uid >= 0) {
12937 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12938 synchronized (bs) {
12939 bs.removeUidStatsLocked(uid);
12940 }
12941 }
12942 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012943 // If resources are unvailble just force stop all
12944 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012945 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012946 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12947 if (list != null && (list.length > 0)) {
12948 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070012949 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012950 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012951 sendPackageBroadcastLocked(
12952 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012953 }
12954 } else {
12955 Uri data = intent.getData();
12956 String ssp;
12957 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12958 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12959 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070012960 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012961 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012962 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012963 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12964 new String[] {ssp});
12965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012966 }
12967 }
12968 }
12969 } else {
12970 String msg = "Permission Denial: " + intent.getAction()
12971 + " broadcast from " + callerPackage + " (pid=" + callingPid
12972 + ", uid=" + callingUid + ")"
12973 + " requires "
12974 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012975 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012976 throw new SecurityException(msg);
12977 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012978
12979 // Special case for adding a package: by default turn on compatibility
12980 // mode.
12981 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012982 Uri data = intent.getData();
12983 String ssp;
12984 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12985 mCompatModePackages.handlePackageAddedLocked(ssp,
12986 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012988 }
12989
12990 /*
12991 * If this is the time zone changed action, queue up a message that will reset the timezone
12992 * of all currently running processes. This message will get queued up before the broadcast
12993 * happens.
12994 */
12995 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12996 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12997 }
12998
Robert Greenwalt03595d02010-11-02 14:08:23 -070012999 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
13000 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
13001 }
13002
Robert Greenwalt434203a2010-10-11 16:00:27 -070013003 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
13004 ProxyProperties proxy = intent.getParcelableExtra("proxy");
13005 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
13006 }
13007
Dianne Hackborn854060af2009-07-09 18:14:31 -070013008 /*
13009 * Prevent non-system code (defined here to be non-persistent
13010 * processes) from sending protected broadcasts.
13011 */
13012 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
13013 || callingUid == Process.SHELL_UID || callingUid == 0) {
13014 // Always okay.
13015 } else if (callerApp == null || !callerApp.persistent) {
13016 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013017 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070013018 intent.getAction())) {
13019 String msg = "Permission Denial: not allowed to send broadcast "
13020 + intent.getAction() + " from pid="
13021 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013022 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070013023 throw new SecurityException(msg);
13024 }
13025 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013026 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070013027 return BROADCAST_SUCCESS;
13028 }
13029 }
13030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013031 // Add to the sticky list if requested.
13032 if (sticky) {
13033 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
13034 callingPid, callingUid)
13035 != PackageManager.PERMISSION_GRANTED) {
13036 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
13037 + callingPid + ", uid=" + callingUid
13038 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013039 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013040 throw new SecurityException(msg);
13041 }
13042 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013043 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013044 + " and enforce permission " + requiredPermission);
13045 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
13046 }
13047 if (intent.getComponent() != null) {
13048 throw new SecurityException(
13049 "Sticky broadcasts can't target a specific component");
13050 }
13051 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13052 if (list == null) {
13053 list = new ArrayList<Intent>();
13054 mStickyBroadcasts.put(intent.getAction(), list);
13055 }
13056 int N = list.size();
13057 int i;
13058 for (i=0; i<N; i++) {
13059 if (intent.filterEquals(list.get(i))) {
13060 // This sticky already exists, replace it.
13061 list.set(i, new Intent(intent));
13062 break;
13063 }
13064 }
13065 if (i >= N) {
13066 list.add(new Intent(intent));
13067 }
13068 }
13069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013070 // Figure out who all will receive this broadcast.
13071 List receivers = null;
13072 List<BroadcastFilter> registeredReceivers = null;
13073 try {
13074 if (intent.getComponent() != null) {
13075 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013076 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070013077 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013078 if (ai != null) {
13079 receivers = new ArrayList();
13080 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070013081 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013082 receivers.add(ri);
13083 }
13084 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070013085 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013086 // Need to resolve the intent to interested receivers...
13087 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
13088 == 0) {
13089 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013090 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013091 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013092 }
Mihai Preda074edef2009-05-18 17:13:31 +020013093 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013094 }
13095 } catch (RemoteException ex) {
13096 // pm is in same process, this will never happen.
13097 }
13098
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013099 final boolean replacePending =
13100 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
13101
Joe Onorato8a9b2202010-02-26 18:56:32 -080013102 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013103 + " replacePending=" + replacePending);
13104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013105 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
13106 if (!ordered && NR > 0) {
13107 // If we are not serializing this broadcast, then send the
13108 // registered receivers separately so they don't wait for the
13109 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080013110 final BroadcastQueue queue = broadcastQueueForIntent(intent);
13111 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013112 callerPackage, callingPid, callingUid, requiredPermission,
13113 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013114 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013115 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080013116 TAG, "Enqueueing parallel broadcast " + r);
13117 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013118 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013119 queue.enqueueParallelBroadcastLocked(r);
13120 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013122 registeredReceivers = null;
13123 NR = 0;
13124 }
13125
13126 // Merge into one list.
13127 int ir = 0;
13128 if (receivers != null) {
13129 // A special case for PACKAGE_ADDED: do not allow the package
13130 // being added to see this broadcast. This prevents them from
13131 // using this as a back door to get run as soon as they are
13132 // installed. Maybe in the future we want to have a special install
13133 // broadcast or such for apps, but we'd like to deliberately make
13134 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013135 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013136 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
13137 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
13138 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013139 Uri data = intent.getData();
13140 if (data != null) {
13141 String pkgName = data.getSchemeSpecificPart();
13142 if (pkgName != null) {
13143 skipPackages = new String[] { pkgName };
13144 }
13145 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013146 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013147 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070013148 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013149 if (skipPackages != null && (skipPackages.length > 0)) {
13150 for (String skipPackage : skipPackages) {
13151 if (skipPackage != null) {
13152 int NT = receivers.size();
13153 for (int it=0; it<NT; it++) {
13154 ResolveInfo curt = (ResolveInfo)receivers.get(it);
13155 if (curt.activityInfo.packageName.equals(skipPackage)) {
13156 receivers.remove(it);
13157 it--;
13158 NT--;
13159 }
13160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013161 }
13162 }
13163 }
13164
13165 int NT = receivers != null ? receivers.size() : 0;
13166 int it = 0;
13167 ResolveInfo curt = null;
13168 BroadcastFilter curr = null;
13169 while (it < NT && ir < NR) {
13170 if (curt == null) {
13171 curt = (ResolveInfo)receivers.get(it);
13172 }
13173 if (curr == null) {
13174 curr = registeredReceivers.get(ir);
13175 }
13176 if (curr.getPriority() >= curt.priority) {
13177 // Insert this broadcast record into the final list.
13178 receivers.add(it, curr);
13179 ir++;
13180 curr = null;
13181 it++;
13182 NT++;
13183 } else {
13184 // Skip to the next ResolveInfo in the final list.
13185 it++;
13186 curt = null;
13187 }
13188 }
13189 }
13190 while (ir < NR) {
13191 if (receivers == null) {
13192 receivers = new ArrayList();
13193 }
13194 receivers.add(registeredReceivers.get(ir));
13195 ir++;
13196 }
13197
13198 if ((receivers != null && receivers.size() > 0)
13199 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013200 BroadcastQueue queue = broadcastQueueForIntent(intent);
13201 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013202 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013203 receivers, resultTo, resultCode, resultData, map, ordered,
13204 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013205 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013206 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080013207 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013208 if (DEBUG_BROADCAST) {
13209 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013210 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013211 }
Christopher Tatef46723b2012-01-26 14:19:24 -080013212 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013213 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013214 queue.enqueueOrderedBroadcastLocked(r);
13215 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013217 }
13218
13219 return BROADCAST_SUCCESS;
13220 }
13221
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013222 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013223 // Refuse possible leaked file descriptors
13224 if (intent != null && intent.hasFileDescriptors() == true) {
13225 throw new IllegalArgumentException("File descriptors passed in Intent");
13226 }
13227
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013228 int flags = intent.getFlags();
13229
13230 if (!mProcessesReady) {
13231 // if the caller really truly claims to know what they're doing, go
13232 // ahead and allow the broadcast without launching any receivers
13233 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
13234 intent = new Intent(intent);
13235 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13236 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
13237 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
13238 + " before boot completion");
13239 throw new IllegalStateException("Cannot broadcast before boot completed");
13240 }
13241 }
13242
13243 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
13244 throw new IllegalArgumentException(
13245 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
13246 }
13247
13248 return intent;
13249 }
13250
13251 public final int broadcastIntent(IApplicationThread caller,
13252 Intent intent, String resolvedType, IIntentReceiver resultTo,
13253 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013254 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013255 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013256 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070013257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013258 final ProcessRecord callerApp = getRecordForAppLocked(caller);
13259 final int callingPid = Binder.getCallingPid();
13260 final int callingUid = Binder.getCallingUid();
13261 final long origId = Binder.clearCallingIdentity();
13262 int res = broadcastIntentLocked(callerApp,
13263 callerApp != null ? callerApp.info.packageName : null,
13264 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070013265 resultCode, resultData, map, requiredPermission, serialized, sticky,
13266 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013267 Binder.restoreCallingIdentity(origId);
13268 return res;
13269 }
13270 }
13271
13272 int broadcastIntentInPackage(String packageName, int uid,
13273 Intent intent, String resolvedType, IIntentReceiver resultTo,
13274 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013275 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013276 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013277 intent = verifyBroadcastLocked(intent);
13278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013279 final long origId = Binder.clearCallingIdentity();
13280 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
13281 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013282 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013283 Binder.restoreCallingIdentity(origId);
13284 return res;
13285 }
13286 }
13287
Amith Yamasani742a6712011-05-04 14:49:28 -070013288 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
13289 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013290 // Refuse possible leaked file descriptors
13291 if (intent != null && intent.hasFileDescriptors() == true) {
13292 throw new IllegalArgumentException("File descriptors passed in Intent");
13293 }
13294
13295 synchronized(this) {
13296 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13297 != PackageManager.PERMISSION_GRANTED) {
13298 String msg = "Permission Denial: unbroadcastIntent() from pid="
13299 + Binder.getCallingPid()
13300 + ", uid=" + Binder.getCallingUid()
13301 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013302 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013303 throw new SecurityException(msg);
13304 }
13305 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13306 if (list != null) {
13307 int N = list.size();
13308 int i;
13309 for (i=0; i<N; i++) {
13310 if (intent.filterEquals(list.get(i))) {
13311 list.remove(i);
13312 break;
13313 }
13314 }
13315 }
13316 }
13317 }
13318
13319 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13320 String resultData, Bundle resultExtras, boolean resultAbort,
13321 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013322 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13323 if (r == null) {
13324 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013325 return false;
13326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013327
Christopher Tatef46723b2012-01-26 14:19:24 -080013328 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13329 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013330 }
13331
13332 public void finishReceiver(IBinder who, int resultCode, String resultData,
13333 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013334 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013335
13336 // Refuse possible leaked file descriptors
13337 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13338 throw new IllegalArgumentException("File descriptors passed in Bundle");
13339 }
13340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013341 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013342 try {
13343 boolean doNext = false;
13344 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013345
Christopher Tatef46723b2012-01-26 14:19:24 -080013346 synchronized(this) {
13347 r = broadcastRecordForReceiverLocked(who);
13348 if (r != null) {
13349 doNext = r.queue.finishReceiverLocked(r, resultCode,
13350 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013352 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013353
Christopher Tatef46723b2012-01-26 14:19:24 -080013354 if (doNext) {
13355 r.queue.processNextBroadcast(false);
13356 }
13357 trimApplications();
13358 } finally {
13359 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013361 }
13362
13363 private final void processCurBroadcastLocked(BroadcastRecord r,
13364 ProcessRecord app) throws RemoteException {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013365 if (DEBUG_BROADCAST) Slog.v(TAG,
13366 "Process cur broadcast " + r + " for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013367 if (app.thread == null) {
13368 throw new RemoteException();
13369 }
13370 r.receiver = app.thread.asBinder();
13371 r.curApp = app;
13372 app.curReceiver = r;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013373 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013374
13375 // Tell the application to launch this receiver.
13376 r.intent.setComponent(r.curComponent);
13377
13378 boolean started = false;
13379 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013380 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013381 "Delivering to component " + r.curComponent
13382 + ": " + r);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070013383 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013384 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
Dianne Hackborne2515ee2011-04-27 18:52:56 -040013385 compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013386 r.resultCode, r.resultData, r.resultExtras, r.ordered);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013387 if (DEBUG_BROADCAST) Slog.v(TAG,
13388 "Process cur broadcast " + r + " DELIVERED for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013389 started = true;
13390 } finally {
13391 if (!started) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013392 if (DEBUG_BROADCAST) Slog.v(TAG,
13393 "Process cur broadcast " + r + ": NOT STARTED!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013394 r.receiver = null;
13395 r.curApp = null;
13396 app.curReceiver = null;
13397 }
13398 }
13399
13400 }
13401
Jeff Brown4d94a762010-09-23 11:33:28 -070013402 static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013403 Intent intent, int resultCode, String data, Bundle extras,
13404 boolean ordered, boolean sticky) throws RemoteException {
Jeff Brown4d94a762010-09-23 11:33:28 -070013405 // Send the intent to the receiver asynchronously using one-way binder calls.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013406 if (app != null && app.thread != null) {
13407 // If we have an app thread, do the call through that so it is
13408 // correctly ordered with other one-way calls.
13409 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013410 data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013411 } else {
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013412 receiver.performReceive(intent, resultCode, data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013413 }
13414 }
13415
Jeff Brown4d94a762010-09-23 11:33:28 -070013416 private final void deliverToRegisteredReceiverLocked(BroadcastRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013417 BroadcastFilter filter, boolean ordered) {
13418 boolean skip = false;
13419 if (filter.requiredPermission != null) {
13420 int perm = checkComponentPermission(filter.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080013421 r.callingPid, r.callingUid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013422 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013423 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013424 + r.intent.toString()
13425 + " from " + r.callerPackage + " (pid="
13426 + r.callingPid + ", uid=" + r.callingUid + ")"
13427 + " requires " + filter.requiredPermission
13428 + " due to registered receiver " + filter);
13429 skip = true;
13430 }
13431 }
13432 if (r.requiredPermission != null) {
13433 int perm = checkComponentPermission(r.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080013434 filter.receiverList.pid, filter.receiverList.uid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013435 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013436 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013437 + r.intent.toString()
13438 + " to " + filter.receiverList.app
13439 + " (pid=" + filter.receiverList.pid
13440 + ", uid=" + filter.receiverList.uid + ")"
13441 + " requires " + r.requiredPermission
13442 + " due to sender " + r.callerPackage
13443 + " (uid " + r.callingUid + ")");
13444 skip = true;
13445 }
13446 }
13447
13448 if (!skip) {
13449 // If this is not being sent as an ordered broadcast, then we
13450 // don't want to touch the fields that keep track of the current
13451 // state of ordered broadcasts.
13452 if (ordered) {
13453 r.receiver = filter.receiverList.receiver.asBinder();
13454 r.curFilter = filter;
13455 filter.receiverList.curBroadcast = r;
13456 r.state = BroadcastRecord.CALL_IN_RECEIVE;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013457 if (filter.receiverList.app != null) {
13458 // Bump hosting application to no longer be in background
13459 // scheduling class. Note that we can't do that if there
13460 // isn't an app... but we can only be in that case for
13461 // things that directly call the IActivityManager API, which
13462 // are already core system stuff so don't matter for this.
13463 r.curApp = filter.receiverList.app;
13464 filter.receiverList.app.curReceiver = r;
13465 updateOomAdjLocked();
13466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013467 }
13468 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013469 if (DEBUG_BROADCAST_LIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013470 int seq = r.intent.getIntExtra("seq", -1);
Dianne Hackborn399cccb2010-04-13 22:57:49 -070013471 Slog.i(TAG, "Delivering to " + filter
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013472 + " (seq=" + seq + "): " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013473 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013474 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013475 new Intent(r.intent), r.resultCode,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013476 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013477 if (ordered) {
13478 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
13479 }
13480 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013481 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013482 if (ordered) {
13483 r.receiver = null;
13484 r.curFilter = null;
13485 filter.receiverList.curBroadcast = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013486 if (filter.receiverList.app != null) {
13487 filter.receiverList.app.curReceiver = null;
13488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013489 }
13490 }
13491 }
13492 }
13493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013494 // =========================================================
13495 // INSTRUMENTATION
13496 // =========================================================
13497
13498 public boolean startInstrumentation(ComponentName className,
13499 String profileFile, int flags, Bundle arguments,
13500 IInstrumentationWatcher watcher) {
13501 // Refuse possible leaked file descriptors
13502 if (arguments != null && arguments.hasFileDescriptors()) {
13503 throw new IllegalArgumentException("File descriptors passed in Bundle");
13504 }
13505
13506 synchronized(this) {
13507 InstrumentationInfo ii = null;
13508 ApplicationInfo ai = null;
13509 try {
13510 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013511 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013512 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013513 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013514 } catch (PackageManager.NameNotFoundException e) {
13515 }
13516 if (ii == null) {
13517 reportStartInstrumentationFailure(watcher, className,
13518 "Unable to find instrumentation info for: " + className);
13519 return false;
13520 }
13521 if (ai == null) {
13522 reportStartInstrumentationFailure(watcher, className,
13523 "Unable to find instrumentation target package: " + ii.targetPackage);
13524 return false;
13525 }
13526
13527 int match = mContext.getPackageManager().checkSignatures(
13528 ii.targetPackage, ii.packageName);
13529 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13530 String msg = "Permission Denial: starting instrumentation "
13531 + className + " from pid="
13532 + Binder.getCallingPid()
13533 + ", uid=" + Binder.getCallingPid()
13534 + " not allowed because package " + ii.packageName
13535 + " does not have a signature matching the target "
13536 + ii.targetPackage;
13537 reportStartInstrumentationFailure(watcher, className, msg);
13538 throw new SecurityException(msg);
13539 }
13540
13541 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013542 // Instrumentation can kill and relaunch even persistent processes
13543 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013544 ProcessRecord app = addAppLocked(ai);
13545 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013546 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013547 app.instrumentationProfileFile = profileFile;
13548 app.instrumentationArguments = arguments;
13549 app.instrumentationWatcher = watcher;
13550 app.instrumentationResultClass = className;
13551 Binder.restoreCallingIdentity(origId);
13552 }
13553
13554 return true;
13555 }
13556
13557 /**
13558 * Report errors that occur while attempting to start Instrumentation. Always writes the
13559 * error to the logs, but if somebody is watching, send the report there too. This enables
13560 * the "am" command to report errors with more information.
13561 *
13562 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13563 * @param cn The component name of the instrumentation.
13564 * @param report The error report.
13565 */
13566 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13567 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013568 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013569 try {
13570 if (watcher != null) {
13571 Bundle results = new Bundle();
13572 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13573 results.putString("Error", report);
13574 watcher.instrumentationStatus(cn, -1, results);
13575 }
13576 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013577 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013578 }
13579 }
13580
13581 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13582 if (app.instrumentationWatcher != null) {
13583 try {
13584 // NOTE: IInstrumentationWatcher *must* be oneway here
13585 app.instrumentationWatcher.instrumentationFinished(
13586 app.instrumentationClass,
13587 resultCode,
13588 results);
13589 } catch (RemoteException e) {
13590 }
13591 }
13592 app.instrumentationWatcher = null;
13593 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013594 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013595 app.instrumentationProfileFile = null;
13596 app.instrumentationArguments = null;
13597
Christopher Tate3dacd842011-08-19 14:56:15 -070013598 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013599 }
13600
13601 public void finishInstrumentation(IApplicationThread target,
13602 int resultCode, Bundle results) {
13603 // Refuse possible leaked file descriptors
13604 if (results != null && results.hasFileDescriptors()) {
13605 throw new IllegalArgumentException("File descriptors passed in Intent");
13606 }
13607
13608 synchronized(this) {
13609 ProcessRecord app = getRecordForAppLocked(target);
13610 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013611 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013612 return;
13613 }
13614 final long origId = Binder.clearCallingIdentity();
13615 finishInstrumentationLocked(app, resultCode, results);
13616 Binder.restoreCallingIdentity(origId);
13617 }
13618 }
13619
13620 // =========================================================
13621 // CONFIGURATION
13622 // =========================================================
13623
13624 public ConfigurationInfo getDeviceConfigurationInfo() {
13625 ConfigurationInfo config = new ConfigurationInfo();
13626 synchronized (this) {
13627 config.reqTouchScreen = mConfiguration.touchscreen;
13628 config.reqKeyboardType = mConfiguration.keyboard;
13629 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013630 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13631 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013632 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13633 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013634 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13635 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013636 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13637 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013638 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013639 }
13640 return config;
13641 }
13642
13643 public Configuration getConfiguration() {
13644 Configuration ci;
13645 synchronized(this) {
13646 ci = new Configuration(mConfiguration);
13647 }
13648 return ci;
13649 }
13650
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013651 public void updatePersistentConfiguration(Configuration values) {
13652 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13653 "updateConfiguration()");
13654 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13655 "updateConfiguration()");
13656 if (values == null) {
13657 throw new NullPointerException("Configuration must not be null");
13658 }
13659
13660 synchronized(this) {
13661 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013662 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013663 Binder.restoreCallingIdentity(origId);
13664 }
13665 }
13666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013667 public void updateConfiguration(Configuration values) {
13668 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13669 "updateConfiguration()");
13670
13671 synchronized(this) {
13672 if (values == null && mWindowManager != null) {
13673 // sentinel: fetch the current configuration from the window manager
13674 values = mWindowManager.computeNewConfiguration();
13675 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013676
13677 if (mWindowManager != null) {
13678 mProcessList.applyDisplaySize(mWindowManager);
13679 }
13680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013681 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013682 if (values != null) {
13683 Settings.System.clearConfiguration(values);
13684 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013685 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013686 Binder.restoreCallingIdentity(origId);
13687 }
13688 }
13689
13690 /**
13691 * Do either or both things: (1) change the current configuration, and (2)
13692 * make sure the given activity is running with the (now) current
13693 * configuration. Returns true if the activity has been left running, or
13694 * false if <var>starting</var> is being destroyed to match the new
13695 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013696 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013697 */
13698 public boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013699 ActivityRecord starting, boolean persistent, boolean initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013700 int changes = 0;
13701
13702 boolean kept = true;
13703
13704 if (values != null) {
13705 Configuration newConfig = new Configuration(mConfiguration);
13706 changes = newConfig.updateFrom(values);
13707 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013708 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013709 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013710 }
13711
Doug Zongker2bec3d42009-12-04 12:52:44 -080013712 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013713
Dianne Hackborn813075a62011-11-14 17:45:19 -080013714 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013715 saveLocaleLocked(values.locale,
13716 !values.locale.equals(mConfiguration.locale),
13717 values.userSetLocale);
13718 }
13719
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013720 mConfigurationSeq++;
13721 if (mConfigurationSeq <= 0) {
13722 mConfigurationSeq = 1;
13723 }
13724 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013725 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013726 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013727
13728 final Configuration configCopy = new Configuration(mConfiguration);
13729
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013730 AttributeCache ac = AttributeCache.instance();
13731 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013732 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013734
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013735 // Make sure all resources in our process are updated
13736 // right now, so that anyone who is going to retrieve
13737 // resource values after we return will be sure to get
13738 // the new ones. This is especially important during
13739 // boot, where the first config change needs to guarantee
13740 // all resources have that config before following boot
13741 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013742 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013743
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013744 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013745 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013746 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013747 mHandler.sendMessage(msg);
13748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013749
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013750 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13751 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013752 try {
13753 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013754 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013755 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013756 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013757 }
13758 } catch (Exception e) {
13759 }
13760 }
13761 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013762 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13763 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013764 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013765 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013766 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13767 broadcastIntentLocked(null, null,
13768 new Intent(Intent.ACTION_LOCALE_CHANGED),
13769 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013770 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013772 }
13773 }
13774
13775 if (changes != 0 && starting == null) {
13776 // If the configuration changed, and the caller is not already
13777 // in the process of starting an activity, then find the top
13778 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013779 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013780 }
13781
13782 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013783 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013784 // And we need to make sure at this point that all other activities
13785 // are made visible with the correct configuration.
13786 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013787 }
13788
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013789 if (values != null && mWindowManager != null) {
13790 mWindowManager.setNewConfiguration(mConfiguration);
13791 }
13792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013793 return kept;
13794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013795
13796 /**
13797 * Save the locale. You must be inside a synchronized (this) block.
13798 */
13799 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13800 if(isDiff) {
13801 SystemProperties.set("user.language", l.getLanguage());
13802 SystemProperties.set("user.region", l.getCountry());
13803 }
13804
13805 if(isPersist) {
13806 SystemProperties.set("persist.sys.language", l.getLanguage());
13807 SystemProperties.set("persist.sys.country", l.getCountry());
13808 SystemProperties.set("persist.sys.localevar", l.getVariant());
13809 }
13810 }
13811
13812 // =========================================================
13813 // LIFETIME MANAGEMENT
13814 // =========================================================
13815
Christopher Tatef46723b2012-01-26 14:19:24 -080013816 // Returns which broadcast queue the app is the current [or imminent] receiver
13817 // on, or 'null' if the app is not an active broadcast recipient.
13818 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13819 BroadcastRecord r = app.curReceiver;
13820 if (r != null) {
13821 return r.queue;
13822 }
13823
13824 // It's not the current receiver, but it might be starting up to become one
13825 synchronized (this) {
13826 for (BroadcastQueue queue : mBroadcastQueues) {
13827 r = queue.mPendingBroadcast;
13828 if (r != null && r.curApp == app) {
13829 // found it; report which queue it's in
13830 return queue;
13831 }
13832 }
13833 }
13834
13835 return null;
13836 }
13837
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013838 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013839 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013840 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013841 // This adjustment has already been computed. If we are calling
13842 // from the top, we may have already computed our adjustment with
13843 // an earlier hidden adjustment that isn't really for us... if
13844 // so, use the new hidden adjustment.
13845 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013846 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013847 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013848 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013849 }
13850
13851 if (app.thread == null) {
13852 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013853 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013854 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013855 }
13856
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013857 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13858 app.adjSource = null;
13859 app.adjTarget = null;
13860 app.empty = false;
13861 app.hidden = false;
13862
13863 final int activitiesSize = app.activities.size();
13864
Dianne Hackborn7d608422011-08-07 16:24:18 -070013865 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013866 // The max adjustment doesn't allow this app to be anything
13867 // below foreground, so it is not worth doing work for it.
13868 app.adjType = "fixed";
13869 app.adjSeq = mAdjSeq;
13870 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013871 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013872 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013873 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013874 // System process can do UI, and when they do we want to have
13875 // them trim their memory after the user leaves the UI. To
13876 // facilitate this, here we need to determine whether or not it
13877 // is currently showing UI.
13878 app.systemNoUi = true;
13879 if (app == TOP_APP) {
13880 app.systemNoUi = false;
13881 } else if (activitiesSize > 0) {
13882 for (int j = 0; j < activitiesSize; j++) {
13883 final ActivityRecord r = app.activities.get(j);
13884 if (r.visible) {
13885 app.systemNoUi = false;
13886 break;
13887 }
13888 }
13889 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013890 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013891 }
13892
13893 final boolean hadForegroundActivities = app.foregroundActivities;
13894
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013895 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013896 app.keeping = false;
13897 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013898
The Android Open Source Project4df24232009-03-05 14:34:35 -080013899 // Determine the importance of the process, starting with most
13900 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013901 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013902 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013903 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013904 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013905 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013906 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013907 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013908 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013909 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013910 } else if (app.instrumentationClass != null) {
13911 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013912 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013913 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013914 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013915 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013916 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013917 // counts as being in the foreground for OOM killer purposes.
13918 // It's placed in a sched group based on the nature of the
13919 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013920 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013921 schedGroup = (queue == mFgBroadcastQueue)
13922 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013923 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013924 } else if (app.executingServices.size() > 0) {
13925 // An app that is currently executing a service callback also
13926 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013927 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013928 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013929 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013930 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013931 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013932 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013933 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013934 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013935 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013936 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013937 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013938 // A very not-needed process. If this is lower in the lru list,
13939 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013940 adj = hiddenAdj;
13941 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013942 app.hidden = true;
13943 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013944 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013945 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013946
13947 // Examine all activities if not already foreground.
13948 if (!app.foregroundActivities && activitiesSize > 0) {
13949 for (int j = 0; j < activitiesSize; j++) {
13950 final ActivityRecord r = app.activities.get(j);
13951 if (r.visible) {
13952 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013953 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13954 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013955 app.adjType = "visible";
13956 }
13957 schedGroup = Process.THREAD_GROUP_DEFAULT;
13958 app.hidden = false;
13959 app.foregroundActivities = true;
13960 break;
13961 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13962 || r.state == ActivityState.STOPPING) {
13963 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013964 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13965 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013966 app.adjType = "stopping";
13967 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013968 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013969 app.foregroundActivities = true;
13970 }
13971 }
13972 }
13973
Dianne Hackborn7d608422011-08-07 16:24:18 -070013974 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013975 if (app.foregroundServices) {
13976 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013977 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013978 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013979 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013980 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013981 } else if (app.forcingToForeground != null) {
13982 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013983 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013984 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013985 app.adjType = "force-foreground";
13986 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013987 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013988 }
13989 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013990
Dianne Hackborn7d608422011-08-07 16:24:18 -070013991 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013992 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013993 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013994 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013995 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013996 app.adjType = "heavy";
13997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013998
Dianne Hackborn7d608422011-08-07 16:24:18 -070013999 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014000 // This process is hosting what we currently consider to be the
14001 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014002 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014003 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014004 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080014005 app.adjType = "home";
14006 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014007
Dianne Hackbornf35fe232011-11-01 19:25:20 -070014008 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
14009 && app.activities.size() > 0) {
14010 // This was the previous process that showed UI to the user.
14011 // We want to try to keep it around more aggressively, to give
14012 // a good experience around switching between two apps.
14013 adj = ProcessList.PREVIOUS_APP_ADJ;
14014 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
14015 app.hidden = false;
14016 app.adjType = "previous";
14017 }
14018
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014019 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
14020 + " reason=" + app.adjType);
14021
The Android Open Source Project4df24232009-03-05 14:34:35 -080014022 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014023 // there are applications dependent on our services or providers, but
14024 // this gives us a baseline and makes sure we don't get into an
14025 // infinite recursion.
14026 app.adjSeq = mAdjSeq;
14027 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014028
Christopher Tate6fa95972009-06-05 18:43:55 -070014029 if (mBackupTarget != null && app == mBackupTarget.app) {
14030 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070014031 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014032 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014033 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014034 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014035 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070014036 }
14037 }
14038
Dianne Hackborn7d608422011-08-07 16:24:18 -070014039 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014040 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014041 final long now = SystemClock.uptimeMillis();
14042 // This process is more important if the top activity is
14043 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070014044 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014045 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014046 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014047 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014048 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014049 // If this process has shown some UI, let it immediately
14050 // go to the LRU list because it may be pretty heavy with
14051 // UI stuff. We'll tag it with a label just to help
14052 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014053 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014054 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014055 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014056 } else {
14057 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
14058 // This service has seen some activity within
14059 // recent memory, so we will keep its process ahead
14060 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014061 if (adj > ProcessList.SERVICE_ADJ) {
14062 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014063 app.adjType = "started-services";
14064 app.hidden = false;
14065 }
14066 }
14067 // If we have let the service slide into the background
14068 // state, still have some text describing what it is doing
14069 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014070 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014071 app.adjType = "started-bg-services";
14072 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014073 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014074 // Don't kill this process because it is doing work; it
14075 // has said it is doing work.
14076 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014077 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014078 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014079 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014080 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014081 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014082 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014083 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014084 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014085 // XXX should compute this based on the max of
14086 // all connected clients.
14087 ConnectionRecord cr = clist.get(i);
14088 if (cr.binding.client == app) {
14089 // Binding to ourself is not interesting.
14090 continue;
14091 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014092 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014093 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014094 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014095 int myHiddenAdj = hiddenAdj;
14096 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014097 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014098 myHiddenAdj = client.hiddenAdj;
14099 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014100 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014101 }
14102 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014103 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014104 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014105 String adjType = null;
14106 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
14107 // Not doing bind OOM management, so treat
14108 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014109 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014110 // If this process has shown some UI, let it immediately
14111 // go to the LRU list because it may be pretty heavy with
14112 // UI stuff. We'll tag it with a label just to help
14113 // debug and understand what is going on.
14114 if (adj > clientAdj) {
14115 adjType = "bound-bg-ui-services";
14116 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014117 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014118 clientAdj = adj;
14119 } else {
14120 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
14121 // This service has not seen activity within
14122 // recent memory, so allow it to drop to the
14123 // LRU list if there is no other reason to keep
14124 // it around. We'll also tag it with a label just
14125 // to help debug and undertand what is going on.
14126 if (adj > clientAdj) {
14127 adjType = "bound-bg-services";
14128 }
14129 clientAdj = adj;
14130 }
14131 }
14132 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014133 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014134 // If this process has recently shown UI, and
14135 // the process that is binding to it is less
14136 // important than being visible, then we don't
14137 // care about the binding as much as we care
14138 // about letting this process get into the LRU
14139 // list to be killed and restarted if needed for
14140 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014141 if (app.hasShownUi && app != mHomeProcess
14142 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014143 adjType = "bound-bg-ui-services";
14144 } else {
14145 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
14146 |Context.BIND_IMPORTANT)) != 0) {
14147 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014148 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
14149 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
14150 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14151 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14152 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014153 adj = clientAdj;
14154 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014155 app.pendingUiClean = true;
14156 if (adj > ProcessList.VISIBLE_APP_ADJ) {
14157 adj = ProcessList.VISIBLE_APP_ADJ;
14158 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014159 }
14160 if (!client.hidden) {
14161 app.hidden = false;
14162 }
14163 if (client.keeping) {
14164 app.keeping = true;
14165 }
14166 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014167 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014168 }
14169 if (adjType != null) {
14170 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014171 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14172 .REASON_SERVICE_IN_USE;
14173 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014174 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014175 app.adjTarget = s.name;
14176 }
14177 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14178 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14179 schedGroup = Process.THREAD_GROUP_DEFAULT;
14180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014181 }
14182 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014183 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
14184 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014185 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014186 (a.visible || a.state == ActivityState.RESUMED
14187 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014188 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014189 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14190 schedGroup = Process.THREAD_GROUP_DEFAULT;
14191 }
14192 app.hidden = false;
14193 app.adjType = "service";
14194 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14195 .REASON_SERVICE_IN_USE;
14196 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014197 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014198 app.adjTarget = s.name;
14199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014201 }
14202 }
14203 }
14204 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014205
Dianne Hackborn287952c2010-09-22 22:34:31 -070014206 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014207 // would like to avoid killing it unless it would prevent the current
14208 // application from running. By default we put the process in
14209 // with the rest of the background processes; as we scan through
14210 // its services we may bump it up from there.
14211 if (adj > hiddenAdj) {
14212 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014213 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014214 app.adjType = "bg-services";
14215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014216 }
14217
Dianne Hackborn7d608422011-08-07 16:24:18 -070014218 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014219 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014220 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014221 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014222 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014223 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014224 if (cpr.clients.size() != 0) {
14225 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014226 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014227 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070014228 if (client == app) {
14229 // Being our own client is not interesting.
14230 continue;
14231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014232 int myHiddenAdj = hiddenAdj;
14233 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014234 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014235 myHiddenAdj = client.hiddenAdj;
14236 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014237 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014238 }
14239 }
14240 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014241 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014242 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014243 if (app.hasShownUi && app != mHomeProcess
14244 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014245 app.adjType = "bg-ui-provider";
14246 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014247 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
14248 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014249 app.adjType = "provider";
14250 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014251 if (!client.hidden) {
14252 app.hidden = false;
14253 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014254 if (client.keeping) {
14255 app.keeping = true;
14256 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070014257 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14258 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014259 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014260 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014261 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014262 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014263 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14264 schedGroup = Process.THREAD_GROUP_DEFAULT;
14265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014266 }
14267 }
14268 // If the provider has external (non-framework) process
14269 // dependencies, ensure that its adjustment is at least
14270 // FOREGROUND_APP_ADJ.
14271 if (cpr.externals != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014272 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
14273 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014274 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014275 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014276 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014277 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014278 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014279 }
14280 }
14281 }
14282 }
14283
14284 app.curRawAdj = adj;
14285
Joe Onorato8a9b2202010-02-26 18:56:32 -080014286 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014287 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14288 if (adj > app.maxAdj) {
14289 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014290 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014291 schedGroup = Process.THREAD_GROUP_DEFAULT;
14292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014293 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014294 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014295 app.keeping = true;
14296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014297
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014298 if (app.hasAboveClient) {
14299 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14300 // then we need to drop its adjustment to be lower than the service's
14301 // in order to honor the request. We want to drop it by one adjustment
14302 // level... but there is special meaning applied to various levels so
14303 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014304 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014305 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014306 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14307 adj = ProcessList.VISIBLE_APP_ADJ;
14308 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14309 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14310 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14311 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014312 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014313 adj++;
14314 }
14315 }
14316
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014317 if (adj == ProcessList.SERVICE_ADJ) {
14318 if (doingAll) {
14319 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
14320 mNewNumServiceProcs++;
14321 }
14322 if (app.serviceb) {
14323 adj = ProcessList.SERVICE_B_ADJ;
14324 }
14325 } else {
14326 app.serviceb = false;
14327 }
14328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014329 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014330 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014331
14332 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014333 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14334 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014335 }
14336
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014337 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014338 }
14339
14340 /**
14341 * Ask a given process to GC right now.
14342 */
14343 final void performAppGcLocked(ProcessRecord app) {
14344 try {
14345 app.lastRequestedGc = SystemClock.uptimeMillis();
14346 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014347 if (app.reportLowMemory) {
14348 app.reportLowMemory = false;
14349 app.thread.scheduleLowMemory();
14350 } else {
14351 app.thread.processInBackground();
14352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014353 }
14354 } catch (Exception e) {
14355 // whatever.
14356 }
14357 }
14358
14359 /**
14360 * Returns true if things are idle enough to perform GCs.
14361 */
Josh Bartel7f208742010-02-25 11:01:44 -060014362 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014363 boolean processingBroadcasts = false;
14364 for (BroadcastQueue q : mBroadcastQueues) {
14365 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14366 processingBroadcasts = true;
14367 }
14368 }
14369 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014370 && (mSleeping || (mMainStack.mResumedActivity != null &&
14371 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014372 }
14373
14374 /**
14375 * Perform GCs on all processes that are waiting for it, but only
14376 * if things are idle.
14377 */
14378 final void performAppGcsLocked() {
14379 final int N = mProcessesToGc.size();
14380 if (N <= 0) {
14381 return;
14382 }
Josh Bartel7f208742010-02-25 11:01:44 -060014383 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014384 while (mProcessesToGc.size() > 0) {
14385 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014386 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014387 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14388 <= SystemClock.uptimeMillis()) {
14389 // To avoid spamming the system, we will GC processes one
14390 // at a time, waiting a few seconds between each.
14391 performAppGcLocked(proc);
14392 scheduleAppGcsLocked();
14393 return;
14394 } else {
14395 // It hasn't been long enough since we last GCed this
14396 // process... put it in the list to wait for its time.
14397 addProcessToGcListLocked(proc);
14398 break;
14399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014400 }
14401 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014402
14403 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014404 }
14405 }
14406
14407 /**
14408 * If all looks good, perform GCs on all processes waiting for them.
14409 */
14410 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014411 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014412 performAppGcsLocked();
14413 return;
14414 }
14415 // Still not idle, wait some more.
14416 scheduleAppGcsLocked();
14417 }
14418
14419 /**
14420 * Schedule the execution of all pending app GCs.
14421 */
14422 final void scheduleAppGcsLocked() {
14423 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014424
14425 if (mProcessesToGc.size() > 0) {
14426 // Schedule a GC for the time to the next process.
14427 ProcessRecord proc = mProcessesToGc.get(0);
14428 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14429
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014430 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014431 long now = SystemClock.uptimeMillis();
14432 if (when < (now+GC_TIMEOUT)) {
14433 when = now + GC_TIMEOUT;
14434 }
14435 mHandler.sendMessageAtTime(msg, when);
14436 }
14437 }
14438
14439 /**
14440 * Add a process to the array of processes waiting to be GCed. Keeps the
14441 * list in sorted order by the last GC time. The process can't already be
14442 * on the list.
14443 */
14444 final void addProcessToGcListLocked(ProcessRecord proc) {
14445 boolean added = false;
14446 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14447 if (mProcessesToGc.get(i).lastRequestedGc <
14448 proc.lastRequestedGc) {
14449 added = true;
14450 mProcessesToGc.add(i+1, proc);
14451 break;
14452 }
14453 }
14454 if (!added) {
14455 mProcessesToGc.add(0, proc);
14456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014457 }
14458
14459 /**
14460 * Set up to ask a process to GC itself. This will either do it
14461 * immediately, or put it on the list of processes to gc the next
14462 * time things are idle.
14463 */
14464 final void scheduleAppGcLocked(ProcessRecord app) {
14465 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014466 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014467 return;
14468 }
14469 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014470 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014471 scheduleAppGcsLocked();
14472 }
14473 }
14474
Dianne Hackborn287952c2010-09-22 22:34:31 -070014475 final void checkExcessivePowerUsageLocked(boolean doKills) {
14476 updateCpuStatsNow();
14477
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014478 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014479 boolean doWakeKills = doKills;
14480 boolean doCpuKills = doKills;
14481 if (mLastPowerCheckRealtime == 0) {
14482 doWakeKills = false;
14483 }
14484 if (mLastPowerCheckUptime == 0) {
14485 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014486 }
14487 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014488 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014489 }
14490 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014491 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14492 final long curUptime = SystemClock.uptimeMillis();
14493 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14494 mLastPowerCheckRealtime = curRealtime;
14495 mLastPowerCheckUptime = curUptime;
14496 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14497 doWakeKills = false;
14498 }
14499 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14500 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014501 }
14502 int i = mLruProcesses.size();
14503 while (i > 0) {
14504 i--;
14505 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014506 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014507 long wtime;
14508 synchronized (stats) {
14509 wtime = stats.getProcessWakeTime(app.info.uid,
14510 app.pid, curRealtime);
14511 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014512 long wtimeUsed = wtime - app.lastWakeTime;
14513 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14514 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014515 StringBuilder sb = new StringBuilder(128);
14516 sb.append("Wake for ");
14517 app.toShortString(sb);
14518 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014519 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014520 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014521 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014522 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014523 sb.append((wtimeUsed*100)/realtimeSince);
14524 sb.append("%)");
14525 Slog.i(TAG, sb.toString());
14526 sb.setLength(0);
14527 sb.append("CPU for ");
14528 app.toShortString(sb);
14529 sb.append(": over ");
14530 TimeUtils.formatDuration(uptimeSince, sb);
14531 sb.append(" used ");
14532 TimeUtils.formatDuration(cputimeUsed, sb);
14533 sb.append(" (");
14534 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014535 sb.append("%)");
14536 Slog.i(TAG, sb.toString());
14537 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014538 // If a process has held a wake lock for more
14539 // than 50% of the time during this period,
14540 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014541 if (doWakeKills && realtimeSince > 0
14542 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14543 synchronized (stats) {
14544 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14545 realtimeSince, wtimeUsed);
14546 }
14547 Slog.w(TAG, "Excessive wake lock in " + app.processName
14548 + " (pid " + app.pid + "): held " + wtimeUsed
14549 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014550 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14551 app.processName, app.setAdj, "excessive wake lock");
14552 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014553 } else if (doCpuKills && uptimeSince > 0
14554 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14555 synchronized (stats) {
14556 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14557 uptimeSince, cputimeUsed);
14558 }
14559 Slog.w(TAG, "Excessive CPU in " + app.processName
14560 + " (pid " + app.pid + "): used " + cputimeUsed
14561 + " during " + uptimeSince);
14562 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14563 app.processName, app.setAdj, "excessive cpu");
14564 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014565 } else {
14566 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014567 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014568 }
14569 }
14570 }
14571 }
14572
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014573 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014574 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014575 app.hiddenAdj = hiddenAdj;
14576
14577 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014578 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014579 }
14580
Dianne Hackborn287952c2010-09-22 22:34:31 -070014581 final boolean wasKeeping = app.keeping;
14582
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014583 boolean success = true;
14584
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014585 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014586
Jeff Brown10e89712011-07-08 18:52:57 -070014587 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070014588 if (false) {
14589 // Removing for now. Forcing GCs is not so useful anymore
14590 // with Dalvik, and the new memory level hint facility is
14591 // better for what we need to do these days.
14592 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14593 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14594 // If this app is transitioning from foreground to
14595 // non-foreground, have it do a gc.
14596 scheduleAppGcLocked(app);
14597 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14598 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14599 // Likewise do a gc when an app is moving in to the
14600 // background (such as a service stopping).
14601 scheduleAppGcLocked(app);
14602 }
Jeff Brown10e89712011-07-08 18:52:57 -070014603 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014604
Jeff Brown10e89712011-07-08 18:52:57 -070014605 if (wasKeeping && !app.keeping) {
14606 // This app is no longer something we want to keep. Note
14607 // its current wake lock time to later know to kill it if
14608 // it is not behaving well.
14609 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14610 synchronized (stats) {
14611 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14612 app.pid, SystemClock.elapsedRealtime());
14613 }
14614 app.lastCpuTime = app.curCpuTime;
14615 }
14616
14617 app.setRawAdj = app.curRawAdj;
14618 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014619
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014620 if (app.curAdj != app.setAdj) {
14621 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014622 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014623 TAG, "Set " + app.pid + " " + app.processName +
14624 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014625 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014626 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014627 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014628 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014629 }
14630 }
14631 if (app.setSchedGroup != app.curSchedGroup) {
14632 app.setSchedGroup = app.curSchedGroup;
14633 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14634 "Setting process group of " + app.processName
14635 + " to " + app.curSchedGroup);
14636 if (app.waitingToKill != null &&
14637 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14638 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14639 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14640 app.processName, app.setAdj, app.waitingToKill);
14641 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014642 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014643 } else {
14644 if (true) {
14645 long oldId = Binder.clearCallingIdentity();
14646 try {
14647 Process.setProcessGroup(app.pid, app.curSchedGroup);
14648 } catch (Exception e) {
14649 Slog.w(TAG, "Failed setting process group of " + app.pid
14650 + " to " + app.curSchedGroup);
14651 e.printStackTrace();
14652 } finally {
14653 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014654 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014655 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014656 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014657 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014658 app.thread.setSchedulingGroup(app.curSchedGroup);
14659 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014660 }
14661 }
14662 }
14663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014664 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014665 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014666 }
14667
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014668 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014669 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014670 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborncbb722e2012-02-07 18:33:49 -080014671 for (int i=mMainStack.mPausingActivities.size()-1; i>=0; i--) {
14672 ActivityRecord r = mMainStack.mPausingActivities.get(i);
14673 if (r.app != null) {
14674 resumedActivity = r;
14675 break;
14676 }
14677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014678 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014679 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014680 }
14681 }
14682 return resumedActivity;
14683 }
14684
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014685 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014686 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014687 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14688 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014689 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14690 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014691
14692 mAdjSeq++;
14693
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014694 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014695 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14696 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014697 if (nowHidden != wasHidden) {
14698 // Changed to/from hidden state, so apps after it in the LRU
14699 // list may also be changed.
14700 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014701 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014702 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014703 }
14704
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014705 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014706 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014707 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14708
14709 if (false) {
14710 RuntimeException e = new RuntimeException();
14711 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014712 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014713 }
14714
14715 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014716 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014717
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014718 // Let's determine how many processes we have running vs.
14719 // how many slots we have for background processes; we may want
14720 // to put multiple processes in a slot of there are enough of
14721 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014722 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014723 int factor = (mLruProcesses.size()-4)/numSlots;
14724 if (factor < 1) factor = 1;
14725 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014726 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014727
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014728 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014729 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014730 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014731 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014732 while (i > 0) {
14733 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014734 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014735 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014736 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14737 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014738 && app.curAdj == curHiddenAdj) {
14739 step++;
14740 if (step >= factor) {
14741 step = 0;
14742 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014743 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014744 }
14745 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014746 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014747 numHidden++;
14748 if (numHidden > mProcessLimit) {
14749 Slog.i(TAG, "No longer want " + app.processName
14750 + " (pid " + app.pid + "): hidden #" + numHidden);
14751 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14752 app.processName, app.setAdj, "too many background");
14753 app.killedBackground = true;
14754 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014755 }
14756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014757 }
14758 }
14759
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014760 mNumServiceProcs = mNewNumServiceProcs;
14761
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014762 // Now determine the memory trimming level of background processes.
14763 // Unfortunately we need to start at the back of the list to do this
14764 // properly. We only do this if the number of background apps we
14765 // are managing to keep around is less than half the maximum we desire;
14766 // if we are keeping a good number around, we'll let them use whatever
14767 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014768 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014769 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014770 factor = numHidden/3;
14771 int minFactor = 2;
14772 if (mHomeProcess != null) minFactor++;
14773 if (mPreviousProcess != null) minFactor++;
14774 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014775 step = 0;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014776 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014777 for (i=0; i<N; i++) {
14778 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014779 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14780 && app.curAdj != ProcessList.SERVICE_B_ADJ
14781 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014782 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14783 try {
14784 app.thread.scheduleTrimMemory(curLevel);
14785 } catch (RemoteException e) {
14786 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014787 if (false) {
14788 // For now we won't do this; our memory trimming seems
14789 // to be good enough at this point that destroying
14790 // activities causes more harm than good.
14791 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14792 && app != mHomeProcess && app != mPreviousProcess) {
14793 // For these apps we will also finish their activities
14794 // to help them free memory.
14795 mMainStack.destroyActivitiesLocked(app, false, "trim");
14796 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014797 }
14798 }
14799 app.trimMemoryLevel = curLevel;
14800 step++;
14801 if (step >= factor) {
14802 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014803 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14804 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014805 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014806 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14807 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014808 break;
14809 }
14810 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014811 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014812 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014813 && app.thread != null) {
14814 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014815 app.thread.scheduleTrimMemory(
14816 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014817 } catch (RemoteException e) {
14818 }
14819 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014820 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014821 } else if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014822 && app.pendingUiClean) {
14823 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14824 && app.thread != null) {
14825 try {
14826 app.thread.scheduleTrimMemory(
14827 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14828 } catch (RemoteException e) {
14829 }
14830 }
14831 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14832 app.pendingUiClean = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014833 } else {
14834 app.trimMemoryLevel = 0;
14835 }
14836 }
14837 } else {
14838 final int N = mLruProcesses.size();
14839 for (i=0; i<N; i++) {
14840 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014841 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014842 && app.pendingUiClean) {
14843 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14844 && app.thread != null) {
14845 try {
14846 app.thread.scheduleTrimMemory(
14847 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14848 } catch (RemoteException e) {
14849 }
14850 }
14851 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14852 app.pendingUiClean = false;
14853 } else {
14854 app.trimMemoryLevel = 0;
14855 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014856 }
14857 }
14858
14859 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014860 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014862 }
14863
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014864 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014865 synchronized (this) {
14866 int i;
14867
14868 // First remove any unused application processes whose package
14869 // has been removed.
14870 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14871 final ProcessRecord app = mRemovedProcesses.get(i);
14872 if (app.activities.size() == 0
14873 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014874 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014875 TAG, "Exiting empty application process "
14876 + app.processName + " ("
14877 + (app.thread != null ? app.thread.asBinder() : null)
14878 + ")\n");
14879 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014880 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14881 app.processName, app.setAdj, "empty");
14882 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014883 } else {
14884 try {
14885 app.thread.scheduleExit();
14886 } catch (Exception e) {
14887 // Ignore exceptions.
14888 }
14889 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014890 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014891 mRemovedProcesses.remove(i);
14892
14893 if (app.persistent) {
14894 if (app.persistent) {
14895 addAppLocked(app.info);
14896 }
14897 }
14898 }
14899 }
14900
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014901 // Now update the oom adj for all processes.
14902 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014903 }
14904 }
14905
14906 /** This method sends the specified signal to each of the persistent apps */
14907 public void signalPersistentProcesses(int sig) throws RemoteException {
14908 if (sig != Process.SIGNAL_USR1) {
14909 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14910 }
14911
14912 synchronized (this) {
14913 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14914 != PackageManager.PERMISSION_GRANTED) {
14915 throw new SecurityException("Requires permission "
14916 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14917 }
14918
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014919 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14920 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014921 if (r.thread != null && r.persistent) {
14922 Process.sendSignal(r.pid, sig);
14923 }
14924 }
14925 }
14926 }
14927
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014928 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14929 if (proc == null || proc == mProfileProc) {
14930 proc = mProfileProc;
14931 path = mProfileFile;
14932 profileType = mProfileType;
14933 clearProfilerLocked();
14934 }
14935 if (proc == null) {
14936 return;
14937 }
14938 try {
14939 proc.thread.profilerControl(false, path, null, profileType);
14940 } catch (RemoteException e) {
14941 throw new IllegalStateException("Process disappeared");
14942 }
14943 }
14944
14945 private void clearProfilerLocked() {
14946 if (mProfileFd != null) {
14947 try {
14948 mProfileFd.close();
14949 } catch (IOException e) {
14950 }
14951 }
14952 mProfileApp = null;
14953 mProfileProc = null;
14954 mProfileFile = null;
14955 mProfileType = 0;
14956 mAutoStopProfiler = false;
14957 }
14958
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014959 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014960 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014961
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014962 try {
14963 synchronized (this) {
14964 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14965 // its own permission.
14966 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14967 != PackageManager.PERMISSION_GRANTED) {
14968 throw new SecurityException("Requires permission "
14969 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014970 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014971
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014972 if (start && fd == null) {
14973 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014974 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014975
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014976 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014977 if (process != null) {
14978 try {
14979 int pid = Integer.parseInt(process);
14980 synchronized (mPidsSelfLocked) {
14981 proc = mPidsSelfLocked.get(pid);
14982 }
14983 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014984 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014985
14986 if (proc == null) {
14987 HashMap<String, SparseArray<ProcessRecord>> all
14988 = mProcessNames.getMap();
14989 SparseArray<ProcessRecord> procs = all.get(process);
14990 if (procs != null && procs.size() > 0) {
14991 proc = procs.valueAt(0);
14992 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014993 }
14994 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014995
14996 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014997 throw new IllegalArgumentException("Unknown process: " + process);
14998 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014999
15000 if (start) {
15001 stopProfilerLocked(null, null, 0);
15002 setProfileApp(proc.info, proc.processName, path, fd, false);
15003 mProfileProc = proc;
15004 mProfileType = profileType;
15005 try {
15006 fd = fd.dup();
15007 } catch (IOException e) {
15008 fd = null;
15009 }
15010 proc.thread.profilerControl(start, path, fd, profileType);
15011 fd = null;
15012 mProfileFd = null;
15013 } else {
15014 stopProfilerLocked(proc, path, profileType);
15015 if (fd != null) {
15016 try {
15017 fd.close();
15018 } catch (IOException e) {
15019 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015020 }
15021 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015022
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015023 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015024 }
15025 } catch (RemoteException e) {
15026 throw new IllegalStateException("Process disappeared");
15027 } finally {
15028 if (fd != null) {
15029 try {
15030 fd.close();
15031 } catch (IOException e) {
15032 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015033 }
15034 }
15035 }
Andy McFadden824c5102010-07-09 16:26:57 -070015036
15037 public boolean dumpHeap(String process, boolean managed,
15038 String path, ParcelFileDescriptor fd) throws RemoteException {
15039
15040 try {
15041 synchronized (this) {
15042 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
15043 // its own permission (same as profileControl).
15044 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15045 != PackageManager.PERMISSION_GRANTED) {
15046 throw new SecurityException("Requires permission "
15047 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
15048 }
15049
15050 if (fd == null) {
15051 throw new IllegalArgumentException("null fd");
15052 }
15053
15054 ProcessRecord proc = null;
15055 try {
15056 int pid = Integer.parseInt(process);
15057 synchronized (mPidsSelfLocked) {
15058 proc = mPidsSelfLocked.get(pid);
15059 }
15060 } catch (NumberFormatException e) {
15061 }
15062
15063 if (proc == null) {
15064 HashMap<String, SparseArray<ProcessRecord>> all
15065 = mProcessNames.getMap();
15066 SparseArray<ProcessRecord> procs = all.get(process);
15067 if (procs != null && procs.size() > 0) {
15068 proc = procs.valueAt(0);
15069 }
15070 }
15071
15072 if (proc == null || proc.thread == null) {
15073 throw new IllegalArgumentException("Unknown process: " + process);
15074 }
15075
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080015076 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
15077 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070015078 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
15079 throw new SecurityException("Process not debuggable: " + proc);
15080 }
15081 }
15082
15083 proc.thread.dumpHeap(managed, path, fd);
15084 fd = null;
15085 return true;
15086 }
15087 } catch (RemoteException e) {
15088 throw new IllegalStateException("Process disappeared");
15089 } finally {
15090 if (fd != null) {
15091 try {
15092 fd.close();
15093 } catch (IOException e) {
15094 }
15095 }
15096 }
15097 }
15098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015099 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
15100 public void monitor() {
15101 synchronized (this) { }
15102 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015103
15104 public void onCoreSettingsChange(Bundle settings) {
15105 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
15106 ProcessRecord processRecord = mLruProcesses.get(i);
15107 try {
15108 if (processRecord.thread != null) {
15109 processRecord.thread.setCoreSettings(settings);
15110 }
15111 } catch (RemoteException re) {
15112 /* ignore */
15113 }
15114 }
15115 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015116
15117 // Multi-user methods
15118
Amith Yamasani742a6712011-05-04 14:49:28 -070015119 private int mCurrentUserId;
15120 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
15121
15122 public boolean switchUser(int userId) {
15123 final int callingUid = Binder.getCallingUid();
15124 if (callingUid != 0 && callingUid != Process.myUid()) {
15125 Slog.e(TAG, "Trying to switch user from unauthorized app");
15126 return false;
15127 }
15128 if (mCurrentUserId == userId)
15129 return true;
15130
15131 synchronized (this) {
15132 // Check if user is already logged in, otherwise check if user exists first before
15133 // adding to the list of logged in users.
15134 if (mLoggedInUsers.indexOfKey(userId) < 0) {
15135 if (!userExists(userId)) {
15136 return false;
15137 }
15138 mLoggedInUsers.append(userId, userId);
15139 }
15140
15141 mCurrentUserId = userId;
15142 boolean haveActivities = mMainStack.switchUser(userId);
15143 if (!haveActivities) {
15144 startHomeActivityLocked(userId);
15145 }
15146 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015147 return true;
15148 }
Amith Yamasani742a6712011-05-04 14:49:28 -070015149
15150 private boolean userExists(int userId) {
15151 try {
15152 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
15153 for (UserInfo user : users) {
15154 if (user.id == userId) {
15155 return true;
15156 }
15157 }
15158 } catch (RemoteException re) {
15159 // Won't happen, in same process
15160 }
15161
15162 return false;
15163 }
15164
15165
15166 private int applyUserId(int uid, int userId) {
15167 return UserId.getUid(userId, uid);
15168 }
15169
15170 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080015171 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070015172 ApplicationInfo newInfo = new ApplicationInfo(info);
15173 newInfo.uid = applyUserId(info.uid, userId);
15174 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
15175 newInfo.dataDir = USER_DATA_DIR + userId + "/"
15176 + info.packageName;
15177 }
15178 return newInfo;
15179 }
15180
15181 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080015182 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070015183 || userId < 1) {
15184 return aInfo;
15185 }
15186
15187 ActivityInfo info = new ActivityInfo(aInfo);
15188 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
15189 return info;
15190 }
15191
15192 static class ServiceMap {
15193
15194 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
15195 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
15196 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
15197 mServicesByIntentPerUser = new SparseArray<
15198 HashMap<Intent.FilterComparison, ServiceRecord>>();
15199
15200 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
15201 // TODO: Deal with global services
15202 if (DEBUG_MU)
15203 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
15204 return getServices(callingUser).get(name);
15205 }
15206
15207 ServiceRecord getServiceByName(ComponentName name) {
15208 return getServiceByName(name, -1);
15209 }
15210
15211 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15212 // TODO: Deal with global services
15213 if (DEBUG_MU)
15214 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
15215 return getServicesByIntent(callingUser).get(filter);
15216 }
15217
15218 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
15219 return getServiceByIntent(filter, -1);
15220 }
15221
15222 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
15223 // TODO: Deal with global services
15224 getServices(callingUser).put(name, value);
15225 }
15226
15227 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
15228 ServiceRecord value) {
15229 // TODO: Deal with global services
15230 getServicesByIntent(callingUser).put(filter, value);
15231 }
15232
15233 void removeServiceByName(ComponentName name, int callingUser) {
15234 // TODO: Deal with global services
15235 ServiceRecord removed = getServices(callingUser).remove(name);
15236 if (DEBUG_MU)
15237 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15238 + " removed=" + removed);
15239 }
15240
15241 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15242 // TODO: Deal with global services
15243 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15244 if (DEBUG_MU)
15245 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15246 + " removed=" + removed);
15247 }
15248
15249 Collection<ServiceRecord> getAllServices(int callingUser) {
15250 // TODO: Deal with global services
15251 return getServices(callingUser).values();
15252 }
15253
15254 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15255 HashMap map = mServicesByNamePerUser.get(callingUser);
15256 if (map == null) {
15257 map = new HashMap<ComponentName, ServiceRecord>();
15258 mServicesByNamePerUser.put(callingUser, map);
15259 }
15260 return map;
15261 }
15262
15263 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15264 int callingUser) {
15265 HashMap map = mServicesByIntentPerUser.get(callingUser);
15266 if (map == null) {
15267 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15268 mServicesByIntentPerUser.put(callingUser, map);
15269 }
15270 return map;
15271 }
15272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015273}