blob: 57bfaed1be88b198524253d95cd623e639767e5b [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;
Dianne Hackborn860755f2010-06-03 18:47:52 -070078import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040079import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.content.res.Configuration;
81import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070082import android.net.Proxy;
83import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.net.Uri;
85import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080086import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080087import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070088import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080089import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080091import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.FileUtils;
93import android.os.Handler;
94import android.os.IBinder;
95import android.os.IPermissionController;
96import android.os.Looper;
97import android.os.Message;
98import android.os.Parcel;
99import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700101import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.os.RemoteException;
103import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700104import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.SystemClock;
106import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700109import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800110import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800111import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.util.PrintWriterPrinter;
113import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700114import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.view.Gravity;
116import android.view.LayoutInflater;
117import android.view.View;
118import android.view.WindowManager;
119import android.view.WindowManagerPolicy;
120
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700121import java.io.BufferedInputStream;
122import java.io.BufferedOutputStream;
123import java.io.DataInputStream;
124import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125import java.io.File;
126import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700127import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700129import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200130import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800131import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import java.io.PrintWriter;
133import java.lang.IllegalStateException;
134import java.lang.ref.WeakReference;
135import java.util.ArrayList;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700136import java.util.Collections;
137import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import java.util.HashMap;
139import java.util.HashSet;
140import java.util.Iterator;
141import java.util.List;
142import java.util.Locale;
143import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700144import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700145import java.util.concurrent.atomic.AtomicBoolean;
146import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700148public final class ActivityManagerService extends ActivityManagerNative
149 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 static final String TAG = "ActivityManager";
151 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400152 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 static final boolean DEBUG_SWITCH = localLOGV || false;
154 static final boolean DEBUG_TASKS = localLOGV || false;
155 static final boolean DEBUG_PAUSE = localLOGV || false;
156 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
157 static final boolean DEBUG_TRANSITION = localLOGV || false;
158 static final boolean DEBUG_BROADCAST = localLOGV || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700159 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700161 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final boolean DEBUG_VISBILITY = localLOGV || false;
163 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700164 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800165 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700167 static final boolean DEBUG_RESULTS = localLOGV || false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700168 static final boolean DEBUG_BACKUP = localLOGV || true;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700169 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700170 static final boolean DEBUG_POWER = localLOGV || false;
171 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 static final boolean VALIDATE_TOKENS = false;
173 static final boolean SHOW_ACTIVITY_START_TIME = true;
174
175 // Control over CPU and battery monitoring.
176 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
177 static final boolean MONITOR_CPU_USAGE = true;
178 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
179 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
180 static final boolean MONITOR_THREAD_CPU_USAGE = false;
181
Dianne Hackborn1655be42009-05-08 14:29:01 -0700182 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700183 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700184
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800185 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 // Maximum number of recent tasks that we can remember.
188 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700189
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700190 // Amount of time after a call to stopAppSwitches() during which we will
191 // prevent further untrusted switches from happening.
192 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
194 // How long we wait for a launched process to attach to the activity manager
195 // before we decide it's never going to come up for real.
196 static final int PROC_START_TIMEOUT = 10*1000;
197
Jeff Brown3f9dd282011-07-08 20:02:19 -0700198 // How long we wait for a launched process to attach to the activity manager
199 // before we decide it's never going to come up for real, when the process was
200 // started with a wrapper for instrumentation (such as Valgrind) because it
201 // could take much longer than usual.
202 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 // How long to wait after going idle before forcing apps to GC.
205 static final int GC_TIMEOUT = 5*1000;
206
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700207 // The minimum amount of time between successive GC requests for a process.
208 static final int GC_MIN_INTERVAL = 60*1000;
209
Dianne Hackborn287952c2010-09-22 22:34:31 -0700210 // The rate at which we check for apps using excessive power -- 15 mins.
211 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
212
213 // The minimum sample duration we will allow before deciding we have
214 // enough data on wake locks to start killing things.
215 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
216
217 // The minimum sample duration we will allow before deciding we have
218 // enough data on CPU usage to start killing things.
219 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 // How long we allow a receiver to run before giving up on it.
222 static final int BROADCAST_TIMEOUT = 10*1000;
223
224 // How long we wait for a service to finish executing.
225 static final int SERVICE_TIMEOUT = 20*1000;
226
227 // How long a service needs to be running until restarting its process
228 // is no longer considered to be a relaunch of the service.
229 static final int SERVICE_RESTART_DURATION = 5*1000;
230
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700231 // How long a service needs to be running until it will start back at
232 // SERVICE_RESTART_DURATION after being killed.
233 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
234
235 // Multiplying factor to increase restart duration time by, for each time
236 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
237 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
238
239 // The minimum amount of time between restarting services that we allow.
240 // That is, when multiple services are restarting, we won't allow each
241 // to restart less than this amount of time from the last one.
242 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // Maximum amount of time for there to be no activity on a service before
245 // we consider it non-essential and allow its process to go on the
246 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700247 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248
249 // How long we wait until we timeout on key dispatching.
250 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 // How long we wait until we timeout on key dispatching during instrumentation.
253 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
254
Dan Egnor42471dd2010-01-07 17:25:22 -0800255 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256
257 static final String[] EMPTY_STRING_ARRAY = new String[0];
258
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700259 public ActivityStack mMainStack;
260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700262 * Description of a request to start a new activity, which has been held
263 * due to app switches being disabled.
264 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700265 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700266 ActivityRecord r;
267 ActivityRecord sourceRecord;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700268 Uri[] grantedUriPermissions;
269 int grantedMode;
270 boolean onlyIfNeeded;
271 }
272
273 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
274 = new ArrayList<PendingActivityLaunch>();
275
276 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 * List of all active broadcasts that are to be executed immediately
278 * (without waiting for another broadcast to finish). Currently this only
279 * contains broadcasts to registered receivers, to avoid spinning up
280 * a bunch of processes to execute IntentReceiver components.
281 */
282 final ArrayList<BroadcastRecord> mParallelBroadcasts
283 = new ArrayList<BroadcastRecord>();
284
285 /**
286 * List of all active broadcasts that are to be executed one at a time.
287 * The object at the top of the list is the currently activity broadcasts;
288 * those after it are waiting for the top to finish..
289 */
290 final ArrayList<BroadcastRecord> mOrderedBroadcasts
291 = new ArrayList<BroadcastRecord>();
292
293 /**
Dianne Hackborn12527f92009-11-11 17:39:50 -0800294 * Historical data of past broadcasts, for debugging.
295 */
296 static final int MAX_BROADCAST_HISTORY = 100;
297 final BroadcastRecord[] mBroadcastHistory
298 = new BroadcastRecord[MAX_BROADCAST_HISTORY];
299
300 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 * Set when we current have a BROADCAST_INTENT_MSG in flight.
302 */
303 boolean mBroadcastsScheduled = false;
304
305 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 * Activity we have told the window manager to have key focus.
307 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700308 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700309 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 * List of intents that were used to start the most recent tasks.
311 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700312 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313
314 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700315 * Process management.
316 */
317 final ProcessList mProcessList = new ProcessList();
318
319 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 * All of the applications we currently have running organized by name.
321 * The keys are strings of the application package name (as
322 * returned by the package manager), and the keys are ApplicationRecord
323 * objects.
324 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700325 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326
327 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700328 * The currently running heavy-weight process, if any.
329 */
330 ProcessRecord mHeavyWeightProcess = null;
331
332 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 * The last time that various processes have crashed.
334 */
335 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
336
337 /**
338 * Set of applications that we consider to be bad, and will reject
339 * incoming broadcasts from (which the user has no control over).
340 * Processes are added to this set when they have crashed twice within
341 * a minimum amount of time; they are removed from it when they are
342 * later restarted (hopefully due to some user action). The value is the
343 * time it was added to the list.
344 */
345 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
346
347 /**
348 * All of the processes we currently have running organized by pid.
349 * The keys are the pid running the application.
350 *
351 * <p>NOTE: This object is protected by its own lock, NOT the global
352 * activity manager lock!
353 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700354 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355
356 /**
357 * All of the processes that have been forced to be foreground. The key
358 * is the pid of the caller who requested it (we hold a death
359 * link on it).
360 */
361 abstract class ForegroundToken implements IBinder.DeathRecipient {
362 int pid;
363 IBinder token;
364 }
365 final SparseArray<ForegroundToken> mForegroundProcesses
366 = new SparseArray<ForegroundToken>();
367
368 /**
369 * List of records for processes that someone had tried to start before the
370 * system was ready. We don't start them at that point, but ensure they
371 * are started by the time booting is complete.
372 */
373 final ArrayList<ProcessRecord> mProcessesOnHold
374 = new ArrayList<ProcessRecord>();
375
376 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 * List of persistent applications that are in the process
378 * of being started.
379 */
380 final ArrayList<ProcessRecord> mPersistentStartingProcesses
381 = new ArrayList<ProcessRecord>();
382
383 /**
384 * Processes that are being forcibly torn down.
385 */
386 final ArrayList<ProcessRecord> mRemovedProcesses
387 = new ArrayList<ProcessRecord>();
388
389 /**
390 * List of running applications, sorted by recent usage.
391 * The first entry in the list is the least recently used.
392 * It contains ApplicationRecord objects. This list does NOT include
393 * any persistent application records (since we never want to exit them).
394 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800395 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 = new ArrayList<ProcessRecord>();
397
398 /**
399 * List of processes that should gc as soon as things are idle.
400 */
401 final ArrayList<ProcessRecord> mProcessesToGc
402 = new ArrayList<ProcessRecord>();
403
404 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800405 * This is the process holding what we currently consider to be
406 * the "home" activity.
407 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700408 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800409
410 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400411 * Packages that the user has asked to have run in screen size
412 * compatibility mode instead of filling the screen.
413 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700414 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400415
416 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 * Set of PendingResultRecord objects that are currently active.
418 */
419 final HashSet mPendingResultRecords = new HashSet();
420
421 /**
422 * Set of IntentSenderRecord objects that are currently active.
423 */
424 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
425 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
426
427 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800428 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700429 * already logged DropBox entries for. Guarded by itself. If
430 * something (rogue user app) forces this over
431 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
432 */
433 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
434 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
435
436 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700437 * Strict Mode background batched logging state.
438 *
439 * The string buffer is guarded by itself, and its lock is also
440 * used to determine if another batched write is already
441 * in-flight.
442 */
443 private final StringBuilder mStrictModeBuffer = new StringBuilder();
444
445 /**
Jeff Brown4d94a762010-09-23 11:33:28 -0700446 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
447 */
448 private boolean mPendingBroadcastTimeoutMessage;
449
450 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 * Intent broadcast that we have tried to start, but are
452 * waiting for its application's process to be created. We only
453 * need one (instead of a list) because we always process broadcasts
454 * one at a time, so no others can be started while waiting for this
455 * one.
456 */
457 BroadcastRecord mPendingBroadcast = null;
458
459 /**
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700460 * The receiver index that is pending, to restart the broadcast if needed.
461 */
462 int mPendingBroadcastRecvIndex;
463
464 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 * Keeps track of all IIntentReceivers that have been registered for
466 * broadcasts. Hash keys are the receiver IBinder, hash value is
467 * a ReceiverList.
468 */
469 final HashMap mRegisteredReceivers = new HashMap();
470
471 /**
472 * Resolver for broadcast intents to registered receivers.
473 * Holds BroadcastFilter (subclass of IntentFilter).
474 */
475 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
476 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
477 @Override
478 protected boolean allowFilterResult(
479 BroadcastFilter filter, List<BroadcastFilter> dest) {
480 IBinder target = filter.receiverList.receiver.asBinder();
481 for (int i=dest.size()-1; i>=0; i--) {
482 if (dest.get(i).receiverList.receiver.asBinder() == target) {
483 return false;
484 }
485 }
486 return true;
487 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700488
489 @Override
490 protected String packageForFilter(BroadcastFilter filter) {
491 return filter.packageName;
492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 };
494
495 /**
496 * State of all active sticky broadcasts. Keys are the action of the
497 * sticky Intent, values are an ArrayList of all broadcasted intents with
498 * that action (which should usually be one).
499 */
500 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
501 new HashMap<String, ArrayList<Intent>>();
502
503 /**
504 * All currently running services.
505 */
506 final HashMap<ComponentName, ServiceRecord> mServices =
507 new HashMap<ComponentName, ServiceRecord>();
508
509 /**
510 * All currently running services indexed by the Intent used to start them.
511 */
512 final HashMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent =
513 new HashMap<Intent.FilterComparison, ServiceRecord>();
514
515 /**
516 * All currently bound service connections. Keys are the IBinder of
517 * the client's IServiceConnection.
518 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700519 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
520 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521
522 /**
523 * List of services that we have been asked to start,
524 * but haven't yet been able to. It is used to hold start requests
525 * while waiting for their corresponding application thread to get
526 * going.
527 */
528 final ArrayList<ServiceRecord> mPendingServices
529 = new ArrayList<ServiceRecord>();
530
531 /**
532 * List of services that are scheduled to restart following a crash.
533 */
534 final ArrayList<ServiceRecord> mRestartingServices
535 = new ArrayList<ServiceRecord>();
536
537 /**
538 * List of services that are in the process of being stopped.
539 */
540 final ArrayList<ServiceRecord> mStoppingServices
541 = new ArrayList<ServiceRecord>();
542
543 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700544 * Backup/restore process management
545 */
546 String mBackupAppName = null;
547 BackupRecord mBackupTarget = null;
548
549 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 * List of PendingThumbnailsRecord objects of clients who are still
551 * waiting to receive all of the thumbnails for a task.
552 */
553 final ArrayList mPendingThumbnails = new ArrayList();
554
555 /**
556 * List of HistoryRecord objects that have been finished and must
557 * still report back to a pending thumbnail receiver.
558 */
559 final ArrayList mCancelledThumbnails = new ArrayList();
560
561 /**
562 * All of the currently running global content providers. Keys are a
563 * string containing the provider name and values are a
564 * ContentProviderRecord object containing the data about it. Note
565 * that a single provider may be published under multiple names, so
566 * there may be multiple entries here for a single one in mProvidersByClass.
567 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700568 final HashMap<String, ContentProviderRecord> mProvidersByName
569 = new HashMap<String, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570
571 /**
572 * All of the currently running global content providers. Keys are a
573 * string containing the provider's implementation class and values are a
574 * ContentProviderRecord object containing the data about it.
575 */
Dianne Hackborn1c9b2602011-08-19 14:08:43 -0700576 final HashMap<ComponentName, ContentProviderRecord> mProvidersByClass
577 = new HashMap<ComponentName, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578
579 /**
580 * List of content providers who have clients waiting for them. The
581 * application is currently being launched and the provider will be
582 * removed from this list once it is published.
583 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700584 final ArrayList<ContentProviderRecord> mLaunchingProviders
585 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586
587 /**
588 * Global set of specific Uri permissions that have been granted.
589 */
590 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
591 = new SparseArray<HashMap<Uri, UriPermission>>();
592
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800593 CoreSettingsObserver mCoreSettingsObserver;
594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 /**
596 * Thread-local storage used to carry caller permissions over through
597 * indirect content-provider access.
598 * @see #ActivityManagerService.openContentUri()
599 */
600 private class Identity {
601 public int pid;
602 public int uid;
603
604 Identity(int _pid, int _uid) {
605 pid = _pid;
606 uid = _uid;
607 }
608 }
609 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
610
611 /**
612 * All information we have collected about the runtime performance of
613 * any user id that can impact battery performance.
614 */
615 final BatteryStatsService mBatteryStatsService;
616
617 /**
618 * information about component usage
619 */
620 final UsageStatsService mUsageStatsService;
621
622 /**
623 * Current configuration information. HistoryRecord objects are given
624 * a reference to this object to indicate which configuration they are
625 * currently running in, so this object must be kept immutable.
626 */
627 Configuration mConfiguration = new Configuration();
628
629 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800630 * Current sequencing integer of the configuration, for skipping old
631 * configurations.
632 */
633 int mConfigurationSeq = 0;
634
635 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700636 * Hardware-reported OpenGLES version.
637 */
638 final int GL_ES_VERSION;
639
640 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 * List of initialization arguments to pass to all processes when binding applications to them.
642 * For example, references to the commonly used services.
643 */
644 HashMap<String, IBinder> mAppBindArgs;
645
646 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700647 * Temporary to avoid allocations. Protected by main lock.
648 */
649 final StringBuilder mStringBuilder = new StringBuilder(256);
650
651 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 * Used to control how we initialize the service.
653 */
654 boolean mStartRunning = false;
655 ComponentName mTopComponent;
656 String mTopAction;
657 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700658 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 boolean mSystemReady = false;
660 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700661 boolean mWaitingUpdate = false;
662 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700663 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700664 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665
666 Context mContext;
667
668 int mFactoryTest;
669
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700670 boolean mCheckedForSetup;
671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700673 * The time at which we will allow normal application switches again,
674 * after a call to {@link #stopAppSwitches()}.
675 */
676 long mAppSwitchesAllowedTime;
677
678 /**
679 * This is set to true after the first switch after mAppSwitchesAllowedTime
680 * is set; any switches after that will clear the time.
681 */
682 boolean mDidAppSwitch;
683
684 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700685 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700686 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700687 long mLastPowerCheckRealtime;
688
689 /**
690 * Last time (in uptime) at which we checked for power usage.
691 */
692 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700693
694 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 * Set while we are wanting to sleep, to prevent any
696 * activities from being started/resumed.
697 */
698 boolean mSleeping = false;
699
700 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700701 * Set if we are shutting down the system, similar to sleeping.
702 */
703 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704
705 /**
706 * Task identifier that activities are currently being started
707 * in. Incremented each time a new task is created.
708 * todo: Replace this with a TokenSpace class that generates non-repeating
709 * integers that won't wrap.
710 */
711 int mCurTask = 1;
712
713 /**
714 * Current sequence id for oom_adj computation traversal.
715 */
716 int mAdjSeq = 0;
717
718 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700719 * Current sequence id for process LRU updating.
720 */
721 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722
723 /**
724 * System monitoring: number of processes that died since the last
725 * N procs were started.
726 */
727 int[] mProcDeaths = new int[20];
728
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700729 /**
730 * This is set if we had to do a delayed dexopt of an app before launching
731 * it, to increasing the ANR timeouts in that case.
732 */
733 boolean mDidDexOpt;
734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 String mDebugApp = null;
736 boolean mWaitForDebugger = false;
737 boolean mDebugTransient = false;
738 String mOrigDebugApp = null;
739 boolean mOrigWaitForDebugger = false;
740 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700741 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700742 String mProfileApp = null;
743 ProcessRecord mProfileProc = null;
744 String mProfileFile;
745 ParcelFileDescriptor mProfileFd;
746 int mProfileType = 0;
747 boolean mAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700749 final RemoteCallbackList<IActivityWatcher> mWatchers
750 = new RemoteCallbackList<IActivityWatcher>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700751
752 final RemoteCallbackList<IProcessObserver> mProcessObservers
753 = new RemoteCallbackList<IProcessObserver>();
754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 /**
756 * Callback of last caller to {@link #requestPss}.
757 */
758 Runnable mRequestPssCallback;
759
760 /**
761 * Remaining processes for which we are waiting results from the last
762 * call to {@link #requestPss}.
763 */
764 final ArrayList<ProcessRecord> mRequestPssList
765 = new ArrayList<ProcessRecord>();
766
767 /**
768 * Runtime statistics collection thread. This object's lock is used to
769 * protect all related state.
770 */
771 final Thread mProcessStatsThread;
772
773 /**
774 * Used to collect process stats when showing not responding dialog.
775 * Protected by mProcessStatsThread.
776 */
777 final ProcessStats mProcessStats = new ProcessStats(
778 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700779 final AtomicLong mLastCpuTime = new AtomicLong(0);
780 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 long mLastWriteTime = 0;
783
784 /**
785 * Set to true after the system has finished booting.
786 */
787 boolean mBooted = false;
788
Dianne Hackborn7d608422011-08-07 16:24:18 -0700789 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700790 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791
792 WindowManagerService mWindowManager;
793
794 static ActivityManagerService mSelf;
795 static ActivityThread mSystemThread;
796
797 private final class AppDeathRecipient implements IBinder.DeathRecipient {
798 final ProcessRecord mApp;
799 final int mPid;
800 final IApplicationThread mAppThread;
801
802 AppDeathRecipient(ProcessRecord app, int pid,
803 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800804 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 TAG, "New death recipient " + this
806 + " for thread " + thread.asBinder());
807 mApp = app;
808 mPid = pid;
809 mAppThread = thread;
810 }
811
812 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800813 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 TAG, "Death received in " + this
815 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 synchronized(ActivityManagerService.this) {
817 appDiedLocked(mApp, mPid, mAppThread);
818 }
819 }
820 }
821
822 static final int SHOW_ERROR_MSG = 1;
823 static final int SHOW_NOT_RESPONDING_MSG = 2;
824 static final int SHOW_FACTORY_ERROR_MSG = 3;
825 static final int UPDATE_CONFIGURATION_MSG = 4;
826 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
827 static final int WAIT_FOR_DEBUGGER_MSG = 6;
828 static final int BROADCAST_INTENT_MSG = 7;
829 static final int BROADCAST_TIMEOUT_MSG = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 static final int SERVICE_TIMEOUT_MSG = 12;
831 static final int UPDATE_TIME_ZONE = 13;
832 static final int SHOW_UID_ERROR_MSG = 14;
833 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700835 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700836 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800837 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700838 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
839 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700840 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700841 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700842 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700843 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700844 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700845 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
846 static final int DISPATCH_PROCESS_DIED = 32;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847
848 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700849 CompatModeDialog mCompatModeDialog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850
851 final Handler mHandler = new Handler() {
852 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800853 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 //}
855
856 public void handleMessage(Message msg) {
857 switch (msg.what) {
858 case SHOW_ERROR_MSG: {
859 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 synchronized (ActivityManagerService.this) {
861 ProcessRecord proc = (ProcessRecord)data.get("app");
862 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800863 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 return;
865 }
866 AppErrorResult res = (AppErrorResult) data.get("result");
Dianne Hackborn55280a92009-05-07 15:53:46 -0700867 if (!mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800868 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 d.show();
870 proc.crashDialog = d;
871 } else {
872 // The device is asleep, so just pretend that the user
873 // saw a crash dialog and hit "force quit".
874 res.set(0);
875 }
876 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700877
878 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 } break;
880 case SHOW_NOT_RESPONDING_MSG: {
881 synchronized (ActivityManagerService.this) {
882 HashMap data = (HashMap) msg.obj;
883 ProcessRecord proc = (ProcessRecord)data.get("app");
884 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800885 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 return;
887 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800888
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700889 Intent intent = new Intent("android.intent.action.ANR");
890 if (!mProcessesReady) {
891 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
892 }
893 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800894 null, null, 0, null, null, null,
895 false, false, MY_PID, Process.SYSTEM_UID);
896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700898 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 d.show();
900 proc.anrDialog = d;
901 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700902
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700903 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700905 case SHOW_STRICT_MODE_VIOLATION_MSG: {
906 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
907 synchronized (ActivityManagerService.this) {
908 ProcessRecord proc = (ProcessRecord) data.get("app");
909 if (proc == null) {
910 Slog.e(TAG, "App not found when showing strict mode dialog.");
911 break;
912 }
913 if (proc.crashDialog != null) {
914 Slog.e(TAG, "App already has strict mode dialog: " + proc);
915 return;
916 }
917 AppErrorResult res = (AppErrorResult) data.get("result");
918 if (!mSleeping && !mShuttingDown) {
919 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
920 d.show();
921 proc.crashDialog = d;
922 } else {
923 // The device is asleep, so just pretend that the user
924 // saw a crash dialog and hit "force quit".
925 res.set(0);
926 }
927 }
928 ensureBootCompleted();
929 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 case SHOW_FACTORY_ERROR_MSG: {
931 Dialog d = new FactoryErrorDialog(
932 mContext, msg.getData().getCharSequence("msg"));
933 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700934 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 } break;
936 case UPDATE_CONFIGURATION_MSG: {
937 final ContentResolver resolver = mContext.getContentResolver();
938 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
939 } break;
940 case GC_BACKGROUND_PROCESSES_MSG: {
941 synchronized (ActivityManagerService.this) {
942 performAppGcsIfAppropriateLocked();
943 }
944 } break;
945 case WAIT_FOR_DEBUGGER_MSG: {
946 synchronized (ActivityManagerService.this) {
947 ProcessRecord app = (ProcessRecord)msg.obj;
948 if (msg.arg1 != 0) {
949 if (!app.waitedForDebugger) {
950 Dialog d = new AppWaitingForDebuggerDialog(
951 ActivityManagerService.this,
952 mContext, app);
953 app.waitDialog = d;
954 app.waitedForDebugger = true;
955 d.show();
956 }
957 } else {
958 if (app.waitDialog != null) {
959 app.waitDialog.dismiss();
960 app.waitDialog = null;
961 }
962 }
963 }
964 } break;
965 case BROADCAST_INTENT_MSG: {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800966 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 TAG, "Received BROADCAST_INTENT_MSG");
968 processNextBroadcast(true);
969 } break;
970 case BROADCAST_TIMEOUT_MSG: {
Jeff Brown4d94a762010-09-23 11:33:28 -0700971 synchronized (ActivityManagerService.this) {
972 broadcastTimeoutLocked(true);
Jeff Hamiltonacf84742010-05-25 22:10:18 -0500973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700976 if (mDidDexOpt) {
977 mDidDexOpt = false;
978 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
979 nmsg.obj = msg.obj;
980 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
981 return;
982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 serviceTimeout((ProcessRecord)msg.obj);
984 } break;
985 case UPDATE_TIME_ZONE: {
986 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800987 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
988 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 if (r.thread != null) {
990 try {
991 r.thread.updateTimeZone();
992 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800993 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 }
995 }
996 }
997 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700998 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700999 case CLEAR_DNS_CACHE: {
1000 synchronized (ActivityManagerService.this) {
1001 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1002 ProcessRecord r = mLruProcesses.get(i);
1003 if (r.thread != null) {
1004 try {
1005 r.thread.clearDnsCache();
1006 } catch (RemoteException ex) {
1007 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1008 }
1009 }
1010 }
1011 }
1012 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001013 case UPDATE_HTTP_PROXY: {
1014 ProxyProperties proxy = (ProxyProperties)msg.obj;
1015 String host = "";
1016 String port = "";
1017 String exclList = "";
1018 if (proxy != null) {
1019 host = proxy.getHost();
1020 port = Integer.toString(proxy.getPort());
1021 exclList = proxy.getExclusionList();
1022 }
1023 synchronized (ActivityManagerService.this) {
1024 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1025 ProcessRecord r = mLruProcesses.get(i);
1026 if (r.thread != null) {
1027 try {
1028 r.thread.setHttpProxy(host, port, exclList);
1029 } catch (RemoteException ex) {
1030 Slog.w(TAG, "Failed to update http proxy for: " +
1031 r.info.processName);
1032 }
1033 }
1034 }
1035 }
1036 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 case SHOW_UID_ERROR_MSG: {
1038 // XXX This is a temporary dialog, no need to localize.
1039 AlertDialog d = new BaseErrorDialog(mContext);
1040 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1041 d.setCancelable(false);
1042 d.setTitle("System UIDs Inconsistent");
1043 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 +02001044 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1046 mUidAlert = d;
1047 d.show();
1048 } break;
1049 case IM_FEELING_LUCKY_MSG: {
1050 if (mUidAlert != null) {
1051 mUidAlert.dismiss();
1052 mUidAlert = null;
1053 }
1054 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001056 if (mDidDexOpt) {
1057 mDidDexOpt = false;
1058 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1059 nmsg.obj = msg.obj;
1060 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1061 return;
1062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 ProcessRecord app = (ProcessRecord)msg.obj;
1064 synchronized (ActivityManagerService.this) {
1065 processStartTimedOutLocked(app);
1066 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001067 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001068 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1069 synchronized (ActivityManagerService.this) {
1070 doPendingActivityLaunchesLocked(true);
1071 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001072 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001073 case KILL_APPLICATION_MSG: {
1074 synchronized (ActivityManagerService.this) {
1075 int uid = msg.arg1;
1076 boolean restart = (msg.arg2 == 1);
1077 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001078 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001079 }
1080 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001081 case FINALIZE_PENDING_INTENT_MSG: {
1082 ((PendingIntentRecord)msg.obj).completeFinalize();
1083 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001084 case POST_HEAVY_NOTIFICATION_MSG: {
1085 INotificationManager inm = NotificationManager.getService();
1086 if (inm == null) {
1087 return;
1088 }
1089
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001090 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001091 ProcessRecord process = root.app;
1092 if (process == null) {
1093 return;
1094 }
1095
1096 try {
1097 Context context = mContext.createPackageContext(process.info.packageName, 0);
1098 String text = mContext.getString(R.string.heavy_weight_notification,
1099 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1100 Notification notification = new Notification();
1101 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1102 notification.when = 0;
1103 notification.flags = Notification.FLAG_ONGOING_EVENT;
1104 notification.tickerText = text;
1105 notification.defaults = 0; // please be quiet
1106 notification.sound = null;
1107 notification.vibrate = null;
1108 notification.setLatestEventInfo(context, text,
1109 mContext.getText(R.string.heavy_weight_notification_detail),
1110 PendingIntent.getActivity(mContext, 0, root.intent,
1111 PendingIntent.FLAG_CANCEL_CURRENT));
1112
1113 try {
1114 int[] outId = new int[1];
1115 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1116 notification, outId);
1117 } catch (RuntimeException e) {
1118 Slog.w(ActivityManagerService.TAG,
1119 "Error showing notification for heavy-weight app", e);
1120 } catch (RemoteException e) {
1121 }
1122 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001123 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001124 }
1125 } break;
1126 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1127 INotificationManager inm = NotificationManager.getService();
1128 if (inm == null) {
1129 return;
1130 }
1131 try {
1132 inm.cancelNotification("android",
1133 R.string.heavy_weight_notification);
1134 } catch (RuntimeException e) {
1135 Slog.w(ActivityManagerService.TAG,
1136 "Error canceling notification for service", e);
1137 } catch (RemoteException e) {
1138 }
1139 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001140 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1141 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001142 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001143 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001144 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1145 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001146 }
1147 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001148 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1149 synchronized (ActivityManagerService.this) {
1150 ActivityRecord ar = (ActivityRecord)msg.obj;
1151 if (mCompatModeDialog != null) {
1152 if (mCompatModeDialog.mAppInfo.packageName.equals(
1153 ar.info.applicationInfo.packageName)) {
1154 return;
1155 }
1156 mCompatModeDialog.dismiss();
1157 mCompatModeDialog = null;
1158 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001159 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001160 if (mCompatModePackages.getPackageAskCompatModeLocked(
1161 ar.packageName)) {
1162 int mode = mCompatModePackages.computeCompatModeLocked(
1163 ar.info.applicationInfo);
1164 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1165 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1166 mCompatModeDialog = new CompatModeDialog(
1167 ActivityManagerService.this, mContext,
1168 ar.info.applicationInfo);
1169 mCompatModeDialog.show();
1170 }
1171 }
1172 }
1173 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001174 break;
1175 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001176 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001177 final int pid = msg.arg1;
1178 final int uid = msg.arg2;
1179 final boolean foregroundActivities = (Boolean) msg.obj;
1180 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001181 break;
1182 }
1183 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001184 final int pid = msg.arg1;
1185 final int uid = msg.arg2;
1186 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001187 break;
1188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 }
1190 }
1191 };
1192
1193 public static void setSystemProcess() {
1194 try {
1195 ActivityManagerService m = mSelf;
1196
1197 ServiceManager.addService("activity", m);
1198 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001199 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 if (MONITOR_CPU_USAGE) {
1201 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 ServiceManager.addService("permission", new PermissionController(m));
1204
1205 ApplicationInfo info =
1206 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001207 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001208 mSystemThread.installSystemApplicationInfo(info);
1209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 synchronized (mSelf) {
1211 ProcessRecord app = mSelf.newProcessRecordLocked(
1212 mSystemThread.getApplicationThread(), info,
1213 info.processName);
1214 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001215 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001216 app.maxAdj = ProcessList.SYSTEM_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 mSelf.mProcessNames.put(app.processName, app.info.uid, app);
1218 synchronized (mSelf.mPidsSelfLocked) {
1219 mSelf.mPidsSelfLocked.put(app.pid, app);
1220 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001221 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 }
1223 } catch (PackageManager.NameNotFoundException e) {
1224 throw new RuntimeException(
1225 "Unable to find android system package", e);
1226 }
1227 }
1228
1229 public void setWindowManager(WindowManagerService wm) {
1230 mWindowManager = wm;
1231 }
1232
1233 public static final Context main(int factoryTest) {
1234 AThread thr = new AThread();
1235 thr.start();
1236
1237 synchronized (thr) {
1238 while (thr.mService == null) {
1239 try {
1240 thr.wait();
1241 } catch (InterruptedException e) {
1242 }
1243 }
1244 }
1245
1246 ActivityManagerService m = thr.mService;
1247 mSelf = m;
1248 ActivityThread at = ActivityThread.systemMain();
1249 mSystemThread = at;
1250 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001251 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 m.mContext = context;
1253 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001254 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255
1256 m.mBatteryStatsService.publish(context);
1257 m.mUsageStatsService.publish(context);
1258
1259 synchronized (thr) {
1260 thr.mReady = true;
1261 thr.notifyAll();
1262 }
1263
1264 m.startRunning(null, null, null, null);
1265
1266 return context;
1267 }
1268
1269 public static ActivityManagerService self() {
1270 return mSelf;
1271 }
1272
1273 static class AThread extends Thread {
1274 ActivityManagerService mService;
1275 boolean mReady = false;
1276
1277 public AThread() {
1278 super("ActivityManager");
1279 }
1280
1281 public void run() {
1282 Looper.prepare();
1283
1284 android.os.Process.setThreadPriority(
1285 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001286 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287
1288 ActivityManagerService m = new ActivityManagerService();
1289
1290 synchronized (this) {
1291 mService = m;
1292 notifyAll();
1293 }
1294
1295 synchronized (this) {
1296 while (!mReady) {
1297 try {
1298 wait();
1299 } catch (InterruptedException e) {
1300 }
1301 }
1302 }
1303
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001304 // For debug builds, log event loop stalls to dropbox for analysis.
1305 if (StrictMode.conditionallyEnableDebugLogging()) {
1306 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1307 }
1308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 Looper.loop();
1310 }
1311 }
1312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 static class MemBinder extends Binder {
1314 ActivityManagerService mActivityManagerService;
1315 MemBinder(ActivityManagerService activityManagerService) {
1316 mActivityManagerService = activityManagerService;
1317 }
1318
1319 @Override
1320 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001321 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 }
1323 }
1324
Chet Haase9c1e23b2011-03-24 10:51:31 -07001325 static class GraphicsBinder extends Binder {
1326 ActivityManagerService mActivityManagerService;
1327 GraphicsBinder(ActivityManagerService activityManagerService) {
1328 mActivityManagerService = activityManagerService;
1329 }
1330
1331 @Override
1332 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001333 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001334 }
1335 }
1336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 static class CpuBinder extends Binder {
1338 ActivityManagerService mActivityManagerService;
1339 CpuBinder(ActivityManagerService activityManagerService) {
1340 mActivityManagerService = activityManagerService;
1341 }
1342
1343 @Override
1344 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1345 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001346 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1347 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1348 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 }
1350 }
1351 }
1352
1353 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001354 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 File dataDir = Environment.getDataDirectory();
1357 File systemDir = new File(dataDir, "system");
1358 systemDir.mkdirs();
1359 mBatteryStatsService = new BatteryStatsService(new File(
1360 systemDir, "batterystats.bin").toString());
1361 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001362 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001363 mOnBattery = DEBUG_POWER ? true
1364 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001365 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001367 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001368 systemDir, "usagestats").toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369
Jack Palevichb90d28c2009-07-22 15:35:24 -07001370 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1371 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1372
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001373 mConfiguration.setToDefaults();
1374 mConfiguration.locale = Locale.getDefault();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 mProcessStats.init();
1376
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001377 mCompatModePackages = new CompatModePackages(this, systemDir);
1378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 // Add ourself to the Watchdog monitors.
1380 Watchdog.getInstance().addMonitor(this);
1381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 mProcessStatsThread = new Thread("ProcessStats") {
1383 public void run() {
1384 while (true) {
1385 try {
1386 try {
1387 synchronized(this) {
1388 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001389 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001391 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 // + ", write delay=" + nextWriteDelay);
1393 if (nextWriteDelay < nextCpuDelay) {
1394 nextCpuDelay = nextWriteDelay;
1395 }
1396 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001397 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 this.wait(nextCpuDelay);
1399 }
1400 }
1401 } catch (InterruptedException e) {
1402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 updateCpuStatsNow();
1404 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001405 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 }
1407 }
1408 }
1409 };
1410 mProcessStatsThread.start();
1411 }
1412
1413 @Override
1414 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1415 throws RemoteException {
1416 try {
1417 return super.onTransact(code, data, reply, flags);
1418 } catch (RuntimeException e) {
1419 // The activity manager only throws security exceptions, so let's
1420 // log all others.
1421 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001422 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
1424 throw e;
1425 }
1426 }
1427
1428 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001429 final long now = SystemClock.uptimeMillis();
1430 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1431 return;
1432 }
1433 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1434 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 mProcessStatsThread.notify();
1436 }
1437 }
1438 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 void updateCpuStatsNow() {
1441 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001442 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 final long now = SystemClock.uptimeMillis();
1444 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001447 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1448 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 haveNewCpuStats = true;
1450 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001451 //Slog.i(TAG, mProcessStats.printCurrentState());
1452 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 // + mProcessStats.getTotalCpuPercent() + "%");
1454
Joe Onorato8a9b2202010-02-26 18:56:32 -08001455 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 if ("true".equals(SystemProperties.get("events.cpu"))) {
1457 int user = mProcessStats.getLastUserTime();
1458 int system = mProcessStats.getLastSystemTime();
1459 int iowait = mProcessStats.getLastIoWaitTime();
1460 int irq = mProcessStats.getLastIrqTime();
1461 int softIrq = mProcessStats.getLastSoftIrqTime();
1462 int idle = mProcessStats.getLastIdleTime();
1463
1464 int total = user + system + iowait + irq + softIrq + idle;
1465 if (total == 0) total = 1;
1466
Doug Zongker2bec3d42009-12-04 12:52:44 -08001467 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 ((user+system+iowait+irq+softIrq) * 100) / total,
1469 (user * 100) / total,
1470 (system * 100) / total,
1471 (iowait * 100) / total,
1472 (irq * 100) / total,
1473 (softIrq * 100) / total);
1474 }
1475 }
1476
Amith Yamasanie43530a2009-08-21 13:11:37 -07001477 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001478 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001479 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 synchronized(mPidsSelfLocked) {
1481 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001482 if (mOnBattery) {
1483 int perc = bstats.startAddingCpuLocked();
1484 int totalUTime = 0;
1485 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001486 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001488 ProcessStats.Stats st = mProcessStats.getStats(i);
1489 if (!st.working) {
1490 continue;
1491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001493 int otherUTime = (st.rel_utime*perc)/100;
1494 int otherSTime = (st.rel_stime*perc)/100;
1495 totalUTime += otherUTime;
1496 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 if (pr != null) {
1498 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001499 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1500 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001501 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001502 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001503 } else {
1504 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001505 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001506 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001507 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1508 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001509 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001513 bstats.finishAddingCpuLocked(perc, totalUTime,
1514 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516 }
1517 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1520 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001521 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 }
1523 }
1524 }
1525 }
1526
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001527 @Override
1528 public void batteryNeedsCpuUpdate() {
1529 updateCpuStatsNow();
1530 }
1531
1532 @Override
1533 public void batteryPowerChanged(boolean onBattery) {
1534 // When plugging in, update the CPU stats first before changing
1535 // the plug state.
1536 updateCpuStatsNow();
1537 synchronized (this) {
1538 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001539 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001540 }
1541 }
1542 }
1543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 /**
1545 * Initialize the application bind args. These are passed to each
1546 * process when the bindApplication() IPC is sent to the process. They're
1547 * lazily setup to make sure the services are running when they're asked for.
1548 */
1549 private HashMap<String, IBinder> getCommonServicesLocked() {
1550 if (mAppBindArgs == null) {
1551 mAppBindArgs = new HashMap<String, IBinder>();
1552
1553 // Setup the application init args
1554 mAppBindArgs.put("package", ServiceManager.getService("package"));
1555 mAppBindArgs.put("window", ServiceManager.getService("window"));
1556 mAppBindArgs.put(Context.ALARM_SERVICE,
1557 ServiceManager.getService(Context.ALARM_SERVICE));
1558 }
1559 return mAppBindArgs;
1560 }
1561
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001562 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 if (mFocusedActivity != r) {
1564 mFocusedActivity = r;
1565 mWindowManager.setFocusedApp(r, true);
1566 }
1567 }
1568
Dianne Hackborn906497c2010-05-10 15:57:38 -07001569 private final void updateLruProcessInternalLocked(ProcessRecord app,
1570 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001572 int lrui = mLruProcesses.indexOf(app);
1573 if (lrui >= 0) mLruProcesses.remove(lrui);
1574
1575 int i = mLruProcesses.size()-1;
1576 int skipTop = 0;
1577
Dianne Hackborn906497c2010-05-10 15:57:38 -07001578 app.lruSeq = mLruSeq;
1579
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001580 // compute the new weight for this process.
1581 if (updateActivityTime) {
1582 app.lastActivityTime = SystemClock.uptimeMillis();
1583 }
1584 if (app.activities.size() > 0) {
1585 // If this process has activities, we more strongly want to keep
1586 // it around.
1587 app.lruWeight = app.lastActivityTime;
1588 } else if (app.pubProviders.size() > 0) {
1589 // If this process contains content providers, we want to keep
1590 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001591 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001592 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001593 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001594 } else {
1595 // If this process doesn't have activities, we less strongly
1596 // want to keep it around, and generally want to avoid getting
1597 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001598 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001599 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001600 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001601 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001602
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001603 while (i >= 0) {
1604 ProcessRecord p = mLruProcesses.get(i);
1605 // If this app shouldn't be in front of the first N background
1606 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001607 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001608 skipTop--;
1609 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001610 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001611 mLruProcesses.add(i+1, app);
1612 break;
1613 }
1614 i--;
1615 }
1616 if (i < 0) {
1617 mLruProcesses.add(0, app);
1618 }
1619
Dianne Hackborn906497c2010-05-10 15:57:38 -07001620 // If the app is currently using a content provider or service,
1621 // bump those processes as well.
1622 if (app.connections.size() > 0) {
1623 for (ConnectionRecord cr : app.connections) {
1624 if (cr.binding != null && cr.binding.service != null
1625 && cr.binding.service.app != null
1626 && cr.binding.service.app.lruSeq != mLruSeq) {
1627 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1628 updateActivityTime, i+1);
1629 }
1630 }
1631 }
1632 if (app.conProviders.size() > 0) {
1633 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
1634 if (cpr.app != null && cpr.app.lruSeq != mLruSeq) {
1635 updateLruProcessInternalLocked(cpr.app, oomAdj,
1636 updateActivityTime, i+1);
1637 }
1638 }
1639 }
1640
Joe Onorato8a9b2202010-02-26 18:56:32 -08001641 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 if (oomAdj) {
1643 updateOomAdjLocked();
1644 }
1645 }
1646
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001647 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001648 boolean oomAdj, boolean updateActivityTime) {
1649 mLruSeq++;
1650 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1651 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001652
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001653 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 String processName, int uid) {
1655 if (uid == Process.SYSTEM_UID) {
1656 // The system gets to run in any process. If there are multiple
1657 // processes with the same uid, just pick the first (this
1658 // should never happen).
1659 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1660 processName);
1661 return procs != null ? procs.valueAt(0) : null;
1662 }
1663 ProcessRecord proc = mProcessNames.get(processName, uid);
1664 return proc;
1665 }
1666
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001667 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001668 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001669 try {
1670 if (pm.performDexOpt(packageName)) {
1671 mDidDexOpt = true;
1672 }
1673 } catch (RemoteException e) {
1674 }
1675 }
1676
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001677 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 int transit = mWindowManager.getPendingAppTransition();
1679 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1680 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1681 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1682 }
1683
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001684 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001686 String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 ProcessRecord app = getProcessRecordLocked(processName, info.uid);
1688 // We don't have to do anything more if:
1689 // (1) There is an existing application record; and
1690 // (2) The caller doesn't think it is dead, OR there is no thread
1691 // object attached to it so we know it couldn't have crashed; and
1692 // (3) There is a pid assigned to it, so it is either starting or
1693 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001694 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 + " app=" + app + " knownToBeDead=" + knownToBeDead
1696 + " thread=" + (app != null ? app.thread : null)
1697 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001698 if (app != null && app.pid > 0) {
1699 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001700 // We already have the app running, or are waiting for it to
1701 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001702 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001703 // If this is a new package in the process, add the package to the list
1704 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001705 return app;
1706 } else {
1707 // An application record is attached to a previous process,
1708 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001709 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001710 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 String hostingNameStr = hostingName != null
1715 ? hostingName.flattenToShortString() : null;
1716
1717 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1718 // If we are in the background, then check to see if this process
1719 // is bad. If so, we will just silently fail.
1720 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001721 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1722 + "/" + info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 return null;
1724 }
1725 } else {
1726 // When the user is explicitly starting a process, then clear its
1727 // crash count so that we won't make it bad until they see at
1728 // least one crash dialog again, and make the process good again
1729 // if it had been bad.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001730 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
1731 + "/" + info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 mProcessCrashTimes.remove(info.processName, info.uid);
1733 if (mBadProcesses.get(info.processName, info.uid) != null) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08001734 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 info.processName);
1736 mBadProcesses.remove(info.processName, info.uid);
1737 if (app != null) {
1738 app.bad = false;
1739 }
1740 }
1741 }
1742
1743 if (app == null) {
1744 app = newProcessRecordLocked(null, info, processName);
1745 mProcessNames.put(processName, info.uid, app);
1746 } else {
1747 // If this is a new package in the process, add the package to the list
1748 app.addPackage(info.packageName);
1749 }
1750
1751 // If the system is not ready yet, then hold off on starting this
1752 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001753 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001754 && !isAllowedWhileBooting(info)
1755 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 if (!mProcessesOnHold.contains(app)) {
1757 mProcessesOnHold.add(app);
1758 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001759 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 return app;
1761 }
1762
1763 startProcessLocked(app, hostingType, hostingNameStr);
1764 return (app.pid != 0) ? app : null;
1765 }
1766
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001767 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1768 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1769 }
1770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 private final void startProcessLocked(ProcessRecord app,
1772 String hostingType, String hostingNameStr) {
1773 if (app.pid > 0 && app.pid != MY_PID) {
1774 synchronized (mPidsSelfLocked) {
1775 mPidsSelfLocked.remove(app.pid);
1776 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1777 }
1778 app.pid = 0;
1779 }
1780
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001781 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1782 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 mProcessesOnHold.remove(app);
1784
1785 updateCpuStats();
1786
1787 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1788 mProcDeaths[0] = 0;
1789
1790 try {
1791 int uid = app.info.uid;
1792 int[] gids = null;
1793 try {
1794 gids = mContext.getPackageManager().getPackageGids(
1795 app.info.packageName);
1796 } catch (PackageManager.NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001797 Slog.w(TAG, "Unable to retrieve gids", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 }
1799 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1800 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1801 && mTopComponent != null
1802 && app.processName.equals(mTopComponent.getPackageName())) {
1803 uid = 0;
1804 }
1805 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1806 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1807 uid = 0;
1808 }
1809 }
1810 int debugFlags = 0;
1811 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1812 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001813 // Also turn on CheckJNI for debuggable apps. It's quite
1814 // awkward to turn on otherwise.
1815 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001817 // Run the app in safe mode if its manifest requests so or the
1818 // system is booted in safe mode.
1819 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1820 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001821 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1824 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1825 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001826 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1827 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 if ("1".equals(SystemProperties.get("debug.assert"))) {
1830 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1831 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001832
1833 // Start the process. It will either succeed and return a result containing
1834 // the PID of the new process, or else throw a RuntimeException.
1835 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001836 app.processName, uid, uid, gids, debugFlags,
1837 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07001838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1840 synchronized (bs) {
1841 if (bs.isOnBattery()) {
1842 app.batteryStats.incStartsLocked();
1843 }
1844 }
1845
Jeff Brown3f9dd282011-07-08 20:02:19 -07001846 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 app.processName, hostingType,
1848 hostingNameStr != null ? hostingNameStr : "");
1849
1850 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07001851 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
1853
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07001854 StringBuilder buf = mStringBuilder;
1855 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 buf.append("Start proc ");
1857 buf.append(app.processName);
1858 buf.append(" for ");
1859 buf.append(hostingType);
1860 if (hostingNameStr != null) {
1861 buf.append(" ");
1862 buf.append(hostingNameStr);
1863 }
1864 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07001865 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 buf.append(" uid=");
1867 buf.append(uid);
1868 buf.append(" gids={");
1869 if (gids != null) {
1870 for (int gi=0; gi<gids.length; gi++) {
1871 if (gi != 0) buf.append(", ");
1872 buf.append(gids[gi]);
1873
1874 }
1875 }
1876 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001877 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07001878 app.pid = startResult.pid;
1879 app.usingWrapper = startResult.usingWrapper;
1880 app.removed = false;
1881 synchronized (mPidsSelfLocked) {
1882 this.mPidsSelfLocked.put(startResult.pid, app);
1883 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1884 msg.obj = app;
1885 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
1886 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 }
1888 } catch (RuntimeException e) {
1889 // XXX do better error recovery.
1890 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001891 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893 }
1894
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001895 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 if (resumed) {
1897 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
1898 } else {
1899 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
1900 }
1901 }
1902
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001903 boolean startHomeActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001904 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1905 && mTopAction == null) {
1906 // We are running in factory test mode, but unable to find
1907 // the factory test app, so just sit around displaying the
1908 // error message and don't try to start anything.
1909 return false;
1910 }
1911 Intent intent = new Intent(
1912 mTopAction,
1913 mTopData != null ? Uri.parse(mTopData) : null);
1914 intent.setComponent(mTopComponent);
1915 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
1916 intent.addCategory(Intent.CATEGORY_HOME);
1917 }
1918 ActivityInfo aInfo =
1919 intent.resolveActivityInfo(mContext.getPackageManager(),
1920 STOCK_PM_FLAGS);
1921 if (aInfo != null) {
1922 intent.setComponent(new ComponentName(
1923 aInfo.applicationInfo.packageName, aInfo.name));
1924 // Don't do this if the home app is currently being
1925 // instrumented.
1926 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
1927 aInfo.applicationInfo.uid);
1928 if (app == null || app.instrumentationClass == null) {
1929 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001930 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001931 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001932 }
1933 }
1934
1935
1936 return true;
1937 }
1938
1939 /**
1940 * Starts the "new version setup screen" if appropriate.
1941 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001942 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001943 // Only do this once per boot.
1944 if (mCheckedForSetup) {
1945 return;
1946 }
1947
1948 // We will show this screen if the current one is a different
1949 // version than the last one shown, and we are not running in
1950 // low-level factory test mode.
1951 final ContentResolver resolver = mContext.getContentResolver();
1952 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
1953 Settings.Secure.getInt(resolver,
1954 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
1955 mCheckedForSetup = true;
1956
1957 // See if we should be showing the platform update setup UI.
1958 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
1959 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
1960 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
1961
1962 // We don't allow third party apps to replace this.
1963 ResolveInfo ri = null;
1964 for (int i=0; ris != null && i<ris.size(); i++) {
1965 if ((ris.get(i).activityInfo.applicationInfo.flags
1966 & ApplicationInfo.FLAG_SYSTEM) != 0) {
1967 ri = ris.get(i);
1968 break;
1969 }
1970 }
1971
1972 if (ri != null) {
1973 String vers = ri.activityInfo.metaData != null
1974 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
1975 : null;
1976 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
1977 vers = ri.activityInfo.applicationInfo.metaData.getString(
1978 Intent.METADATA_SETUP_VERSION);
1979 }
1980 String lastVers = Settings.Secure.getString(
1981 resolver, Settings.Secure.LAST_SETUP_SHOWN);
1982 if (vers != null && !vers.equals(lastVers)) {
1983 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1984 intent.setComponent(new ComponentName(
1985 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001986 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001987 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001988 }
1989 }
1990 }
1991 }
1992
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001993 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001994 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001995 }
1996
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001997 public int getFrontActivityScreenCompatMode() {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001998 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001999 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2000 }
2001 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002002
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002003 public void setFrontActivityScreenCompatMode(int mode) {
2004 synchronized (this) {
2005 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2006 }
2007 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002008
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002009 public int getPackageScreenCompatMode(String packageName) {
2010 synchronized (this) {
2011 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2012 }
2013 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002014
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002015 public void setPackageScreenCompatMode(String packageName, int mode) {
2016 synchronized (this) {
2017 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002018 }
2019 }
2020
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002021 public boolean getPackageAskScreenCompat(String packageName) {
2022 synchronized (this) {
2023 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2024 }
2025 }
2026
2027 public void setPackageAskScreenCompat(String packageName, boolean ask) {
2028 synchronized (this) {
2029 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2030 }
2031 }
2032
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002033 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002034 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002035
2036 final int identHash = System.identityHashCode(r);
2037 updateUsageStats(r, true);
2038
2039 int i = mWatchers.beginBroadcast();
2040 while (i > 0) {
2041 i--;
2042 IActivityWatcher w = mWatchers.getBroadcastItem(i);
2043 if (w != null) {
2044 try {
2045 w.activityResuming(identHash);
2046 } catch (RemoteException e) {
2047 }
2048 }
2049 }
2050 mWatchers.finishBroadcast();
2051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052
Jeff Sharkeya4620792011-05-20 15:29:23 -07002053 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2054 int i = mProcessObservers.beginBroadcast();
2055 while (i > 0) {
2056 i--;
2057 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2058 if (observer != null) {
2059 try {
2060 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2061 } catch (RemoteException e) {
2062 }
2063 }
2064 }
2065 mProcessObservers.finishBroadcast();
2066 }
2067
2068 private void dispatchProcessDied(int pid, int uid) {
2069 int i = mProcessObservers.beginBroadcast();
2070 while (i > 0) {
2071 i--;
2072 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2073 if (observer != null) {
2074 try {
2075 observer.onProcessDied(pid, uid);
2076 } catch (RemoteException e) {
2077 }
2078 }
2079 }
2080 mProcessObservers.finishBroadcast();
2081 }
2082
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002083 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002084 final int N = mPendingActivityLaunches.size();
2085 if (N <= 0) {
2086 return;
2087 }
2088 for (int i=0; i<N; i++) {
2089 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002090 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002091 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
2092 doResume && i == (N-1));
2093 }
2094 mPendingActivityLaunches.clear();
2095 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002096
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002097 public final int startActivity(IApplicationThread caller,
2098 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2099 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002100 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
2101 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002102 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002103 grantedUriPermissions, grantedMode, resultTo, resultWho,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002104 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
2105 null, null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002106 }
2107
2108 public final WaitResult startActivityAndWait(IApplicationThread caller,
2109 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2110 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002111 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
2112 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002113 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002114 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002115 grantedUriPermissions, grantedMode, resultTo, resultWho,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002116 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
2117 res, null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002118 return res;
2119 }
2120
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002121 public final int startActivityWithConfig(IApplicationThread caller,
2122 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2123 int grantedMode, IBinder resultTo,
2124 String resultWho, int requestCode, boolean onlyIfNeeded,
2125 boolean debug, Configuration config) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002126 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002127 grantedUriPermissions, grantedMode, resultTo, resultWho,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002128 requestCode, onlyIfNeeded, debug, null, null, false, null, config);
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002129 }
2130
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002131 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002132 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002133 IBinder resultTo, String resultWho, int requestCode,
2134 int flagsMask, int flagsValues) {
2135 // Refuse possible leaked file descriptors
2136 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2137 throw new IllegalArgumentException("File descriptors passed in Intent");
2138 }
2139
2140 IIntentSender sender = intent.getTarget();
2141 if (!(sender instanceof PendingIntentRecord)) {
2142 throw new IllegalArgumentException("Bad PendingIntent object");
2143 }
2144
2145 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002146
2147 synchronized (this) {
2148 // If this is coming from the currently resumed activity, it is
2149 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002150 if (mMainStack.mResumedActivity != null
2151 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002152 Binder.getCallingUid()) {
2153 mAppSwitchesAllowedTime = 0;
2154 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002155 }
2156
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002157 return pir.sendInner(0, fillInIntent, resolvedType, null,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002158 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
2159 }
2160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 public boolean startNextMatchingActivity(IBinder callingActivity,
2162 Intent intent) {
2163 // Refuse possible leaked file descriptors
2164 if (intent != null && intent.hasFileDescriptors() == true) {
2165 throw new IllegalArgumentException("File descriptors passed in Intent");
2166 }
2167
2168 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002169 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2170 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 return false;
2172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 if (r.app == null || r.app.thread == null) {
2174 // The caller is not running... d'oh!
2175 return false;
2176 }
2177 intent = new Intent(intent);
2178 // The caller is not allowed to change the data.
2179 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2180 // And we are resetting to find the next component...
2181 intent.setComponent(null);
2182
2183 ActivityInfo aInfo = null;
2184 try {
2185 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002186 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002188 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189
2190 // Look for the original activity in the list...
2191 final int N = resolves != null ? resolves.size() : 0;
2192 for (int i=0; i<N; i++) {
2193 ResolveInfo rInfo = resolves.get(i);
2194 if (rInfo.activityInfo.packageName.equals(r.packageName)
2195 && rInfo.activityInfo.name.equals(r.info.name)) {
2196 // We found the current one... the next matching is
2197 // after it.
2198 i++;
2199 if (i<N) {
2200 aInfo = resolves.get(i).activityInfo;
2201 }
2202 break;
2203 }
2204 }
2205 } catch (RemoteException e) {
2206 }
2207
2208 if (aInfo == null) {
2209 // Nobody who is next!
2210 return false;
2211 }
2212
2213 intent.setComponent(new ComponentName(
2214 aInfo.applicationInfo.packageName, aInfo.name));
2215 intent.setFlags(intent.getFlags()&~(
2216 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2217 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2218 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2219 Intent.FLAG_ACTIVITY_NEW_TASK));
2220
2221 // Okay now we need to start the new activity, replacing the
2222 // currently running activity. This is a little tricky because
2223 // we want to start the new one as if the current one is finished,
2224 // but not finish the current one first so that there is no flicker.
2225 // And thus...
2226 final boolean wasFinishing = r.finishing;
2227 r.finishing = true;
2228
2229 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002230 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 final String resultWho = r.resultWho;
2232 final int requestCode = r.requestCode;
2233 r.resultTo = null;
2234 if (resultTo != null) {
2235 resultTo.removeResultsLocked(r, resultWho, requestCode);
2236 }
2237
2238 final long origId = Binder.clearCallingIdentity();
2239 // XXX we are not dealing with propagating grantedUriPermissions...
2240 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002241 int res = mMainStack.startActivityLocked(r.app.thread, intent,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 r.resolvedType, null, 0, aInfo, resultTo, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002243 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 Binder.restoreCallingIdentity(origId);
2245
2246 r.finishing = wasFinishing;
2247 if (res != START_SUCCESS) {
2248 return false;
2249 }
2250 return true;
2251 }
2252 }
2253
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002254 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 Intent intent, String resolvedType, IBinder resultTo,
2256 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002257
2258 // This is so super not safe, that only the system (or okay root)
2259 // can do it.
2260 final int callingUid = Binder.getCallingUid();
2261 if (callingUid != 0 && callingUid != Process.myUid()) {
2262 throw new SecurityException(
2263 "startActivityInPackage only available to the system");
2264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002266 return mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002267 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false,
2268 null, null, false, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002269 }
2270
2271 public final int startActivities(IApplicationThread caller,
2272 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2273 return mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo);
2274 }
2275
2276 public final int startActivitiesInPackage(int uid,
2277 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2278
2279 // This is so super not safe, that only the system (or okay root)
2280 // can do it.
2281 final int callingUid = Binder.getCallingUid();
2282 if (callingUid != 0 && callingUid != Process.myUid()) {
2283 throw new SecurityException(
2284 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 }
2286
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002287 return mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 }
2289
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002290 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002292 // Quick case: check if the top-most recent task is the same.
2293 if (N > 0 && mRecentTasks.get(0) == task) {
2294 return;
2295 }
2296 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 for (int i=0; i<N; i++) {
2298 TaskRecord tr = mRecentTasks.get(i);
2299 if ((task.affinity != null && task.affinity.equals(tr.affinity))
2300 || (task.intent != null && task.intent.filterEquals(tr.intent))) {
2301 mRecentTasks.remove(i);
2302 i--;
2303 N--;
2304 if (task.intent == null) {
2305 // If the new recent task we are adding is not fully
2306 // specified, then replace it with the existing recent task.
2307 task = tr;
2308 }
2309 }
2310 }
2311 if (N >= MAX_RECENT_TASKS) {
2312 mRecentTasks.remove(N-1);
2313 }
2314 mRecentTasks.add(0, task);
2315 }
2316
2317 public void setRequestedOrientation(IBinder token,
2318 int requestedOrientation) {
2319 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002320 ActivityRecord r = mMainStack.isInStackLocked(token);
2321 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 return;
2323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 final long origId = Binder.clearCallingIdentity();
2325 mWindowManager.setAppOrientation(r, requestedOrientation);
2326 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002327 mConfiguration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 r.mayFreezeScreenLocked(r.app) ? r : null);
2329 if (config != null) {
2330 r.frozenBeforeDestroy = true;
Dianne Hackborn31ca8542011-07-19 14:58:28 -07002331 if (!updateConfigurationLocked(config, r, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002332 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 }
2334 }
2335 Binder.restoreCallingIdentity(origId);
2336 }
2337 }
2338
2339 public int getRequestedOrientation(IBinder token) {
2340 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002341 ActivityRecord r = mMainStack.isInStackLocked(token);
2342 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 return mWindowManager.getAppOrientation(r);
2346 }
2347 }
2348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 /**
2350 * This is the internal entry point for handling Activity.finish().
2351 *
2352 * @param token The Binder token referencing the Activity we want to finish.
2353 * @param resultCode Result code, if any, from this Activity.
2354 * @param resultData Result data (Intent), if any, from this Activity.
2355 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002356 * @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 -08002357 */
2358 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2359 // Refuse possible leaked file descriptors
2360 if (resultData != null && resultData.hasFileDescriptors() == true) {
2361 throw new IllegalArgumentException("File descriptors passed in Intent");
2362 }
2363
2364 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002365 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002367 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 if (next != null) {
2369 // ask watcher if this is allowed
2370 boolean resumeOK = true;
2371 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002372 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002374 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 }
2376
2377 if (!resumeOK) {
2378 return false;
2379 }
2380 }
2381 }
2382 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002383 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 resultData, "app-request");
2385 Binder.restoreCallingIdentity(origId);
2386 return res;
2387 }
2388 }
2389
Dianne Hackborn860755f2010-06-03 18:47:52 -07002390 public final void finishHeavyWeightApp() {
2391 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2392 != PackageManager.PERMISSION_GRANTED) {
2393 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2394 + Binder.getCallingPid()
2395 + ", uid=" + Binder.getCallingUid()
2396 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2397 Slog.w(TAG, msg);
2398 throw new SecurityException(msg);
2399 }
2400
2401 synchronized(this) {
2402 if (mHeavyWeightProcess == null) {
2403 return;
2404 }
2405
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002406 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002407 mHeavyWeightProcess.activities);
2408 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002409 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002410 if (!r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002411 int index = mMainStack.indexOfTokenLocked(r);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002412 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002413 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002414 null, "finish-heavy");
2415 }
2416 }
2417 }
2418
2419 mHeavyWeightProcess = null;
2420 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2421 }
2422 }
2423
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002424 public void crashApplication(int uid, int initialPid, String packageName,
2425 String message) {
2426 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2427 != PackageManager.PERMISSION_GRANTED) {
2428 String msg = "Permission Denial: crashApplication() from pid="
2429 + Binder.getCallingPid()
2430 + ", uid=" + Binder.getCallingUid()
2431 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2432 Slog.w(TAG, msg);
2433 throw new SecurityException(msg);
2434 }
2435
2436 synchronized(this) {
2437 ProcessRecord proc = null;
2438
2439 // Figure out which process to kill. We don't trust that initialPid
2440 // still has any relation to current pids, so must scan through the
2441 // list.
2442 synchronized (mPidsSelfLocked) {
2443 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2444 ProcessRecord p = mPidsSelfLocked.valueAt(i);
2445 if (p.info.uid != uid) {
2446 continue;
2447 }
2448 if (p.pid == initialPid) {
2449 proc = p;
2450 break;
2451 }
2452 for (String str : p.pkgList) {
2453 if (str.equals(packageName)) {
2454 proc = p;
2455 }
2456 }
2457 }
2458 }
2459
2460 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002461 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002462 + " initialPid=" + initialPid
2463 + " packageName=" + packageName);
2464 return;
2465 }
2466
2467 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002468 if (proc.pid == Process.myPid()) {
2469 Log.w(TAG, "crashApplication: trying to crash self!");
2470 return;
2471 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002472 long ident = Binder.clearCallingIdentity();
2473 try {
2474 proc.thread.scheduleCrash(message);
2475 } catch (RemoteException e) {
2476 }
2477 Binder.restoreCallingIdentity(ident);
2478 }
2479 }
2480 }
2481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 public final void finishSubActivity(IBinder token, String resultWho,
2483 int requestCode) {
2484 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002485 ActivityRecord self = mMainStack.isInStackLocked(token);
2486 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 return;
2488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489
2490 final long origId = Binder.clearCallingIdentity();
2491
2492 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002493 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2494 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 if (r.resultTo == self && r.requestCode == requestCode) {
2496 if ((r.resultWho == null && resultWho == null) ||
2497 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002498 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 Activity.RESULT_CANCELED, null, "request-sub");
2500 }
2501 }
2502 }
2503
2504 Binder.restoreCallingIdentity(origId);
2505 }
2506 }
2507
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002508 public boolean willActivityBeVisible(IBinder token) {
2509 synchronized(this) {
2510 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002511 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2512 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002513 if (r == token) {
2514 return true;
2515 }
2516 if (r.fullscreen && !r.finishing) {
2517 return false;
2518 }
2519 }
2520 return true;
2521 }
2522 }
2523
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002524 public void overridePendingTransition(IBinder token, String packageName,
2525 int enterAnim, int exitAnim) {
2526 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002527 ActivityRecord self = mMainStack.isInStackLocked(token);
2528 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002529 return;
2530 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002531
2532 final long origId = Binder.clearCallingIdentity();
2533
2534 if (self.state == ActivityState.RESUMED
2535 || self.state == ActivityState.PAUSING) {
2536 mWindowManager.overridePendingAppTransition(packageName,
2537 enterAnim, exitAnim);
2538 }
2539
2540 Binder.restoreCallingIdentity(origId);
2541 }
2542 }
2543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 * Main function for removing an existing process from the activity manager
2546 * as a result of that process going away. Clears out all connections
2547 * to the process.
2548 */
2549 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002550 boolean restarting, boolean allowRestart) {
2551 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002553 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 }
2555
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002556 if (mProfileProc == app) {
2557 clearProfilerLocked();
2558 }
2559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 // Just in case...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002561 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2562 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2563 mMainStack.mPausingActivity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002565 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2566 mMainStack.mLastPausedActivity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 }
2568
2569 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002570 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571
2572 boolean atTop = true;
2573 boolean hasVisibleActivities = false;
2574
2575 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002576 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002577 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 TAG, "Removing app " + app + " from history with " + i + " entries");
2579 while (i > 0) {
2580 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002581 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002582 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2584 if (r.app == app) {
2585 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002586 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 TAG, "Removing this entry! frozen=" + r.haveState
2588 + " finishing=" + r.finishing);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08002589 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002590 mMainStack.mHistory.remove(i);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002591 r.takeFromHistory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 mWindowManager.removeAppToken(r);
2593 if (VALIDATE_TOKENS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002594 mWindowManager.validateAppTokens(mMainStack.mHistory);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002596 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597
2598 } else {
2599 // We have the current state for this activity, so
2600 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002601 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 TAG, "Keeping entry, setting app to null");
2603 if (r.visible) {
2604 hasVisibleActivities = true;
2605 }
2606 r.app = null;
2607 r.nowVisible = false;
2608 if (!r.haveState) {
2609 r.icicle = null;
2610 }
2611 }
2612
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002613 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 }
2615 atTop = false;
2616 }
2617
2618 app.activities.clear();
2619
2620 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002621 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 + " running instrumentation " + app.instrumentationClass);
2623 Bundle info = new Bundle();
2624 info.putString("shortMsg", "Process crashed.");
2625 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2626 }
2627
2628 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002629 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 // If there was nothing to resume, and we are not already
2631 // restarting this process, but there is a visible activity that
2632 // is hosted by the process... then make sure all visible
2633 // activities are running, taking care of restarting this
2634 // process.
2635 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002636 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 }
2638 }
2639 }
2640 }
2641
2642 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2643 IBinder threadBinder = thread.asBinder();
2644
2645 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002646 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2647 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2649 return i;
2650 }
2651 }
2652 return -1;
2653 }
2654
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002655 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 IApplicationThread thread) {
2657 if (thread == null) {
2658 return null;
2659 }
2660
2661 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002662 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 }
2664
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002665 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 IApplicationThread thread) {
2667
2668 mProcDeaths[0]++;
2669
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002670 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2671 synchronized (stats) {
2672 stats.noteProcessDiedLocked(app.info.uid, pid);
2673 }
2674
Magnus Edlund7bb25812010-02-24 15:45:06 +01002675 // Clean up already done if the process has been re-started.
2676 if (app.pid == pid && app.thread != null &&
2677 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002678 if (!app.killedBackground) {
2679 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2680 + ") has died.");
2681 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002682 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002683 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 TAG, "Dying app: " + app + ", pid: " + pid
2685 + ", thread: " + thread.asBinder());
2686 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002687 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688
2689 if (doLowMem) {
2690 // If there are no longer any background processes running,
2691 // and the app that died was not running instrumentation,
2692 // then tell everyone we are now low on memory.
2693 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002694 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2695 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002696 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 haveBg = true;
2698 break;
2699 }
2700 }
2701
2702 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002703 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002704 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002705 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2706 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002707 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002708 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2709 // The low memory report is overriding any current
2710 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002711 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002712 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002713 rec.lastRequestedGc = 0;
2714 } else {
2715 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002717 rec.reportLowMemory = true;
2718 rec.lastLowMemory = now;
2719 mProcessesToGc.remove(rec);
2720 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 }
2722 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002723 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 }
2725 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002726 } else if (app.pid != pid) {
2727 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002728 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002729 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002730 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002731 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002732 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 + thread.asBinder());
2734 }
2735 }
2736
Dan Egnor42471dd2010-01-07 17:25:22 -08002737 /**
2738 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002739 * @param clearTraces causes the dump file to be erased prior to the new
2740 * traces being written, if true; when false, the new traces will be
2741 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002742 * @param firstPids of dalvik VM processes to dump stack traces for first
2743 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002744 * @return file containing stack traces, or null if no dump file is configured
2745 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002746 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2747 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002748 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2749 if (tracesPath == null || tracesPath.length() == 0) {
2750 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002752
2753 File tracesFile = new File(tracesPath);
2754 try {
2755 File tracesDir = tracesFile.getParentFile();
2756 if (!tracesDir.exists()) tracesFile.mkdirs();
2757 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2758
Christopher Tate6ee412d2010-05-28 12:01:56 -07002759 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002760 tracesFile.createNewFile();
2761 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2762 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002763 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002764 return null;
2765 }
2766
2767 // Use a FileObserver to detect when traces finish writing.
2768 // The order of traces is considered important to maintain for legibility.
2769 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2770 public synchronized void onEvent(int event, String path) { notify(); }
2771 };
2772
2773 try {
2774 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002775
2776 // First collect all of the stacks of the most important pids.
2777 try {
2778 int num = firstPids.size();
2779 for (int i = 0; i < num; i++) {
2780 synchronized (observer) {
2781 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2782 observer.wait(200); // Wait for write-close, give up after 200msec
2783 }
2784 }
2785 } catch (InterruptedException e) {
2786 Log.wtf(TAG, e);
2787 }
2788
2789 // Next measure CPU usage.
2790 if (processStats != null) {
2791 processStats.init();
2792 System.gc();
2793 processStats.update();
2794 try {
2795 synchronized (processStats) {
2796 processStats.wait(500); // measure over 1/2 second.
2797 }
2798 } catch (InterruptedException e) {
2799 }
2800 processStats.update();
2801
2802 // We'll take the stack crawls of just the top apps using CPU.
2803 final int N = processStats.countWorkingStats();
2804 int numProcs = 0;
2805 for (int i=0; i<N && numProcs<5; i++) {
2806 ProcessStats.Stats stats = processStats.getWorkingStats(i);
2807 if (lastPids.indexOfKey(stats.pid) >= 0) {
2808 numProcs++;
2809 try {
2810 synchronized (observer) {
2811 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
2812 observer.wait(200); // Wait for write-close, give up after 200msec
2813 }
2814 } catch (InterruptedException e) {
2815 Log.wtf(TAG, e);
2816 }
2817
2818 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002819 }
2820 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002821
2822 return tracesFile;
2823
Dan Egnor42471dd2010-01-07 17:25:22 -08002824 } finally {
2825 observer.stopWatching();
2826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 }
2828
Jeff Brown4d94a762010-09-23 11:33:28 -07002829 private final class AppNotResponding implements Runnable {
2830 private final ProcessRecord mApp;
2831 private final String mAnnotation;
2832
2833 public AppNotResponding(ProcessRecord app, String annotation) {
2834 mApp = app;
2835 mAnnotation = annotation;
2836 }
2837
2838 @Override
2839 public void run() {
2840 appNotResponding(mApp, null, null, mAnnotation);
2841 }
2842 }
2843
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002844 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
2845 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002846 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
2847 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
2848
Dianne Hackborn287952c2010-09-22 22:34:31 -07002849 if (mController != null) {
2850 try {
2851 // 0 == continue, -1 = kill process immediately
2852 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
2853 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
2854 } catch (RemoteException e) {
2855 mController = null;
2856 }
2857 }
2858
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002859 long anrTime = SystemClock.uptimeMillis();
2860 if (MONITOR_CPU_USAGE) {
2861 updateCpuStatsNow();
2862 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002863
2864 synchronized (this) {
2865 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
2866 if (mShuttingDown) {
2867 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
2868 return;
2869 } else if (app.notResponding) {
2870 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
2871 return;
2872 } else if (app.crashing) {
2873 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
2874 return;
2875 }
2876
2877 // In case we come through here for the same app before completing
2878 // this one, mark as anring now so we will bail out.
2879 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08002880
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002881 // Log the ANR to the event log.
2882 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
2883 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08002884
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002885 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002886 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002887
2888 int parentPid = app.pid;
2889 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002890 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002891
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002892 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08002893
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002894 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
2895 ProcessRecord r = mLruProcesses.get(i);
2896 if (r != null && r.thread != null) {
2897 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002898 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
2899 if (r.persistent) {
2900 firstPids.add(pid);
2901 } else {
2902 lastPids.put(pid, Boolean.TRUE);
2903 }
2904 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 }
2907 }
2908
Dan Egnor42471dd2010-01-07 17:25:22 -08002909 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002910 StringBuilder info = mStringBuilder;
2911 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08002912 info.append("ANR in ").append(app.processName);
2913 if (activity != null && activity.shortComponentName != null) {
2914 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07002915 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08002916 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08002918 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002920 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08002921 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923
Dianne Hackborn287952c2010-09-22 22:34:31 -07002924 final ProcessStats processStats = new ProcessStats(true);
2925
2926 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
2927
Dan Egnor42471dd2010-01-07 17:25:22 -08002928 String cpuInfo = null;
2929 if (MONITOR_CPU_USAGE) {
2930 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002931 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002932 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002933 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002934 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08002935 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 }
2937
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002938 info.append(processStats.printCurrentState(anrTime));
2939
Joe Onorato8a9b2202010-02-26 18:56:32 -08002940 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08002941 if (tracesFile == null) {
2942 // There is no trace file, so dump (only) the alleged culprit's threads to the log
2943 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
2944 }
2945
2946 addErrorToDropBox("anr", app, activity, parent, annotation, cpuInfo, tracesFile, null);
2947
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002948 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08002950 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
2951 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002953 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
2954 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 }
2956 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002957 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 }
2959 }
2960
Dan Egnor42471dd2010-01-07 17:25:22 -08002961 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
2962 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
2963 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002964
2965 synchronized (this) {
2966 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002967 Slog.w(TAG, "Killing " + app + ": background ANR");
2968 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
2969 app.processName, app.setAdj, "background ANR");
2970 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002971 return;
2972 }
2973
2974 // Set the app's notResponding state, and look up the errorReportReceiver
2975 makeAppNotRespondingLocked(app,
2976 activity != null ? activity.shortComponentName : null,
2977 annotation != null ? "ANR " + annotation : "ANR",
2978 info.toString());
2979
2980 // Bring up the infamous App Not Responding dialog
2981 Message msg = Message.obtain();
2982 HashMap map = new HashMap();
2983 msg.what = SHOW_NOT_RESPONDING_MSG;
2984 msg.obj = map;
2985 map.put("app", app);
2986 if (activity != null) {
2987 map.put("activity", activity);
2988 }
2989
2990 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08002991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 }
2993
Dianne Hackborn0dad3642010-09-09 21:25:35 -07002994 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
2995 if (!mLaunchWarningShown) {
2996 mLaunchWarningShown = true;
2997 mHandler.post(new Runnable() {
2998 @Override
2999 public void run() {
3000 synchronized (ActivityManagerService.this) {
3001 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3002 d.show();
3003 mHandler.postDelayed(new Runnable() {
3004 @Override
3005 public void run() {
3006 synchronized (ActivityManagerService.this) {
3007 d.dismiss();
3008 mLaunchWarningShown = false;
3009 }
3010 }
3011 }, 4000);
3012 }
3013 }
3014 });
3015 }
3016 }
3017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 public boolean clearApplicationUserData(final String packageName,
3019 final IPackageDataObserver observer) {
3020 int uid = Binder.getCallingUid();
3021 int pid = Binder.getCallingPid();
3022 long callingId = Binder.clearCallingIdentity();
3023 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003024 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 int pkgUid = -1;
3026 synchronized(this) {
3027 try {
3028 pkgUid = pm.getPackageUid(packageName);
3029 } catch (RemoteException e) {
3030 }
3031 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003032 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 return false;
3034 }
3035 if (uid == pkgUid || checkComponentPermission(
3036 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003037 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003039 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 } else {
3041 throw new SecurityException(pid+" does not have permission:"+
3042 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3043 "for process:"+packageName);
3044 }
3045 }
3046
3047 try {
3048 //clear application user data
3049 pm.clearApplicationUserData(packageName, observer);
3050 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3051 Uri.fromParts("package", packageName, null));
3052 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003053 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
3054 null, null, 0, null, null, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 } catch (RemoteException e) {
3056 }
3057 } finally {
3058 Binder.restoreCallingIdentity(callingId);
3059 }
3060 return true;
3061 }
3062
Dianne Hackborn03abb812010-01-04 18:43:19 -08003063 public void killBackgroundProcesses(final String packageName) {
3064 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3065 != PackageManager.PERMISSION_GRANTED &&
3066 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3067 != PackageManager.PERMISSION_GRANTED) {
3068 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 + Binder.getCallingPid()
3070 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003071 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003072 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 throw new SecurityException(msg);
3074 }
3075
3076 long callingId = Binder.clearCallingIdentity();
3077 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003078 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 int pkgUid = -1;
3080 synchronized(this) {
3081 try {
3082 pkgUid = pm.getPackageUid(packageName);
3083 } catch (RemoteException e) {
3084 }
3085 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003086 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 return;
3088 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003089 killPackageProcessesLocked(packageName, pkgUid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003090 ProcessList.SECONDARY_SERVER_ADJ, false, true, true, false);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003091 }
3092 } finally {
3093 Binder.restoreCallingIdentity(callingId);
3094 }
3095 }
3096
3097 public void forceStopPackage(final String packageName) {
3098 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3099 != PackageManager.PERMISSION_GRANTED) {
3100 String msg = "Permission Denial: forceStopPackage() from pid="
3101 + Binder.getCallingPid()
3102 + ", uid=" + Binder.getCallingUid()
3103 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003104 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003105 throw new SecurityException(msg);
3106 }
3107
3108 long callingId = Binder.clearCallingIdentity();
3109 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003110 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003111 int pkgUid = -1;
3112 synchronized(this) {
3113 try {
3114 pkgUid = pm.getPackageUid(packageName);
3115 } catch (RemoteException e) {
3116 }
3117 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003118 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003119 return;
3120 }
3121 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003122 try {
3123 pm.setPackageStoppedState(packageName, true);
3124 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003125 } catch (IllegalArgumentException e) {
3126 Slog.w(TAG, "Failed trying to unstop package "
3127 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 }
3130 } finally {
3131 Binder.restoreCallingIdentity(callingId);
3132 }
3133 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003134
3135 /*
3136 * The pkg name and uid have to be specified.
3137 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3138 */
3139 public void killApplicationWithUid(String pkg, int uid) {
3140 if (pkg == null) {
3141 return;
3142 }
3143 // Make sure the uid is valid.
3144 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003145 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003146 return;
3147 }
3148 int callerUid = Binder.getCallingUid();
3149 // Only the system server can kill an application
3150 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003151 // Post an aysnc message to kill the application
3152 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3153 msg.arg1 = uid;
3154 msg.arg2 = 0;
3155 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003156 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003157 } else {
3158 throw new SecurityException(callerUid + " cannot kill pkg: " +
3159 pkg);
3160 }
3161 }
3162
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003163 public void closeSystemDialogs(String reason) {
3164 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003165 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003166 if (reason != null) {
3167 intent.putExtra("reason", reason);
3168 }
3169
3170 final int uid = Binder.getCallingUid();
3171 final long origId = Binder.clearCallingIdentity();
3172 synchronized (this) {
3173 int i = mWatchers.beginBroadcast();
3174 while (i > 0) {
3175 i--;
3176 IActivityWatcher w = mWatchers.getBroadcastItem(i);
3177 if (w != null) {
3178 try {
3179 w.closingSystemDialogs(reason);
3180 } catch (RemoteException e) {
3181 }
3182 }
3183 }
3184 mWatchers.finishBroadcast();
3185
Dianne Hackbornffa42482009-09-23 22:20:11 -07003186 mWindowManager.closeSystemDialogs(reason);
3187
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003188 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3189 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003190 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003191 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003192 Activity.RESULT_CANCELED, null, "close-sys");
3193 }
3194 }
3195
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003196 broadcastIntentLocked(null, null, intent, null,
3197 null, 0, null, null, null, false, false, -1, uid);
3198 }
3199 Binder.restoreCallingIdentity(origId);
3200 }
3201
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003202 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003203 throws RemoteException {
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003204 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3205 for (int i=pids.length-1; i>=0; i--) {
3206 infos[i] = new Debug.MemoryInfo();
3207 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003208 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003209 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003210 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003211
Dianne Hackbornb437e092011-08-05 17:50:29 -07003212 public long[] getProcessPss(int[] pids) throws RemoteException {
3213 long[] pss = new long[pids.length];
3214 for (int i=pids.length-1; i>=0; i--) {
3215 pss[i] = Debug.getPss(pids[i]);
3216 }
3217 return pss;
3218 }
3219
Christopher Tate5e1ab332009-09-01 20:32:49 -07003220 public void killApplicationProcess(String processName, int uid) {
3221 if (processName == null) {
3222 return;
3223 }
3224
3225 int callerUid = Binder.getCallingUid();
3226 // Only the system server can kill an application
3227 if (callerUid == Process.SYSTEM_UID) {
3228 synchronized (this) {
3229 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003230 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003231 try {
3232 app.thread.scheduleSuicide();
3233 } catch (RemoteException e) {
3234 // If the other end already died, then our work here is done.
3235 }
3236 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003237 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003238 + processName + " / " + uid);
3239 }
3240 }
3241 } else {
3242 throw new SecurityException(callerUid + " cannot kill app process: " +
3243 processName);
3244 }
3245 }
3246
Dianne Hackborn03abb812010-01-04 18:43:19 -08003247 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07003248 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3250 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003251 if (!mProcessesReady) {
3252 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 intent.putExtra(Intent.EXTRA_UID, uid);
3255 broadcastIntentLocked(null, null, intent,
3256 null, null, 0, null, null, null,
3257 false, false, MY_PID, Process.SYSTEM_UID);
3258 }
3259
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003260 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003261 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
3262 boolean evenPersistent) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003263 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264
Dianne Hackborn03abb812010-01-04 18:43:19 -08003265 // Remove all processes this package may have touched: all with the
3266 // same UID (except for the system or root user), and all whose name
3267 // matches the package name.
3268 final String procNamePrefix = packageName + ":";
3269 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3270 final int NA = apps.size();
3271 for (int ia=0; ia<NA; ia++) {
3272 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003273 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003274 // we don't kill persistent processes
3275 continue;
3276 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003277 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003278 if (doit) {
3279 procs.add(app);
3280 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003281 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3282 || app.processName.equals(packageName)
3283 || app.processName.startsWith(procNamePrefix)) {
3284 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003285 if (!doit) {
3286 return true;
3287 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003288 app.removed = true;
3289 procs.add(app);
3290 }
3291 }
3292 }
3293 }
3294
3295 int N = procs.size();
3296 for (int i=0; i<N; i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003297 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003298 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003299 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003300 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003301
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003302 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003303 boolean callerWillRestart, boolean purgeCache, boolean doit,
3304 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003305 int i;
3306 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 if (uid < 0) {
3309 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003310 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 } catch (RemoteException e) {
3312 }
3313 }
3314
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003315 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003316 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003317
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003318 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3319 while (badApps.hasNext()) {
3320 SparseArray<Long> ba = badApps.next();
3321 if (ba.get(uid) != null) {
3322 badApps.remove();
3323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 }
3325 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003326
3327 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Christopher Tate3dacd842011-08-19 14:56:15 -07003328 callerWillRestart, false, doit, evenPersistent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003330 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3331 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Christopher Tate064d8422011-07-26 15:38:07 -07003332 if (r.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003333 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003334 if (!doit) {
3335 return true;
3336 }
3337 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003338 Slog.i(TAG, " Force finishing activity " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 if (r.app != null) {
3340 r.app.removed = true;
3341 }
3342 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003343 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "uninstall");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 }
3345 }
3346
3347 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3348 for (ServiceRecord service : mServices.values()) {
Christopher Tate064d8422011-07-26 15:38:07 -07003349 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003350 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003351 if (!doit) {
3352 return true;
3353 }
3354 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003355 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 if (service.app != null) {
3357 service.app.removed = true;
3358 }
3359 service.app = null;
3360 services.add(service);
3361 }
3362 }
3363
3364 N = services.size();
3365 for (i=0; i<N; i++) {
3366 bringDownServiceLocked(services.get(i), true);
3367 }
3368
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003369 if (doit) {
3370 if (purgeCache) {
3371 AttributeCache ac = AttributeCache.instance();
3372 if (ac != null) {
3373 ac.removePackage(name);
3374 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003375 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003376 mMainStack.resumeTopActivityLocked(null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003377 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003378
3379 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 }
3381
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003382 private final boolean removeProcessLocked(ProcessRecord app,
3383 boolean callerWillRestart, boolean allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 final String name = app.processName;
3385 final int uid = app.info.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003386 if (DEBUG_PROCESSES) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 TAG, "Force removing process " + app + " (" + name
3388 + "/" + uid + ")");
3389
3390 mProcessNames.remove(name, uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003391 if (mHeavyWeightProcess == app) {
3392 mHeavyWeightProcess = null;
3393 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 boolean needRestart = false;
3396 if (app.pid > 0 && app.pid != MY_PID) {
3397 int pid = app.pid;
3398 synchronized (mPidsSelfLocked) {
3399 mPidsSelfLocked.remove(pid);
3400 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3401 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003402 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003403 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 Process.killProcess(pid);
3405
3406 if (app.persistent) {
3407 if (!callerWillRestart) {
3408 addAppLocked(app.info);
3409 } else {
3410 needRestart = true;
3411 }
3412 }
3413 } else {
3414 mRemovedProcesses.add(app);
3415 }
3416
3417 return needRestart;
3418 }
3419
3420 private final void processStartTimedOutLocked(ProcessRecord app) {
3421 final int pid = app.pid;
3422 boolean gone = false;
3423 synchronized (mPidsSelfLocked) {
3424 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3425 if (knownApp != null && knownApp.thread == null) {
3426 mPidsSelfLocked.remove(pid);
3427 gone = true;
3428 }
3429 }
3430
3431 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003432 Slog.w(TAG, "Process " + app + " failed to attach");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003433 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.info.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003434 app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003436 if (mHeavyWeightProcess == app) {
3437 mHeavyWeightProcess = null;
3438 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3439 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003440 // Take care of any launching providers waiting for this process.
3441 checkAppInLaunchingProvidersLocked(app, true);
3442 // Take care of any services that are waiting for the process.
3443 for (int i=0; i<mPendingServices.size(); i++) {
3444 ServiceRecord sr = mPendingServices.get(i);
3445 if (app.info.uid == sr.appInfo.uid
3446 && app.processName.equals(sr.processName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003447 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003448 mPendingServices.remove(i);
3449 i--;
3450 bringDownServiceLocked(sr, true);
3451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003453 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3454 app.processName, app.setAdj, "start timeout");
3455 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003456 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003457 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003458 try {
3459 IBackupManager bm = IBackupManager.Stub.asInterface(
3460 ServiceManager.getService(Context.BACKUP_SERVICE));
3461 bm.agentDisconnected(app.info.packageName);
3462 } catch (RemoteException e) {
3463 // Can't happen; the backup manager is local
3464 }
3465 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003466 if (mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003467 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003468 mPendingBroadcast.state = BroadcastRecord.IDLE;
3469 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003470 mPendingBroadcast = null;
3471 scheduleBroadcastsLocked();
3472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003474 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 }
3476 }
3477
3478 private final boolean attachApplicationLocked(IApplicationThread thread,
3479 int pid) {
3480
3481 // Find the application record that is being attached... either via
3482 // the pid if we are running in multiple processes, or just pull the
3483 // next app record if we are emulating process with anonymous threads.
3484 ProcessRecord app;
3485 if (pid != MY_PID && pid >= 0) {
3486 synchronized (mPidsSelfLocked) {
3487 app = mPidsSelfLocked.get(pid);
3488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 } else {
3490 app = null;
3491 }
3492
3493 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003494 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003496 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003498 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 } else {
3500 try {
3501 thread.scheduleExit();
3502 } catch (Exception e) {
3503 // Ignore exceptions.
3504 }
3505 }
3506 return false;
3507 }
3508
3509 // If this application record is still attached to a previous
3510 // process, clean it up now.
3511 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003512 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 }
3514
3515 // Tell the process all about itself.
3516
Joe Onorato8a9b2202010-02-26 18:56:32 -08003517 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 TAG, "Binding process pid " + pid + " to record " + app);
3519
3520 String processName = app.processName;
3521 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003522 AppDeathRecipient adr = new AppDeathRecipient(
3523 app, pid, thread);
3524 thread.asBinder().linkToDeath(adr, 0);
3525 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 } catch (RemoteException e) {
3527 app.resetPackageList();
3528 startProcessLocked(app, "link fail", processName);
3529 return false;
3530 }
3531
Doug Zongker2bec3d42009-12-04 12:52:44 -08003532 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533
3534 app.thread = thread;
3535 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003536 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3537 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 app.forcingToForeground = null;
3539 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003540 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 app.debugging = false;
3542
3543 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3544
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003545 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003546 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003548 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003549 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003550 }
3551
Joe Onorato8a9b2202010-02-26 18:56:32 -08003552 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003553 TAG, "New app record " + app
3554 + " thread=" + thread.asBinder() + " pid=" + pid);
3555 try {
3556 int testMode = IApplicationThread.DEBUG_OFF;
3557 if (mDebugApp != null && mDebugApp.equals(processName)) {
3558 testMode = mWaitForDebugger
3559 ? IApplicationThread.DEBUG_WAIT
3560 : IApplicationThread.DEBUG_ON;
3561 app.debugging = true;
3562 if (mDebugTransient) {
3563 mDebugApp = mOrigDebugApp;
3564 mWaitForDebugger = mOrigWaitForDebugger;
3565 }
3566 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003567 String profileFile = app.instrumentationProfileFile;
3568 ParcelFileDescriptor profileFd = null;
3569 boolean profileAutoStop = false;
3570 if (mProfileApp != null && mProfileApp.equals(processName)) {
3571 mProfileProc = app;
3572 profileFile = mProfileFile;
3573 profileFd = mProfileFd;
3574 profileAutoStop = mAutoStopProfiler;
3575 }
3576
Christopher Tate181fafa2009-05-14 11:12:14 -07003577 // If the app is being launched for restore or full backup, set it up specially
3578 boolean isRestrictedBackupMode = false;
3579 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3580 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003581 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003582 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3583 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003584
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003585 ensurePackageDexOpt(app.instrumentationInfo != null
3586 ? app.instrumentationInfo.packageName
3587 : app.info.packageName);
3588 if (app.instrumentationClass != null) {
3589 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003590 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003591 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003592 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003593 ApplicationInfo appInfo = app.instrumentationInfo != null
3594 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003595 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003596 if (profileFd != null) {
3597 profileFd = profileFd.dup();
3598 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003599 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003600 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003602 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003603 mConfiguration, app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003604 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003605 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003606 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 } catch (Exception e) {
3608 // todo: Yikes! What should we do? For now we will try to
3609 // start another process, but that could easily get us in
3610 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003611 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612
3613 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003614 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 startProcessLocked(app, "bind fail", processName);
3616 return false;
3617 }
3618
3619 // Remove this record from the list of starting applications.
3620 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003621 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3622 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 mProcessesOnHold.remove(app);
3624
3625 boolean badApp = false;
3626 boolean didSomething = false;
3627
3628 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003629 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003630 if (hr != null && normalMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
3632 && processName.equals(hr.processName)) {
3633 try {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003634 if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 didSomething = true;
3636 }
3637 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003638 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 + hr.intent.getComponent().flattenToShortString(), e);
3640 badApp = true;
3641 }
3642 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003643 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003644 }
3645 }
3646
3647 // Find any services that should be running in this process...
3648 if (!badApp && mPendingServices.size() > 0) {
3649 ServiceRecord sr = null;
3650 try {
3651 for (int i=0; i<mPendingServices.size(); i++) {
3652 sr = mPendingServices.get(i);
3653 if (app.info.uid != sr.appInfo.uid
3654 || !processName.equals(sr.processName)) {
3655 continue;
3656 }
3657
3658 mPendingServices.remove(i);
3659 i--;
3660 realStartServiceLocked(sr, app);
3661 didSomething = true;
3662 }
3663 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003664 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 + sr.shortName, e);
3666 badApp = true;
3667 }
3668 }
3669
3670 // Check if the next broadcast receiver is in this process...
3671 BroadcastRecord br = mPendingBroadcast;
3672 if (!badApp && br != null && br.curApp == app) {
3673 try {
3674 mPendingBroadcast = null;
3675 processCurBroadcastLocked(br, app);
3676 didSomething = true;
3677 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003678 Slog.w(TAG, "Exception in new application when starting receiver "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 + br.curComponent.flattenToShortString(), e);
3680 badApp = true;
Jeff Brown4d94a762010-09-23 11:33:28 -07003681 logBroadcastReceiverDiscardLocked(br);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003682 finishReceiverLocked(br.receiver, br.resultCode, br.resultData,
3683 br.resultExtras, br.resultAbort, true);
3684 scheduleBroadcastsLocked();
Magnus Edlund7bb25812010-02-24 15:45:06 +01003685 // We need to reset the state if we fails to start the receiver.
3686 br.state = BroadcastRecord.IDLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 }
3688 }
3689
Christopher Tate181fafa2009-05-14 11:12:14 -07003690 // Check whether the next backup agent is in this process...
3691 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.info.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003692 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003693 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003694 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003695 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
3696 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
3697 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07003698 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003699 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003700 e.printStackTrace();
3701 }
3702 }
3703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 if (badApp) {
3705 // todo: Also need to kill application to deal with all
3706 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003707 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 return false;
3709 }
3710
3711 if (!didSomething) {
3712 updateOomAdjLocked();
3713 }
3714
3715 return true;
3716 }
3717
3718 public final void attachApplication(IApplicationThread thread) {
3719 synchronized (this) {
3720 int callingPid = Binder.getCallingPid();
3721 final long origId = Binder.clearCallingIdentity();
3722 attachApplicationLocked(thread, callingPid);
3723 Binder.restoreCallingIdentity(origId);
3724 }
3725 }
3726
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003727 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003729 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
3730 if (stopProfiling) {
3731 synchronized (this) {
3732 if (mProfileProc == r.app) {
3733 if (mProfileFd != null) {
3734 try {
3735 mProfileFd.close();
3736 } catch (IOException e) {
3737 }
3738 clearProfilerLocked();
3739 }
3740 }
3741 }
3742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 Binder.restoreCallingIdentity(origId);
3744 }
3745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003747 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003748 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 mWindowManager.enableScreenAfterBoot();
3750 }
3751
Dianne Hackborn661cd522011-08-22 00:26:20 -07003752 public void showBootMessage(final CharSequence msg, final boolean always) {
3753 mWindowManager.showBootMessage(msg, always);
3754 }
3755
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003756 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003757 IntentFilter pkgFilter = new IntentFilter();
3758 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
3759 pkgFilter.addDataScheme("package");
3760 mContext.registerReceiver(new BroadcastReceiver() {
3761 @Override
3762 public void onReceive(Context context, Intent intent) {
3763 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3764 if (pkgs != null) {
3765 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07003766 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07003767 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07003768 setResultCode(Activity.RESULT_OK);
3769 return;
3770 }
3771 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003772 }
3773 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003774 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003775 }, pkgFilter);
3776
3777 synchronized (this) {
3778 // Ensure that any processes we had put on hold are now started
3779 // up.
3780 final int NP = mProcessesOnHold.size();
3781 if (NP > 0) {
3782 ArrayList<ProcessRecord> procs =
3783 new ArrayList<ProcessRecord>(mProcessesOnHold);
3784 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003785 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
3786 + procs.get(ip));
3787 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003788 }
3789 }
3790
3791 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003792 // Start looking for apps that are abusing wake locks.
3793 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003794 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003795 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07003796 SystemProperties.set("sys.boot_completed", "1");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003797 broadcastIntentLocked(null, null,
3798 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
3799 null, null, 0, null, null,
3800 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
3801 false, false, MY_PID, Process.SYSTEM_UID);
3802 }
3803 }
3804 }
3805
3806 final void ensureBootCompleted() {
3807 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003808 boolean enableScreen;
3809 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003810 booting = mBooting;
3811 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003812 enableScreen = !mBooted;
3813 mBooted = true;
3814 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003815
3816 if (booting) {
3817 finishBooting();
3818 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003819
3820 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003821 enableScreenAfterBoot();
3822 }
3823 }
3824
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003825 public final void activityPaused(IBinder token) {
3826 final long origId = Binder.clearCallingIdentity();
3827 mMainStack.activityPaused(token, false);
3828 Binder.restoreCallingIdentity(origId);
3829 }
3830
3831 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
3832 CharSequence description) {
3833 if (localLOGV) Slog.v(
3834 TAG, "Activity stopped: token=" + token);
3835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 // Refuse possible leaked file descriptors
3837 if (icicle != null && icicle.hasFileDescriptors()) {
3838 throw new IllegalArgumentException("File descriptors passed in Bundle");
3839 }
3840
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003841 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842
3843 final long origId = Binder.clearCallingIdentity();
3844
3845 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003846 r = mMainStack.isInStackLocked(token);
3847 if (r != null) {
3848 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 }
3850 }
3851
3852 if (r != null) {
3853 sendPendingThumbnail(r, null, null, null, false);
3854 }
3855
3856 trimApplications();
3857
3858 Binder.restoreCallingIdentity(origId);
3859 }
3860
3861 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003862 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003863 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 }
3865
3866 public String getCallingPackage(IBinder token) {
3867 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003868 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07003869 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 }
3871 }
3872
3873 public ComponentName getCallingActivity(IBinder token) {
3874 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003875 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 return r != null ? r.intent.getComponent() : null;
3877 }
3878 }
3879
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003880 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003881 ActivityRecord r = mMainStack.isInStackLocked(token);
3882 if (r == null) {
3883 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003885 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 }
3887
3888 public ComponentName getActivityClassForToken(IBinder token) {
3889 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003890 ActivityRecord r = mMainStack.isInStackLocked(token);
3891 if (r == null) {
3892 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003894 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 }
3896 }
3897
3898 public String getPackageForToken(IBinder token) {
3899 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003900 ActivityRecord r = mMainStack.isInStackLocked(token);
3901 if (r == null) {
3902 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003904 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 }
3906 }
3907
3908 public IIntentSender getIntentSender(int type,
3909 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003910 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003912 if (intents != null) {
3913 if (intents.length < 1) {
3914 throw new IllegalArgumentException("Intents array length must be >= 1");
3915 }
3916 for (int i=0; i<intents.length; i++) {
3917 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07003918 if (intent != null) {
3919 if (intent.hasFileDescriptors()) {
3920 throw new IllegalArgumentException("File descriptors passed in Intent");
3921 }
3922 if (type == INTENT_SENDER_BROADCAST &&
3923 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
3924 throw new IllegalArgumentException(
3925 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
3926 }
3927 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003928 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003929 }
3930 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003931 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003932 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003933 }
3934 }
3935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 synchronized(this) {
3937 int callingUid = Binder.getCallingUid();
3938 try {
Jeff Brown10e89712011-07-08 18:52:57 -07003939 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003940 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 .getPackageUid(packageName);
3942 if (uid != Binder.getCallingUid()) {
3943 String msg = "Permission Denial: getIntentSender() from pid="
3944 + Binder.getCallingPid()
3945 + ", uid=" + Binder.getCallingUid()
3946 + ", (need uid=" + uid + ")"
3947 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003948 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 throw new SecurityException(msg);
3950 }
3951 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003952
3953 return getIntentSenderLocked(type, packageName, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003954 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 } catch (RemoteException e) {
3957 throw new SecurityException(e);
3958 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003959 }
3960 }
3961
3962 IIntentSender getIntentSenderLocked(int type,
3963 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003964 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003965 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003966 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003967 activity = mMainStack.isInStackLocked(token);
3968 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07003969 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003971 if (activity.finishing) {
3972 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003974 }
3975
3976 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
3977 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
3978 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
3979 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
3980 |PendingIntent.FLAG_UPDATE_CURRENT);
3981
3982 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
3983 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003984 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003985 WeakReference<PendingIntentRecord> ref;
3986 ref = mIntentSenderRecords.get(key);
3987 PendingIntentRecord rec = ref != null ? ref.get() : null;
3988 if (rec != null) {
3989 if (!cancelCurrent) {
3990 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003991 if (rec.key.requestIntent != null) {
3992 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
3993 }
3994 if (intents != null) {
3995 intents[intents.length-1] = rec.key.requestIntent;
3996 rec.key.allIntents = intents;
3997 rec.key.allResolvedTypes = resolvedTypes;
3998 } else {
3999 rec.key.allIntents = null;
4000 rec.key.allResolvedTypes = null;
4001 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 return rec;
4004 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004005 rec.canceled = true;
4006 mIntentSenderRecords.remove(key);
4007 }
4008 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 return rec;
4010 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004011 rec = new PendingIntentRecord(this, key, callingUid);
4012 mIntentSenderRecords.put(key, rec.ref);
4013 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
4014 if (activity.pendingResults == null) {
4015 activity.pendingResults
4016 = new HashSet<WeakReference<PendingIntentRecord>>();
4017 }
4018 activity.pendingResults.add(rec.ref);
4019 }
4020 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 }
4022
4023 public void cancelIntentSender(IIntentSender sender) {
4024 if (!(sender instanceof PendingIntentRecord)) {
4025 return;
4026 }
4027 synchronized(this) {
4028 PendingIntentRecord rec = (PendingIntentRecord)sender;
4029 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004030 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 .getPackageUid(rec.key.packageName);
4032 if (uid != Binder.getCallingUid()) {
4033 String msg = "Permission Denial: cancelIntentSender() from pid="
4034 + Binder.getCallingPid()
4035 + ", uid=" + Binder.getCallingUid()
4036 + " is not allowed to cancel packges "
4037 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004038 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 throw new SecurityException(msg);
4040 }
4041 } catch (RemoteException e) {
4042 throw new SecurityException(e);
4043 }
4044 cancelIntentSenderLocked(rec, true);
4045 }
4046 }
4047
4048 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4049 rec.canceled = true;
4050 mIntentSenderRecords.remove(rec.key);
4051 if (cleanActivity && rec.key.activity != null) {
4052 rec.key.activity.pendingResults.remove(rec.ref);
4053 }
4054 }
4055
4056 public String getPackageForIntentSender(IIntentSender pendingResult) {
4057 if (!(pendingResult instanceof PendingIntentRecord)) {
4058 return null;
4059 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004060 try {
4061 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4062 return res.key.packageName;
4063 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 }
4065 return null;
4066 }
4067
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004068 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4069 if (!(pendingResult instanceof PendingIntentRecord)) {
4070 return false;
4071 }
4072 try {
4073 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4074 if (res.key.allIntents == null) {
4075 return false;
4076 }
4077 for (int i=0; i<res.key.allIntents.length; i++) {
4078 Intent intent = res.key.allIntents[i];
4079 if (intent.getPackage() != null && intent.getComponent() != null) {
4080 return false;
4081 }
4082 }
4083 return true;
4084 } catch (ClassCastException e) {
4085 }
4086 return false;
4087 }
4088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 public void setProcessLimit(int max) {
4090 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4091 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004092 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004093 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004094 mProcessLimitOverride = max;
4095 }
4096 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 }
4098
4099 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004100 synchronized (this) {
4101 return mProcessLimitOverride;
4102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 }
4104
4105 void foregroundTokenDied(ForegroundToken token) {
4106 synchronized (ActivityManagerService.this) {
4107 synchronized (mPidsSelfLocked) {
4108 ForegroundToken cur
4109 = mForegroundProcesses.get(token.pid);
4110 if (cur != token) {
4111 return;
4112 }
4113 mForegroundProcesses.remove(token.pid);
4114 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4115 if (pr == null) {
4116 return;
4117 }
4118 pr.forcingToForeground = null;
4119 pr.foregroundServices = false;
4120 }
4121 updateOomAdjLocked();
4122 }
4123 }
4124
4125 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4126 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4127 "setProcessForeground()");
4128 synchronized(this) {
4129 boolean changed = false;
4130
4131 synchronized (mPidsSelfLocked) {
4132 ProcessRecord pr = mPidsSelfLocked.get(pid);
4133 if (pr == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004134 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 return;
4136 }
4137 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4138 if (oldToken != null) {
4139 oldToken.token.unlinkToDeath(oldToken, 0);
4140 mForegroundProcesses.remove(pid);
4141 pr.forcingToForeground = null;
4142 changed = true;
4143 }
4144 if (isForeground && token != null) {
4145 ForegroundToken newToken = new ForegroundToken() {
4146 public void binderDied() {
4147 foregroundTokenDied(this);
4148 }
4149 };
4150 newToken.pid = pid;
4151 newToken.token = token;
4152 try {
4153 token.linkToDeath(newToken, 0);
4154 mForegroundProcesses.put(pid, newToken);
4155 pr.forcingToForeground = token;
4156 changed = true;
4157 } catch (RemoteException e) {
4158 // If the process died while doing this, we will later
4159 // do the cleanup with the process death link.
4160 }
4161 }
4162 }
4163
4164 if (changed) {
4165 updateOomAdjLocked();
4166 }
4167 }
4168 }
4169
4170 // =========================================================
4171 // PERMISSIONS
4172 // =========================================================
4173
4174 static class PermissionController extends IPermissionController.Stub {
4175 ActivityManagerService mActivityManagerService;
4176 PermissionController(ActivityManagerService activityManagerService) {
4177 mActivityManagerService = activityManagerService;
4178 }
4179
4180 public boolean checkPermission(String permission, int pid, int uid) {
4181 return mActivityManagerService.checkPermission(permission, pid,
4182 uid) == PackageManager.PERMISSION_GRANTED;
4183 }
4184 }
4185
4186 /**
4187 * This can be called with or without the global lock held.
4188 */
4189 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004190 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 // We might be performing an operation on behalf of an indirect binder
4192 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4193 // client identity accordingly before proceeding.
4194 Identity tlsIdentity = sCallerIdentity.get();
4195 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004196 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004197 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4198 uid = tlsIdentity.uid;
4199 pid = tlsIdentity.pid;
4200 }
4201
4202 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004203 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 return PackageManager.PERMISSION_GRANTED;
4205 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004206 // If there is a uid that owns whatever is being accessed, it has
4207 // blanket access to it regardless of the permissions it requires.
4208 if (owningUid >= 0 && uid == owningUid) {
4209 return PackageManager.PERMISSION_GRANTED;
4210 }
4211 // If the target is not exported, then nobody else can get to it.
4212 if (!exported) {
4213 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 return PackageManager.PERMISSION_DENIED;
4215 }
4216 if (permission == null) {
4217 return PackageManager.PERMISSION_GRANTED;
4218 }
4219 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004220 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 .checkUidPermission(permission, uid);
4222 } catch (RemoteException e) {
4223 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004224 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 }
4226 return PackageManager.PERMISSION_DENIED;
4227 }
4228
4229 /**
4230 * As the only public entry point for permissions checking, this method
4231 * can enforce the semantic that requesting a check on a null global
4232 * permission is automatically denied. (Internally a null permission
4233 * string is used when calling {@link #checkComponentPermission} in cases
4234 * when only uid-based security is needed.)
4235 *
4236 * This can be called with or without the global lock held.
4237 */
4238 public int checkPermission(String permission, int pid, int uid) {
4239 if (permission == null) {
4240 return PackageManager.PERMISSION_DENIED;
4241 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004242 return checkComponentPermission(permission, pid, uid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 }
4244
4245 /**
4246 * Binder IPC calls go through the public entry point.
4247 * This can be called with or without the global lock held.
4248 */
4249 int checkCallingPermission(String permission) {
4250 return checkPermission(permission,
4251 Binder.getCallingPid(),
4252 Binder.getCallingUid());
4253 }
4254
4255 /**
4256 * This can be called with or without the global lock held.
4257 */
4258 void enforceCallingPermission(String permission, String func) {
4259 if (checkCallingPermission(permission)
4260 == PackageManager.PERMISSION_GRANTED) {
4261 return;
4262 }
4263
4264 String msg = "Permission Denial: " + func + " from pid="
4265 + Binder.getCallingPid()
4266 + ", uid=" + Binder.getCallingUid()
4267 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004268 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 throw new SecurityException(msg);
4270 }
4271
4272 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07004273 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
4274 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4275 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
4276 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4277 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004279 // Is the component private from the target uid?
4280 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
4281
4282 // Acceptable if the there is no read permission needed from the
4283 // target or the target is holding the read permission.
4284 if (!readPerm) {
4285 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004286 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004287 == PackageManager.PERMISSION_GRANTED)) {
4288 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 }
4290 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004291
4292 // Acceptable if the there is no write permission needed from the
4293 // target or the target is holding the read permission.
4294 if (!writePerm) {
4295 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004297 == PackageManager.PERMISSION_GRANTED)) {
4298 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 }
4300 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004301
4302 // Acceptable if there is a path permission matching the URI that
4303 // the target holds the permission on.
4304 PathPermission[] pps = pi.pathPermissions;
4305 if (pps != null && (!readPerm || !writePerm)) {
4306 final String path = uri.getPath();
4307 int i = pps.length;
4308 while (i > 0 && (!readPerm || !writePerm)) {
4309 i--;
4310 PathPermission pp = pps[i];
4311 if (!readPerm) {
4312 final String pprperm = pp.getReadPermission();
4313 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4314 + pprperm + " for " + pp.getPath()
4315 + ": match=" + pp.match(path)
4316 + " check=" + pm.checkUidPermission(pprperm, uid));
4317 if (pprperm != null && pp.match(path) &&
4318 (pm.checkUidPermission(pprperm, uid)
4319 == PackageManager.PERMISSION_GRANTED)) {
4320 readPerm = true;
4321 }
4322 }
4323 if (!writePerm) {
4324 final String ppwperm = pp.getWritePermission();
4325 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4326 + ppwperm + " for " + pp.getPath()
4327 + ": match=" + pp.match(path)
4328 + " check=" + pm.checkUidPermission(ppwperm, uid));
4329 if (ppwperm != null && pp.match(path) &&
4330 (pm.checkUidPermission(ppwperm, uid)
4331 == PackageManager.PERMISSION_GRANTED)) {
4332 writePerm = true;
4333 }
4334 }
4335 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 } catch (RemoteException e) {
4338 return false;
4339 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004340
4341 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 }
4343
4344 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4345 int modeFlags) {
4346 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004347 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004348 return true;
4349 }
4350 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4351 if (perms == null) return false;
4352 UriPermission perm = perms.get(uri);
4353 if (perm == null) return false;
4354 return (modeFlags&perm.modeFlags) == modeFlags;
4355 }
4356
4357 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
4358 // Another redirected-binder-call permissions check as in
4359 // {@link checkComponentPermission}.
4360 Identity tlsIdentity = sCallerIdentity.get();
4361 if (tlsIdentity != null) {
4362 uid = tlsIdentity.uid;
4363 pid = tlsIdentity.pid;
4364 }
4365
4366 // Our own process gets to do everything.
4367 if (pid == MY_PID) {
4368 return PackageManager.PERMISSION_GRANTED;
4369 }
4370 synchronized(this) {
4371 return checkUriPermissionLocked(uri, uid, modeFlags)
4372 ? PackageManager.PERMISSION_GRANTED
4373 : PackageManager.PERMISSION_DENIED;
4374 }
4375 }
4376
Dianne Hackborn39792d22010-08-19 18:01:52 -07004377 /**
4378 * Check if the targetPkg can be granted permission to access uri by
4379 * the callingUid using the given modeFlags. Throws a security exception
4380 * if callingUid is not allowed to do this. Returns the uid of the target
4381 * if the URI permission grant should be performed; returns -1 if it is not
4382 * needed (for example targetPkg already has permission to access the URI).
4383 */
4384 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
4385 Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4387 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4388 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004389 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 }
4391
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004392 if (targetPkg != null) {
4393 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4394 "Checking grant " + targetPkg + " permission to " + uri);
4395 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004396
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004397 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398
4399 // If this is not a content: uri, we can't do anything with it.
4400 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004401 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004402 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004403 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004404 }
4405
4406 String name = uri.getAuthority();
4407 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004408 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409 if (cpr != null) {
4410 pi = cpr.info;
4411 } else {
4412 try {
4413 pi = pm.resolveContentProvider(name,
4414 PackageManager.GET_URI_PERMISSION_PATTERNS);
4415 } catch (RemoteException ex) {
4416 }
4417 }
4418 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004419 Slog.w(TAG, "No content provider found for: " + name);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004420 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004421 }
4422
4423 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004424 if (targetPkg != null) {
4425 try {
4426 targetUid = pm.getPackageUid(targetPkg);
4427 if (targetUid < 0) {
4428 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4429 "Can't grant URI permission no uid for: " + targetPkg);
4430 return -1;
4431 }
4432 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004433 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004434 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004435 } else {
4436 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004437 }
4438
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004439 if (targetUid >= 0) {
4440 // First... does the target actually need this permission?
4441 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4442 // No need to grant the target this permission.
4443 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4444 "Target " + targetPkg + " already has full permission to " + uri);
4445 return -1;
4446 }
4447 } else {
4448 // First... there is no target package, so can anyone access it?
4449 boolean allowed = pi.exported;
4450 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4451 if (pi.readPermission != null) {
4452 allowed = false;
4453 }
4454 }
4455 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4456 if (pi.writePermission != null) {
4457 allowed = false;
4458 }
4459 }
4460 if (allowed) {
4461 return -1;
4462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 }
4464
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004465 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 if (!pi.grantUriPermissions) {
4467 throw new SecurityException("Provider " + pi.packageName
4468 + "/" + pi.name
4469 + " does not allow granting of Uri permissions (uri "
4470 + uri + ")");
4471 }
4472 if (pi.uriPermissionPatterns != null) {
4473 final int N = pi.uriPermissionPatterns.length;
4474 boolean allowed = false;
4475 for (int i=0; i<N; i++) {
4476 if (pi.uriPermissionPatterns[i] != null
4477 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4478 allowed = true;
4479 break;
4480 }
4481 }
4482 if (!allowed) {
4483 throw new SecurityException("Provider " + pi.packageName
4484 + "/" + pi.name
4485 + " does not allow granting of permission to path of Uri "
4486 + uri);
4487 }
4488 }
4489
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004490 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004492 if (callingUid != Process.myUid()) {
4493 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4494 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4495 throw new SecurityException("Uid " + callingUid
4496 + " does not have permission to uri " + uri);
4497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 }
4499 }
4500
Dianne Hackborn39792d22010-08-19 18:01:52 -07004501 return targetUid;
4502 }
4503
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004504 public int checkGrantUriPermission(int callingUid, String targetPkg,
4505 Uri uri, int modeFlags) {
4506 synchronized(this) {
4507 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4508 }
4509 }
4510
Dianne Hackborn39792d22010-08-19 18:01:52 -07004511 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4512 Uri uri, int modeFlags, UriPermissionOwner owner) {
4513 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4514 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4515 if (modeFlags == 0) {
4516 return;
4517 }
4518
4519 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 // to the uri, and the target doesn't. Let's now give this to
4521 // the target.
4522
Joe Onorato8a9b2202010-02-26 18:56:32 -08004523 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004524 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526 HashMap<Uri, UriPermission> targetUris
4527 = mGrantedUriPermissions.get(targetUid);
4528 if (targetUris == null) {
4529 targetUris = new HashMap<Uri, UriPermission>();
4530 mGrantedUriPermissions.put(targetUid, targetUris);
4531 }
4532
4533 UriPermission perm = targetUris.get(uri);
4534 if (perm == null) {
4535 perm = new UriPermission(targetUid, uri);
4536 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004540 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004541 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004542 } else {
4543 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4544 perm.readOwners.add(owner);
4545 owner.addReadPermission(perm);
4546 }
4547 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4548 perm.writeOwners.add(owner);
4549 owner.addWritePermission(perm);
4550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 }
4552 }
4553
Dianne Hackborn39792d22010-08-19 18:01:52 -07004554 void grantUriPermissionLocked(int callingUid,
4555 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004556 if (targetPkg == null) {
4557 throw new NullPointerException("targetPkg");
4558 }
4559
Dianne Hackborn39792d22010-08-19 18:01:52 -07004560 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4561 if (targetUid < 0) {
4562 return;
4563 }
4564
4565 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4566 }
4567
4568 /**
4569 * Like checkGrantUriPermissionLocked, but takes an Intent.
4570 */
4571 int checkGrantUriPermissionFromIntentLocked(int callingUid,
4572 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004573 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004574 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004575 + " from " + intent + "; flags=0x"
4576 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4577
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004578 if (targetPkg == null) {
4579 throw new NullPointerException("targetPkg");
4580 }
4581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004583 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 }
4585 Uri data = intent.getData();
4586 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004587 return -1;
4588 }
4589 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4590 intent.getFlags());
4591 }
4592
4593 /**
4594 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4595 */
4596 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
4597 String targetPkg, Intent intent, UriPermissionOwner owner) {
4598 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
4599 intent.getFlags(), owner);
4600 }
4601
4602 void grantUriPermissionFromIntentLocked(int callingUid,
4603 String targetPkg, Intent intent, UriPermissionOwner owner) {
4604 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
4605 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004606 return;
4607 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004608
4609 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004610 }
4611
4612 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4613 Uri uri, int modeFlags) {
4614 synchronized(this) {
4615 final ProcessRecord r = getRecordForAppLocked(caller);
4616 if (r == null) {
4617 throw new SecurityException("Unable to find app for caller "
4618 + caller
4619 + " when granting permission to uri " + uri);
4620 }
4621 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004622 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 }
4624 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004625 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 }
4627
4628 grantUriPermissionLocked(r.info.uid, targetPkg, uri, modeFlags,
4629 null);
4630 }
4631 }
4632
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004633 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4635 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4636 HashMap<Uri, UriPermission> perms
4637 = mGrantedUriPermissions.get(perm.uid);
4638 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004639 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004640 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 perms.remove(perm.uri);
4642 if (perms.size() == 0) {
4643 mGrantedUriPermissions.remove(perm.uid);
4644 }
4645 }
4646 }
4647 }
4648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 private void revokeUriPermissionLocked(int callingUid, Uri uri,
4650 int modeFlags) {
4651 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4652 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4653 if (modeFlags == 0) {
4654 return;
4655 }
4656
Joe Onorato8a9b2202010-02-26 18:56:32 -08004657 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004658 "Revoking all granted permissions to " + uri);
4659
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004660 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004661
4662 final String authority = uri.getAuthority();
4663 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004664 ContentProviderRecord cpr = mProvidersByName.get(authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 if (cpr != null) {
4666 pi = cpr.info;
4667 } else {
4668 try {
4669 pi = pm.resolveContentProvider(authority,
4670 PackageManager.GET_URI_PERMISSION_PATTERNS);
4671 } catch (RemoteException ex) {
4672 }
4673 }
4674 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004675 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676 return;
4677 }
4678
4679 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07004680 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004681 // Right now, if you are not the original owner of the permission,
4682 // you are not allowed to revoke it.
4683 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4684 throw new SecurityException("Uid " + callingUid
4685 + " does not have permission to uri " + uri);
4686 //}
4687 }
4688
4689 // Go through all of the permissions and remove any that match.
4690 final List<String> SEGMENTS = uri.getPathSegments();
4691 if (SEGMENTS != null) {
4692 final int NS = SEGMENTS.size();
4693 int N = mGrantedUriPermissions.size();
4694 for (int i=0; i<N; i++) {
4695 HashMap<Uri, UriPermission> perms
4696 = mGrantedUriPermissions.valueAt(i);
4697 Iterator<UriPermission> it = perms.values().iterator();
4698 toploop:
4699 while (it.hasNext()) {
4700 UriPermission perm = it.next();
4701 Uri targetUri = perm.uri;
4702 if (!authority.equals(targetUri.getAuthority())) {
4703 continue;
4704 }
4705 List<String> targetSegments = targetUri.getPathSegments();
4706 if (targetSegments == null) {
4707 continue;
4708 }
4709 if (targetSegments.size() < NS) {
4710 continue;
4711 }
4712 for (int j=0; j<NS; j++) {
4713 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
4714 continue toploop;
4715 }
4716 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004717 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004718 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004719 perm.clearModes(modeFlags);
4720 if (perm.modeFlags == 0) {
4721 it.remove();
4722 }
4723 }
4724 if (perms.size() == 0) {
4725 mGrantedUriPermissions.remove(
4726 mGrantedUriPermissions.keyAt(i));
4727 N--;
4728 i--;
4729 }
4730 }
4731 }
4732 }
4733
4734 public void revokeUriPermission(IApplicationThread caller, Uri uri,
4735 int modeFlags) {
4736 synchronized(this) {
4737 final ProcessRecord r = getRecordForAppLocked(caller);
4738 if (r == null) {
4739 throw new SecurityException("Unable to find app for caller "
4740 + caller
4741 + " when revoking permission to uri " + uri);
4742 }
4743 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004744 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 return;
4746 }
4747
4748 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4749 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4750 if (modeFlags == 0) {
4751 return;
4752 }
4753
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004754 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004755
4756 final String authority = uri.getAuthority();
4757 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004758 ContentProviderRecord cpr = mProvidersByName.get(authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004759 if (cpr != null) {
4760 pi = cpr.info;
4761 } else {
4762 try {
4763 pi = pm.resolveContentProvider(authority,
4764 PackageManager.GET_URI_PERMISSION_PATTERNS);
4765 } catch (RemoteException ex) {
4766 }
4767 }
4768 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004769 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004770 return;
4771 }
4772
4773 revokeUriPermissionLocked(r.info.uid, uri, modeFlags);
4774 }
4775 }
4776
Dianne Hackborn7e269642010-08-25 19:50:20 -07004777 @Override
4778 public IBinder newUriPermissionOwner(String name) {
4779 synchronized(this) {
4780 UriPermissionOwner owner = new UriPermissionOwner(this, name);
4781 return owner.getExternalTokenLocked();
4782 }
4783 }
4784
4785 @Override
4786 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
4787 Uri uri, int modeFlags) {
4788 synchronized(this) {
4789 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
4790 if (owner == null) {
4791 throw new IllegalArgumentException("Unknown owner: " + token);
4792 }
4793 if (fromUid != Binder.getCallingUid()) {
4794 if (Binder.getCallingUid() != Process.myUid()) {
4795 // Only system code can grant URI permissions on behalf
4796 // of other users.
4797 throw new SecurityException("nice try");
4798 }
4799 }
4800 if (targetPkg == null) {
4801 throw new IllegalArgumentException("null target");
4802 }
4803 if (uri == null) {
4804 throw new IllegalArgumentException("null uri");
4805 }
4806
4807 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
4808 }
4809 }
4810
4811 @Override
4812 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
4813 synchronized(this) {
4814 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
4815 if (owner == null) {
4816 throw new IllegalArgumentException("Unknown owner: " + token);
4817 }
4818
4819 if (uri == null) {
4820 owner.removeUriPermissionsLocked(mode);
4821 } else {
4822 owner.removeUriPermissionLocked(uri, mode);
4823 }
4824 }
4825 }
4826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004827 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
4828 synchronized (this) {
4829 ProcessRecord app =
4830 who != null ? getRecordForAppLocked(who) : null;
4831 if (app == null) return;
4832
4833 Message msg = Message.obtain();
4834 msg.what = WAIT_FOR_DEBUGGER_MSG;
4835 msg.obj = app;
4836 msg.arg1 = waiting ? 1 : 0;
4837 mHandler.sendMessage(msg);
4838 }
4839 }
4840
4841 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004842 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
4843 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004844 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07004845 outInfo.threshold = homeAppMem;
4846 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
4847 outInfo.hiddenAppThreshold = hiddenAppMem;
4848 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
4849 ProcessList.SECONDARY_SERVER_ADJ);
4850 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
4851 ProcessList.VISIBLE_APP_ADJ);
4852 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
4853 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004854 }
4855
4856 // =========================================================
4857 // TASK MANAGEMENT
4858 // =========================================================
4859
4860 public List getTasks(int maxNum, int flags,
4861 IThumbnailReceiver receiver) {
4862 ArrayList list = new ArrayList();
4863
4864 PendingThumbnailsRecord pending = null;
4865 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004866 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867
4868 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004869 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
4871 + ", receiver=" + receiver);
4872
4873 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
4874 != PackageManager.PERMISSION_GRANTED) {
4875 if (receiver != null) {
4876 // If the caller wants to wait for pending thumbnails,
4877 // it ain't gonna get them.
4878 try {
4879 receiver.finished();
4880 } catch (RemoteException ex) {
4881 }
4882 }
4883 String msg = "Permission Denial: getTasks() from pid="
4884 + Binder.getCallingPid()
4885 + ", uid=" + Binder.getCallingUid()
4886 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004887 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004888 throw new SecurityException(msg);
4889 }
4890
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004891 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004892 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004893 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004894 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 TaskRecord curTask = null;
4896 int numActivities = 0;
4897 int numRunning = 0;
4898 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004899 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004900 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004901 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902
4903 // Initialize state for next task if needed.
4904 if (top == null ||
4905 (top.state == ActivityState.INITIALIZING
4906 && top.task == r.task)) {
4907 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004908 curTask = r.task;
4909 numActivities = numRunning = 0;
4910 }
4911
4912 // Add 'r' into the current task.
4913 numActivities++;
4914 if (r.app != null && r.app.thread != null) {
4915 numRunning++;
4916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004917
Joe Onorato8a9b2202010-02-26 18:56:32 -08004918 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004919 TAG, r.intent.getComponent().flattenToShortString()
4920 + ": task=" + r.task);
4921
4922 // If the next one is a different task, generate a new
4923 // TaskInfo entry for what we have.
4924 if (next == null || next.task != curTask) {
4925 ActivityManager.RunningTaskInfo ci
4926 = new ActivityManager.RunningTaskInfo();
4927 ci.id = curTask.taskId;
4928 ci.baseActivity = r.intent.getComponent();
4929 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07004930 if (top.thumbHolder != null) {
4931 ci.description = top.thumbHolder.lastDescription;
4932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004933 ci.numActivities = numActivities;
4934 ci.numRunning = numRunning;
4935 //System.out.println(
4936 // "#" + maxNum + ": " + " descr=" + ci.description);
4937 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004938 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 TAG, "State=" + top.state + "Idle=" + top.idle
4940 + " app=" + top.app
4941 + " thr=" + (top.app != null ? top.app.thread : null));
4942 if (top.state == ActivityState.RESUMED
4943 || top.state == ActivityState.PAUSING) {
4944 if (top.idle && top.app != null
4945 && top.app.thread != null) {
4946 topRecord = top;
4947 topThumbnail = top.app.thread;
4948 } else {
4949 top.thumbnailNeeded = true;
4950 }
4951 }
4952 if (pending == null) {
4953 pending = new PendingThumbnailsRecord(receiver);
4954 }
4955 pending.pendingRecords.add(top);
4956 }
4957 list.add(ci);
4958 maxNum--;
4959 top = null;
4960 }
4961 }
4962
4963 if (pending != null) {
4964 mPendingThumbnails.add(pending);
4965 }
4966 }
4967
Joe Onorato8a9b2202010-02-26 18:56:32 -08004968 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969
4970 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004971 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004972 try {
4973 topThumbnail.requestThumbnail(topRecord);
4974 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004975 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 sendPendingThumbnail(null, topRecord, null, null, true);
4977 }
4978 }
4979
4980 if (pending == null && receiver != null) {
4981 // In this case all thumbnails were available and the client
4982 // is being asked to be told when the remaining ones come in...
4983 // which is unusually, since the top-most currently running
4984 // activity should never have a canned thumbnail! Oh well.
4985 try {
4986 receiver.finished();
4987 } catch (RemoteException ex) {
4988 }
4989 }
4990
4991 return list;
4992 }
4993
4994 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
4995 int flags) {
4996 synchronized (this) {
4997 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
4998 "getRecentTasks()");
4999
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005000 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005002 final int N = mRecentTasks.size();
5003 ArrayList<ActivityManager.RecentTaskInfo> res
5004 = new ArrayList<ActivityManager.RecentTaskInfo>(
5005 maxNum < N ? maxNum : N);
5006 for (int i=0; i<N && maxNum > 0; i++) {
5007 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackborn905577f2011-09-07 18:31:28 -07005008 // Return the entry if desired by the caller. We always return
5009 // the first entry, because callers always expect this to be the
5010 // forground app. We may filter others if the caller has
5011 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5012 // we should exclude the entry.
5013 if (i == 0
5014 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005015 || (tr.intent == null)
5016 || ((tr.intent.getFlags()
5017 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5018 ActivityManager.RecentTaskInfo rti
5019 = new ActivityManager.RecentTaskInfo();
5020 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005021 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005022 rti.baseIntent = new Intent(
5023 tr.intent != null ? tr.intent : tr.affinityIntent);
5024 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005025 rti.description = tr.lastDescription;
5026
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005027 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5028 // Check whether this activity is currently available.
5029 try {
5030 if (rti.origActivity != null) {
5031 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5032 continue;
5033 }
5034 } else if (rti.baseIntent != null) {
5035 if (pm.queryIntentActivities(rti.baseIntent,
5036 null, 0) == null) {
5037 continue;
5038 }
5039 }
5040 } catch (RemoteException e) {
5041 // Will never happen.
5042 }
5043 }
5044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005045 res.add(rti);
5046 maxNum--;
5047 }
5048 }
5049 return res;
5050 }
5051 }
5052
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005053 private TaskRecord taskForIdLocked(int id) {
5054 final int N = mRecentTasks.size();
5055 for (int i=0; i<N; i++) {
5056 TaskRecord tr = mRecentTasks.get(i);
5057 if (tr.taskId == id) {
5058 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005059 }
5060 }
5061 return null;
5062 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005063
5064 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5065 synchronized (this) {
5066 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5067 "getTaskThumbnails()");
5068 TaskRecord tr = taskForIdLocked(id);
5069 if (tr != null) {
5070 return mMainStack.getTaskThumbnailsLocked(tr);
5071 }
5072 }
5073 return null;
5074 }
5075
5076 public boolean removeSubTask(int taskId, int subTaskIndex) {
5077 synchronized (this) {
5078 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5079 "removeSubTask()");
5080 long ident = Binder.clearCallingIdentity();
5081 try {
5082 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
5083 } finally {
5084 Binder.restoreCallingIdentity(ident);
5085 }
5086 }
5087 }
5088
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005089 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005090 TaskRecord tr = root.task;
5091 Intent baseIntent = new Intent(
5092 tr.intent != null ? tr.intent : tr.affinityIntent);
5093 ComponentName component = baseIntent.getComponent();
5094 if (component == null) {
5095 Slog.w(TAG, "Now component for base intent of task: " + tr);
5096 return;
5097 }
5098
5099 // Find any running services associated with this app.
5100 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
5101 for (ServiceRecord sr : mServices.values()) {
5102 if (sr.packageName.equals(component.getPackageName())) {
5103 services.add(sr);
5104 }
5105 }
5106
5107 // Take care of any running services associated with the app.
5108 for (int i=0; i<services.size(); i++) {
5109 ServiceRecord sr = services.get(i);
5110 if (sr.startRequested) {
5111 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005112 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005113 stopServiceLocked(sr);
5114 } else {
5115 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
5116 sr.makeNextStartId(), baseIntent, -1));
5117 if (sr.app != null && sr.app.thread != null) {
5118 sendServiceArgsLocked(sr, false);
5119 }
5120 }
5121 }
5122 }
5123
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005124 if (killProcesses) {
5125 // Find any running processes associated with this app.
5126 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5127 SparseArray<ProcessRecord> appProcs
5128 = mProcessNames.getMap().get(component.getPackageName());
5129 if (appProcs != null) {
5130 for (int i=0; i<appProcs.size(); i++) {
5131 procs.add(appProcs.valueAt(i));
5132 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005133 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005134
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005135 // Kill the running processes.
5136 for (int i=0; i<procs.size(); i++) {
5137 ProcessRecord pr = procs.get(i);
5138 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5139 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5140 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5141 pr.processName, pr.setAdj, "remove task");
5142 Process.killProcessQuiet(pr.pid);
5143 } else {
5144 pr.waitingToKill = "remove task";
5145 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005146 }
5147 }
5148 }
5149
5150 public boolean removeTask(int taskId, int flags) {
5151 synchronized (this) {
5152 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5153 "removeTask()");
5154 long ident = Binder.clearCallingIdentity();
5155 try {
5156 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
5157 if (r != null) {
5158 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005159 cleanUpRemovedTaskLocked(r,
5160 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005161 return true;
5162 }
5163 } finally {
5164 Binder.restoreCallingIdentity(ident);
5165 }
5166 }
5167 return false;
5168 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005170 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5171 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005172 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 TaskRecord jt = startTask;
5174
5175 // First look backwards
5176 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005177 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005178 if (r.task != jt) {
5179 jt = r.task;
5180 if (affinity.equals(jt.affinity)) {
5181 return j;
5182 }
5183 }
5184 }
5185
5186 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005187 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005188 jt = startTask;
5189 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005190 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191 if (r.task != jt) {
5192 if (affinity.equals(jt.affinity)) {
5193 return j;
5194 }
5195 jt = r.task;
5196 }
5197 }
5198
5199 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005200 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005201 return N-1;
5202 }
5203
5204 return -1;
5205 }
5206
5207 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005208 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005210 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005211 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5212 "moveTaskToFront()");
5213
5214 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005215 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5216 Binder.getCallingUid(), "Task to front")) {
5217 return;
5218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 final long origId = Binder.clearCallingIdentity();
5220 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005221 TaskRecord tr = taskForIdLocked(task);
5222 if (tr != null) {
5223 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5224 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005226 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5227 // Caller wants the home activity moved with it. To accomplish this,
5228 // we'll just move the home task to the top first.
5229 mMainStack.moveHomeToFrontLocked();
5230 }
5231 mMainStack.moveTaskToFrontLocked(tr, null);
5232 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005233 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005234 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5235 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005236 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005237 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5238 mMainStack.mUserLeaving = true;
5239 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005240 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5241 // Caller wants the home activity moved with it. To accomplish this,
5242 // we'll just move the home task to the top first.
5243 mMainStack.moveHomeToFrontLocked();
5244 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005245 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 return;
5247 }
5248 }
5249 } finally {
5250 Binder.restoreCallingIdentity(origId);
5251 }
5252 }
5253 }
5254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255 public void moveTaskToBack(int task) {
5256 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5257 "moveTaskToBack()");
5258
5259 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005260 if (mMainStack.mResumedActivity != null
5261 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005262 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5263 Binder.getCallingUid(), "Task to back")) {
5264 return;
5265 }
5266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005267 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005268 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 Binder.restoreCallingIdentity(origId);
5270 }
5271 }
5272
5273 /**
5274 * Moves an activity, and all of the other activities within the same task, to the bottom
5275 * of the history stack. The activity's order within the task is unchanged.
5276 *
5277 * @param token A reference to the activity we wish to move
5278 * @param nonRoot If false then this only works if the activity is the root
5279 * of a task; if true it will work for any activity in a task.
5280 * @return Returns true if the move completed, false if not.
5281 */
5282 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
5283 synchronized(this) {
5284 final long origId = Binder.clearCallingIdentity();
5285 int taskId = getTaskForActivityLocked(token, !nonRoot);
5286 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005287 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005288 }
5289 Binder.restoreCallingIdentity(origId);
5290 }
5291 return false;
5292 }
5293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 public void moveTaskBackwards(int task) {
5295 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5296 "moveTaskBackwards()");
5297
5298 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005299 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5300 Binder.getCallingUid(), "Task backwards")) {
5301 return;
5302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 final long origId = Binder.clearCallingIdentity();
5304 moveTaskBackwardsLocked(task);
5305 Binder.restoreCallingIdentity(origId);
5306 }
5307 }
5308
5309 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005310 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005311 }
5312
5313 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5314 synchronized(this) {
5315 return getTaskForActivityLocked(token, onlyRoot);
5316 }
5317 }
5318
5319 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005320 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005321 TaskRecord lastTask = null;
5322 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005323 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005324 if (r == token) {
5325 if (!onlyRoot || lastTask != r.task) {
5326 return r.task.taskId;
5327 }
5328 return -1;
5329 }
5330 lastTask = r.task;
5331 }
5332
5333 return -1;
5334 }
5335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005336 public void finishOtherInstances(IBinder token, ComponentName className) {
5337 synchronized(this) {
5338 final long origId = Binder.clearCallingIdentity();
5339
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005340 int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005341 TaskRecord lastTask = null;
5342 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005343 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005344 if (r.realActivity.equals(className)
5345 && r != token && lastTask != r.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005346 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005347 null, "others")) {
5348 i--;
5349 N--;
5350 }
5351 }
5352 lastTask = r.task;
5353 }
5354
5355 Binder.restoreCallingIdentity(origId);
5356 }
5357 }
5358
5359 // =========================================================
5360 // THUMBNAILS
5361 // =========================================================
5362
5363 public void reportThumbnail(IBinder token,
5364 Bitmap thumbnail, CharSequence description) {
5365 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5366 final long origId = Binder.clearCallingIdentity();
5367 sendPendingThumbnail(null, token, thumbnail, description, true);
5368 Binder.restoreCallingIdentity(origId);
5369 }
5370
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005371 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 Bitmap thumbnail, CharSequence description, boolean always) {
5373 TaskRecord task = null;
5374 ArrayList receivers = null;
5375
5376 //System.out.println("Send pending thumbnail: " + r);
5377
5378 synchronized(this) {
5379 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005380 r = mMainStack.isInStackLocked(token);
5381 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005382 return;
5383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005385 if (thumbnail == null && r.thumbHolder != null) {
5386 thumbnail = r.thumbHolder.lastThumbnail;
5387 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005388 }
5389 if (thumbnail == null && !always) {
5390 // If there is no thumbnail, and this entry is not actually
5391 // going away, then abort for now and pick up the next
5392 // thumbnail we get.
5393 return;
5394 }
5395 task = r.task;
5396
5397 int N = mPendingThumbnails.size();
5398 int i=0;
5399 while (i<N) {
5400 PendingThumbnailsRecord pr =
5401 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5402 //System.out.println("Looking in " + pr.pendingRecords);
5403 if (pr.pendingRecords.remove(r)) {
5404 if (receivers == null) {
5405 receivers = new ArrayList();
5406 }
5407 receivers.add(pr);
5408 if (pr.pendingRecords.size() == 0) {
5409 pr.finished = true;
5410 mPendingThumbnails.remove(i);
5411 N--;
5412 continue;
5413 }
5414 }
5415 i++;
5416 }
5417 }
5418
5419 if (receivers != null) {
5420 final int N = receivers.size();
5421 for (int i=0; i<N; i++) {
5422 try {
5423 PendingThumbnailsRecord pr =
5424 (PendingThumbnailsRecord)receivers.get(i);
5425 pr.receiver.newThumbnail(
5426 task != null ? task.taskId : -1, thumbnail, description);
5427 if (pr.finished) {
5428 pr.receiver.finished();
5429 }
5430 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005431 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 }
5433 }
5434 }
5435 }
5436
5437 // =========================================================
5438 // CONTENT PROVIDERS
5439 // =========================================================
5440
Jeff Brown10e89712011-07-08 18:52:57 -07005441 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5442 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005444 providers = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 queryContentProviders(app.processName, app.info.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005446 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 } catch (RemoteException ex) {
5448 }
5449 if (providers != null) {
5450 final int N = providers.size();
5451 for (int i=0; i<N; i++) {
5452 ProviderInfo cpi =
5453 (ProviderInfo)providers.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005454 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
5455 ContentProviderRecord cpr = mProvidersByClass.get(comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456 if (cpr == null) {
5457 cpr = new ContentProviderRecord(cpi, app.info);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005458 mProvidersByClass.put(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 }
5460 app.pubProviders.put(cpi.name, cpr);
5461 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005462 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 }
5464 }
5465 return providers;
5466 }
5467
5468 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005469 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
5471 final int callingUid = (r != null) ? r.info.uid : Binder.getCallingUid();
5472 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005473 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005474 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 return null;
5476 }
5477 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005478 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 == PackageManager.PERMISSION_GRANTED) {
5480 return null;
5481 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005482
5483 PathPermission[] pps = cpi.pathPermissions;
5484 if (pps != null) {
5485 int i = pps.length;
5486 while (i > 0) {
5487 i--;
5488 PathPermission pp = pps[i];
5489 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005490 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005491 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005492 return null;
5493 }
5494 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005495 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005496 == PackageManager.PERMISSION_GRANTED) {
5497 return null;
5498 }
5499 }
5500 }
5501
Dianne Hackbornb424b632010-08-18 15:59:05 -07005502 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5503 if (perms != null) {
5504 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5505 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5506 return null;
5507 }
5508 }
5509 }
5510
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005511 String msg;
5512 if (!cpi.exported) {
5513 msg = "Permission Denial: opening provider " + cpi.name
5514 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5515 + ", uid=" + callingUid + ") that is not exported from uid "
5516 + cpi.applicationInfo.uid;
5517 } else {
5518 msg = "Permission Denial: opening provider " + cpi.name
5519 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5520 + ", uid=" + callingUid + ") requires "
5521 + cpi.readPermission + " or " + cpi.writePermission;
5522 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005523 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 return msg;
5525 }
5526
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005527 boolean incProviderCount(ProcessRecord r, ContentProviderRecord cpr) {
5528 if (r != null) {
5529 Integer cnt = r.conProviders.get(cpr);
5530 if (DEBUG_PROVIDER) Slog.v(TAG,
5531 "Adding provider requested by "
5532 + r.processName + " from process "
5533 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5534 + " cnt=" + (cnt == null ? 1 : cnt));
5535 if (cnt == null) {
5536 cpr.clients.add(r);
5537 r.conProviders.put(cpr, new Integer(1));
5538 return true;
5539 } else {
5540 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5541 }
5542 } else {
5543 cpr.externals++;
5544 }
5545 return false;
5546 }
5547
5548 boolean decProviderCount(ProcessRecord r, ContentProviderRecord cpr) {
5549 if (r != null) {
5550 Integer cnt = r.conProviders.get(cpr);
5551 if (DEBUG_PROVIDER) Slog.v(TAG,
5552 "Removing provider requested by "
5553 + r.processName + " from process "
5554 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5555 + " cnt=" + cnt);
5556 if (cnt == null || cnt.intValue() <= 1) {
5557 cpr.clients.remove(r);
5558 r.conProviders.remove(cpr);
5559 return true;
5560 } else {
5561 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
5562 }
5563 } else {
5564 cpr.externals++;
5565 }
5566 return false;
5567 }
5568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 private final ContentProviderHolder getContentProviderImpl(
5570 IApplicationThread caller, String name) {
5571 ContentProviderRecord cpr;
5572 ProviderInfo cpi = null;
5573
5574 synchronized(this) {
5575 ProcessRecord r = null;
5576 if (caller != null) {
5577 r = getRecordForAppLocked(caller);
5578 if (r == null) {
5579 throw new SecurityException(
5580 "Unable to find app for caller " + caller
5581 + " (pid=" + Binder.getCallingPid()
5582 + ") when getting content provider " + name);
5583 }
5584 }
5585
5586 // First check if this content provider has been published...
Dianne Hackborn860755f2010-06-03 18:47:52 -07005587 cpr = mProvidersByName.get(name);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005588 boolean providerRunning = cpr != null;
5589 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005591 String msg;
5592 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5593 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 }
5595
5596 if (r != null && cpr.canRunHere(r)) {
5597 // This provider has been published or is in the process
5598 // of being published... but it is also allowed to run
5599 // in the caller's process, so don't make a connection
5600 // and just let the caller instantiate its own instance.
5601 if (cpr.provider != null) {
5602 // don't give caller the provider object, it needs
5603 // to make its own.
5604 cpr = new ContentProviderRecord(cpr);
5605 }
5606 return cpr;
5607 }
5608
5609 final long origId = Binder.clearCallingIdentity();
5610
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005611 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 // return it right away.
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005613 final boolean countChanged = incProviderCount(r, cpr);
5614 if (countChanged) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005615 if (cpr.app != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005616 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005617 // make sure to count it as being accessed and thus
5618 // back up on the LRU list. This is good because
5619 // content providers are often expensive to start.
5620 updateLruProcessLocked(cpr.app, false, true);
5621 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07005622 }
5623
5624 if (cpr.app != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005625 if (false) {
5626 if (cpr.name.flattenToShortString().equals(
5627 "com.android.providers.calendar/.CalendarProvider2")) {
5628 Slog.v(TAG, "****************** KILLING "
5629 + cpr.name.flattenToShortString());
5630 Process.killProcess(cpr.app.pid);
5631 }
5632 }
5633 boolean success = updateOomAdjLocked(cpr.app);
5634 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
5635 // NOTE: there is still a race here where a signal could be
5636 // pending on the process even though we managed to update its
5637 // adj level. Not sure what to do about this, but at least
5638 // the race is now smaller.
5639 if (!success) {
5640 // Uh oh... it looks like the provider's process
5641 // has been killed on us. We need to wait for a new
5642 // process to be started, and make sure its death
5643 // doesn't kill our process.
5644 Slog.i(TAG,
5645 "Existing provider " + cpr.name.flattenToShortString()
5646 + " is crashing; detaching " + r);
5647 boolean lastRef = decProviderCount(r, cpr);
5648 appDiedLocked(cpr.app, cpr.app.pid, cpr.app.thread);
5649 if (!lastRef) {
5650 // This wasn't the last ref our process had on
5651 // the provider... we have now been killed, bail.
5652 return null;
5653 }
5654 providerRunning = false;
5655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 }
5657
5658 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005661 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005663 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07005664 resolveContentProvider(name,
5665 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 } catch (RemoteException ex) {
5667 }
5668 if (cpi == null) {
5669 return null;
5670 }
5671
Dianne Hackbornb424b632010-08-18 15:59:05 -07005672 String msg;
5673 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5674 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 }
5676
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07005677 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005678 && !cpi.processName.equals("system")) {
5679 // If this content provider does not run in the system
5680 // process, and the system is not yet ready to run other
5681 // processes, then fail fast instead of hanging.
5682 throw new IllegalArgumentException(
5683 "Attempt to launch content provider before system ready");
5684 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005685
5686 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
5687 cpr = mProvidersByClass.get(comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 final boolean firstClass = cpr == null;
5689 if (firstClass) {
5690 try {
5691 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005692 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005693 getApplicationInfo(
5694 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005695 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005697 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005698 + cpi.name);
5699 return null;
5700 }
5701 cpr = new ContentProviderRecord(cpi, ai);
5702 } catch (RemoteException ex) {
5703 // pm is in same process, this will never happen.
5704 }
5705 }
5706
5707 if (r != null && cpr.canRunHere(r)) {
5708 // If this is a multiprocess provider, then just return its
5709 // info and allow the caller to instantiate it. Only do
5710 // this if the provider is the same user as the caller's
5711 // process, or can run as root (so can be in any process).
5712 return cpr;
5713 }
5714
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005715 if (DEBUG_PROVIDER) {
5716 RuntimeException e = new RuntimeException("here");
Joe Onorato8a9b2202010-02-26 18:56:32 -08005717 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.info.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005718 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 }
5720
5721 // This is single process, and our app is now connecting to it.
5722 // See if we are already in the process of launching this
5723 // provider.
5724 final int N = mLaunchingProviders.size();
5725 int i;
5726 for (i=0; i<N; i++) {
5727 if (mLaunchingProviders.get(i) == cpr) {
5728 break;
5729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 }
5731
5732 // If the provider is not already being launched, then get it
5733 // started.
5734 if (i >= N) {
5735 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08005736
5737 try {
5738 // Content provider is now in use, its package can't be stopped.
5739 try {
5740 AppGlobals.getPackageManager().setPackageStoppedState(
5741 cpr.appInfo.packageName, false);
5742 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08005743 } catch (IllegalArgumentException e) {
5744 Slog.w(TAG, "Failed trying to unstop package "
5745 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08005746 }
5747
5748 ProcessRecord proc = startProcessLocked(cpi.processName,
5749 cpr.appInfo, false, 0, "content provider",
5750 new ComponentName(cpi.applicationInfo.packageName,
5751 cpi.name), false);
5752 if (proc == null) {
5753 Slog.w(TAG, "Unable to launch app "
5754 + cpi.applicationInfo.packageName + "/"
5755 + cpi.applicationInfo.uid + " for provider "
5756 + name + ": process is bad");
5757 return null;
5758 }
5759 cpr.launchingApp = proc;
5760 mLaunchingProviders.add(cpr);
5761 } finally {
5762 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005764 }
5765
5766 // Make sure the provider is published (the same provider class
5767 // may be published under multiple names).
5768 if (firstClass) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005769 mProvidersByClass.put(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 }
5771 mProvidersByName.put(name, cpr);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005772 incProviderCount(r, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773 }
5774 }
5775
5776 // Wait for the provider to be published...
5777 synchronized (cpr) {
5778 while (cpr.provider == null) {
5779 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005780 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781 + cpi.applicationInfo.packageName + "/"
5782 + cpi.applicationInfo.uid + " for provider "
5783 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08005784 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 cpi.applicationInfo.packageName,
5786 cpi.applicationInfo.uid, name);
5787 return null;
5788 }
5789 try {
5790 cpr.wait();
5791 } catch (InterruptedException ex) {
5792 }
5793 }
5794 }
5795 return cpr;
5796 }
5797
5798 public final ContentProviderHolder getContentProvider(
5799 IApplicationThread caller, String name) {
5800 if (caller == null) {
5801 String msg = "null IApplicationThread when getting content provider "
5802 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005803 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 throw new SecurityException(msg);
5805 }
5806
5807 return getContentProviderImpl(caller, name);
5808 }
5809
5810 private ContentProviderHolder getContentProviderExternal(String name) {
5811 return getContentProviderImpl(null, name);
5812 }
5813
5814 /**
5815 * Drop a content provider from a ProcessRecord's bookkeeping
5816 * @param cpr
5817 */
5818 public void removeContentProvider(IApplicationThread caller, String name) {
5819 synchronized (this) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005820 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005822 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08005823 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005824 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 return;
5826 }
5827 final ProcessRecord r = getRecordForAppLocked(caller);
5828 if (r == null) {
5829 throw new SecurityException(
5830 "Unable to find app for caller " + caller +
5831 " when removing content provider " + name);
5832 }
5833 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005834 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
5835 ContentProviderRecord localCpr = mProvidersByClass.get(comp);
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005836 if (localCpr.app == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08005838 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005839 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 return;
5841 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005842 if (decProviderCount(r, localCpr)) {
5843 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005846 }
5847 }
5848
5849 private void removeContentProviderExternal(String name) {
5850 synchronized (this) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005851 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 if(cpr == null) {
5853 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08005854 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 return;
5856 }
5857
5858 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005859 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
5860 ContentProviderRecord localCpr = mProvidersByClass.get(comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 localCpr.externals--;
5862 if (localCpr.externals < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005863 Slog.e(TAG, "Externals < 0 for content provider " + localCpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 }
5865 updateOomAdjLocked();
5866 }
5867 }
5868
5869 public final void publishContentProviders(IApplicationThread caller,
5870 List<ContentProviderHolder> providers) {
5871 if (providers == null) {
5872 return;
5873 }
5874
5875 synchronized(this) {
5876 final ProcessRecord r = getRecordForAppLocked(caller);
5877 if (r == null) {
5878 throw new SecurityException(
5879 "Unable to find app for caller " + caller
5880 + " (pid=" + Binder.getCallingPid()
5881 + ") when publishing content providers");
5882 }
5883
5884 final long origId = Binder.clearCallingIdentity();
5885
5886 final int N = providers.size();
5887 for (int i=0; i<N; i++) {
5888 ContentProviderHolder src = providers.get(i);
5889 if (src == null || src.info == null || src.provider == null) {
5890 continue;
5891 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005892 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005894 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
5895 mProvidersByClass.put(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005896 String names[] = dst.info.authority.split(";");
5897 for (int j = 0; j < names.length; j++) {
5898 mProvidersByName.put(names[j], dst);
5899 }
5900
5901 int NL = mLaunchingProviders.size();
5902 int j;
5903 for (j=0; j<NL; j++) {
5904 if (mLaunchingProviders.get(j) == dst) {
5905 mLaunchingProviders.remove(j);
5906 j--;
5907 NL--;
5908 }
5909 }
5910 synchronized (dst) {
5911 dst.provider = src.provider;
5912 dst.app = r;
5913 dst.notifyAll();
5914 }
5915 updateOomAdjLocked(r);
5916 }
5917 }
5918
5919 Binder.restoreCallingIdentity(origId);
5920 }
5921 }
5922
5923 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07005924 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06005925 synchronized (mSelf) {
5926 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
5927 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08005928 if (providers != null) {
5929 for (int i=providers.size()-1; i>=0; i--) {
5930 ProviderInfo pi = (ProviderInfo)providers.get(i);
5931 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5932 Slog.w(TAG, "Not installing system proc provider " + pi.name
5933 + ": not system .apk");
5934 providers.remove(i);
5935 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005936 }
5937 }
5938 }
Josh Bartel2ecce342010-02-25 10:55:48 -06005939 if (providers != null) {
5940 mSystemThread.installSystemProviders(providers);
5941 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08005942
5943 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01005944
5945 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 }
5947
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07005948 /**
5949 * Allows app to retrieve the MIME type of a URI without having permission
5950 * to access its content provider.
5951 *
5952 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
5953 *
5954 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
5955 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
5956 */
5957 public String getProviderMimeType(Uri uri) {
5958 final String name = uri.getAuthority();
5959 final long ident = Binder.clearCallingIdentity();
5960 ContentProviderHolder holder = null;
5961
5962 try {
5963 holder = getContentProviderExternal(name);
5964 if (holder != null) {
5965 return holder.provider.getType(uri);
5966 }
5967 } catch (RemoteException e) {
5968 Log.w(TAG, "Content provider dead retrieving " + uri, e);
5969 return null;
5970 } finally {
5971 if (holder != null) {
5972 removeContentProviderExternal(name);
5973 }
5974 Binder.restoreCallingIdentity(ident);
5975 }
5976
5977 return null;
5978 }
5979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980 // =========================================================
5981 // GLOBAL MANAGEMENT
5982 // =========================================================
5983
5984 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
5985 ApplicationInfo info, String customProcess) {
5986 String proc = customProcess != null ? customProcess : info.processName;
5987 BatteryStatsImpl.Uid.Proc ps = null;
5988 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
5989 synchronized (stats) {
5990 ps = stats.getProcessStatsLocked(info.uid, proc);
5991 }
5992 return new ProcessRecord(ps, thread, info, proc);
5993 }
5994
5995 final ProcessRecord addAppLocked(ApplicationInfo info) {
5996 ProcessRecord app = getProcessRecordLocked(info.processName, info.uid);
5997
5998 if (app == null) {
5999 app = newProcessRecordLocked(null, info, null);
6000 mProcessNames.put(info.processName, info.uid, app);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006001 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 }
6003
Dianne Hackborne7f97212011-02-24 14:40:20 -08006004 // This package really, really can not be stopped.
6005 try {
6006 AppGlobals.getPackageManager().setPackageStoppedState(
6007 info.packageName, false);
6008 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006009 } catch (IllegalArgumentException e) {
6010 Slog.w(TAG, "Failed trying to unstop package "
6011 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006012 }
6013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6015 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6016 app.persistent = true;
Dianne Hackborn7d608422011-08-07 16:24:18 -07006017 app.maxAdj = ProcessList.CORE_SERVER_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006018 }
6019 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6020 mPersistentStartingProcesses.add(app);
6021 startProcessLocked(app, "added application", app.processName);
6022 }
6023
6024 return app;
6025 }
6026
6027 public void unhandledBack() {
6028 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6029 "unhandledBack()");
6030
6031 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006032 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006033 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006034 TAG, "Performing unhandledBack(): stack size = " + count);
6035 if (count > 1) {
6036 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006037 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6039 Binder.restoreCallingIdentity(origId);
6040 }
6041 }
6042 }
6043
6044 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
6045 String name = uri.getAuthority();
6046 ContentProviderHolder cph = getContentProviderExternal(name);
6047 ParcelFileDescriptor pfd = null;
6048 if (cph != null) {
6049 // We record the binder invoker's uid in thread-local storage before
6050 // going to the content provider to open the file. Later, in the code
6051 // that handles all permissions checks, we look for this uid and use
6052 // that rather than the Activity Manager's own uid. The effect is that
6053 // we do the check against the caller's permissions even though it looks
6054 // to the content provider like the Activity Manager itself is making
6055 // the request.
6056 sCallerIdentity.set(new Identity(
6057 Binder.getCallingPid(), Binder.getCallingUid()));
6058 try {
6059 pfd = cph.provider.openFile(uri, "r");
6060 } catch (FileNotFoundException e) {
6061 // do nothing; pfd will be returned null
6062 } finally {
6063 // Ensure that whatever happens, we clean up the identity state
6064 sCallerIdentity.remove();
6065 }
6066
6067 // We've got the fd now, so we're done with the provider.
6068 removeContentProviderExternal(name);
6069 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006070 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 }
6072 return pfd;
6073 }
6074
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006075 // Actually is sleeping or shutting down or whatever else in the future
6076 // is an inactive state.
6077 public boolean isSleeping() {
6078 return mSleeping || mShuttingDown;
6079 }
6080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 public void goingToSleep() {
6082 synchronized(this) {
6083 mSleeping = true;
6084 mWindowManager.setEventDispatching(false);
6085
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006086 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006087
6088 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006089 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006090 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6091 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006092 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 }
6094 }
6095
Dianne Hackborn55280a92009-05-07 15:53:46 -07006096 public boolean shutdown(int timeout) {
6097 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6098 != PackageManager.PERMISSION_GRANTED) {
6099 throw new SecurityException("Requires permission "
6100 + android.Manifest.permission.SHUTDOWN);
6101 }
6102
6103 boolean timedout = false;
6104
6105 synchronized(this) {
6106 mShuttingDown = true;
6107 mWindowManager.setEventDispatching(false);
6108
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006109 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006110 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006111 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006112 while (mMainStack.mResumedActivity != null
6113 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006114 long delay = endTime - System.currentTimeMillis();
6115 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006116 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006117 timedout = true;
6118 break;
6119 }
6120 try {
6121 this.wait();
6122 } catch (InterruptedException e) {
6123 }
6124 }
6125 }
6126 }
6127
6128 mUsageStatsService.shutdown();
6129 mBatteryStatsService.shutdown();
6130
6131 return timedout;
6132 }
6133
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006134 public final void activitySlept(IBinder token) {
6135 if (localLOGV) Slog.v(
6136 TAG, "Activity slept: token=" + token);
6137
6138 ActivityRecord r = null;
6139
6140 final long origId = Binder.clearCallingIdentity();
6141
6142 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006143 r = mMainStack.isInStackLocked(token);
6144 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006145 mMainStack.activitySleptLocked(r);
6146 }
6147 }
6148
6149 Binder.restoreCallingIdentity(origId);
6150 }
6151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 public void wakingUp() {
6153 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 mWindowManager.setEventDispatching(true);
6155 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006156 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006157 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 }
6159 }
6160
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006161 public void stopAppSwitches() {
6162 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6163 != PackageManager.PERMISSION_GRANTED) {
6164 throw new SecurityException("Requires permission "
6165 + android.Manifest.permission.STOP_APP_SWITCHES);
6166 }
6167
6168 synchronized(this) {
6169 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6170 + APP_SWITCH_DELAY_TIME;
6171 mDidAppSwitch = false;
6172 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6173 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6174 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6175 }
6176 }
6177
6178 public void resumeAppSwitches() {
6179 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6180 != PackageManager.PERMISSION_GRANTED) {
6181 throw new SecurityException("Requires permission "
6182 + android.Manifest.permission.STOP_APP_SWITCHES);
6183 }
6184
6185 synchronized(this) {
6186 // Note that we don't execute any pending app switches... we will
6187 // let those wait until either the timeout, or the next start
6188 // activity request.
6189 mAppSwitchesAllowedTime = 0;
6190 }
6191 }
6192
6193 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6194 String name) {
6195 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6196 return true;
6197 }
6198
6199 final int perm = checkComponentPermission(
6200 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006201 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006202 if (perm == PackageManager.PERMISSION_GRANTED) {
6203 return true;
6204 }
6205
Joe Onorato8a9b2202010-02-26 18:56:32 -08006206 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006207 return false;
6208 }
6209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 public void setDebugApp(String packageName, boolean waitForDebugger,
6211 boolean persistent) {
6212 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6213 "setDebugApp()");
6214
6215 // Note that this is not really thread safe if there are multiple
6216 // callers into it at the same time, but that's not a situation we
6217 // care about.
6218 if (persistent) {
6219 final ContentResolver resolver = mContext.getContentResolver();
6220 Settings.System.putString(
6221 resolver, Settings.System.DEBUG_APP,
6222 packageName);
6223 Settings.System.putInt(
6224 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6225 waitForDebugger ? 1 : 0);
6226 }
6227
6228 synchronized (this) {
6229 if (!persistent) {
6230 mOrigDebugApp = mDebugApp;
6231 mOrigWaitForDebugger = mWaitForDebugger;
6232 }
6233 mDebugApp = packageName;
6234 mWaitForDebugger = waitForDebugger;
6235 mDebugTransient = !persistent;
6236 if (packageName != null) {
6237 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07006238 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 Binder.restoreCallingIdentity(origId);
6240 }
6241 }
6242 }
6243
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006244 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6245 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6246 synchronized (this) {
6247 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6248 if (!isDebuggable) {
6249 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6250 throw new SecurityException("Process not debuggable: " + app.packageName);
6251 }
6252 }
6253 mProfileApp = processName;
6254 mProfileFile = profileFile;
6255 if (mProfileFd != null) {
6256 try {
6257 mProfileFd.close();
6258 } catch (IOException e) {
6259 }
6260 mProfileFd = null;
6261 }
6262 mProfileFd = profileFd;
6263 mProfileType = 0;
6264 mAutoStopProfiler = autoStopProfiler;
6265 }
6266 }
6267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 public void setAlwaysFinish(boolean enabled) {
6269 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6270 "setAlwaysFinish()");
6271
6272 Settings.System.putInt(
6273 mContext.getContentResolver(),
6274 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6275
6276 synchronized (this) {
6277 mAlwaysFinishActivities = enabled;
6278 }
6279 }
6280
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006281 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006283 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006285 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 }
6287 }
6288
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006289 public boolean isUserAMonkey() {
6290 // For now the fact that there is a controller implies
6291 // we have a monkey.
6292 synchronized (this) {
6293 return mController != null;
6294 }
6295 }
6296
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006297 public void registerActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06006298 synchronized (this) {
6299 mWatchers.register(watcher);
6300 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006301 }
6302
6303 public void unregisterActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06006304 synchronized (this) {
6305 mWatchers.unregister(watcher);
6306 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006307 }
6308
Jeff Sharkeya4620792011-05-20 15:29:23 -07006309 public void registerProcessObserver(IProcessObserver observer) {
6310 mProcessObservers.register(observer);
6311 }
6312
6313 public void unregisterProcessObserver(IProcessObserver observer) {
6314 mProcessObservers.unregister(observer);
6315 }
6316
Daniel Sandler69a48172010-06-23 16:29:36 -04006317 public void setImmersive(IBinder token, boolean immersive) {
6318 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006319 ActivityRecord r = mMainStack.isInStackLocked(token);
6320 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006321 throw new IllegalArgumentException();
6322 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006323 r.immersive = immersive;
6324 }
6325 }
6326
6327 public boolean isImmersive(IBinder token) {
6328 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006329 ActivityRecord r = mMainStack.isInStackLocked(token);
6330 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006331 throw new IllegalArgumentException();
6332 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006333 return r.immersive;
6334 }
6335 }
6336
6337 public boolean isTopActivityImmersive() {
6338 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006339 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006340 return (r != null) ? r.immersive : false;
6341 }
6342 }
6343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 public final void enterSafeMode() {
6345 synchronized(this) {
6346 // It only makes sense to do this before the system is ready
6347 // and started launching other packages.
6348 if (!mSystemReady) {
6349 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006350 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 } catch (RemoteException e) {
6352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 }
6354 }
6355 }
6356
Jeff Brownb09abc12011-01-13 21:08:27 -08006357 public final void showSafeModeOverlay() {
6358 View v = LayoutInflater.from(mContext).inflate(
6359 com.android.internal.R.layout.safe_mode, null);
6360 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6361 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6362 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6363 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6364 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6365 lp.format = v.getBackground().getOpacity();
6366 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6367 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6368 ((WindowManager)mContext.getSystemService(
6369 Context.WINDOW_SERVICE)).addView(v, lp);
6370 }
6371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 public void noteWakeupAlarm(IIntentSender sender) {
6373 if (!(sender instanceof PendingIntentRecord)) {
6374 return;
6375 }
6376 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6377 synchronized (stats) {
6378 if (mBatteryStatsService.isOnBattery()) {
6379 mBatteryStatsService.enforceCallingPermission();
6380 PendingIntentRecord rec = (PendingIntentRecord)sender;
6381 int MY_UID = Binder.getCallingUid();
6382 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6383 BatteryStatsImpl.Uid.Pkg pkg =
6384 stats.getPackageStatsLocked(uid, rec.key.packageName);
6385 pkg.incWakeupsLocked();
6386 }
6387 }
6388 }
6389
Dianne Hackborn64825172011-03-02 21:32:58 -08006390 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006392 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006394 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 // XXX Note: don't acquire main activity lock here, because the window
6396 // manager calls in with its locks held.
6397
6398 boolean killed = false;
6399 synchronized (mPidsSelfLocked) {
6400 int[] types = new int[pids.length];
6401 int worstType = 0;
6402 for (int i=0; i<pids.length; i++) {
6403 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6404 if (proc != null) {
6405 int type = proc.setAdj;
6406 types[i] = type;
6407 if (type > worstType) {
6408 worstType = type;
6409 }
6410 }
6411 }
6412
Dianne Hackborn64825172011-03-02 21:32:58 -08006413 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 // then constrain it so we will kill all hidden procs.
Dianne Hackborn7d608422011-08-07 16:24:18 -07006415 if (worstType < ProcessList.EMPTY_APP_ADJ && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
6416 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006418
6419 // If this is not a secure call, don't let it kill processes that
6420 // are important.
Dianne Hackborn7d608422011-08-07 16:24:18 -07006421 if (!secure && worstType < ProcessList.SECONDARY_SERVER_ADJ) {
6422 worstType = ProcessList.SECONDARY_SERVER_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006423 }
6424
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006425 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 for (int i=0; i<pids.length; i++) {
6427 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6428 if (proc == null) {
6429 continue;
6430 }
6431 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006432 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006433 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006434 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6435 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006437 proc.killedBackground = true;
6438 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 }
6440 }
6441 }
6442 return killed;
6443 }
6444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 public final void startRunning(String pkg, String cls, String action,
6446 String data) {
6447 synchronized(this) {
6448 if (mStartRunning) {
6449 return;
6450 }
6451 mStartRunning = true;
6452 mTopComponent = pkg != null && cls != null
6453 ? new ComponentName(pkg, cls) : null;
6454 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6455 mTopData = data;
6456 if (!mSystemReady) {
6457 return;
6458 }
6459 }
6460
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006461 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 }
6463
6464 private void retrieveSettings() {
6465 final ContentResolver resolver = mContext.getContentResolver();
6466 String debugApp = Settings.System.getString(
6467 resolver, Settings.System.DEBUG_APP);
6468 boolean waitForDebugger = Settings.System.getInt(
6469 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6470 boolean alwaysFinishActivities = Settings.System.getInt(
6471 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6472
6473 Configuration configuration = new Configuration();
6474 Settings.System.getConfiguration(resolver, configuration);
6475
6476 synchronized (this) {
6477 mDebugApp = mOrigDebugApp = debugApp;
6478 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6479 mAlwaysFinishActivities = alwaysFinishActivities;
6480 // This happens before any activities are started, so we can
6481 // change mConfiguration in-place.
6482 mConfiguration.updateFrom(configuration);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006483 mConfigurationSeq = mConfiguration.seq = 1;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006484 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 }
6486 }
6487
6488 public boolean testIsSystemReady() {
6489 // no need to synchronize(this) just to read & return the value
6490 return mSystemReady;
6491 }
6492
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006493 private static File getCalledPreBootReceiversFile() {
6494 File dataDir = Environment.getDataDirectory();
6495 File systemDir = new File(dataDir, "system");
6496 File fname = new File(systemDir, "called_pre_boots.dat");
6497 return fname;
6498 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07006499
6500 static final int LAST_DONE_VERSION = 10000;
6501
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006502 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6503 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6504 File file = getCalledPreBootReceiversFile();
6505 FileInputStream fis = null;
6506 try {
6507 fis = new FileInputStream(file);
6508 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006509 int fvers = dis.readInt();
6510 if (fvers == LAST_DONE_VERSION) {
6511 String vers = dis.readUTF();
6512 String codename = dis.readUTF();
6513 String build = dis.readUTF();
6514 if (android.os.Build.VERSION.RELEASE.equals(vers)
6515 && android.os.Build.VERSION.CODENAME.equals(codename)
6516 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
6517 int num = dis.readInt();
6518 while (num > 0) {
6519 num--;
6520 String pkg = dis.readUTF();
6521 String cls = dis.readUTF();
6522 lastDoneReceivers.add(new ComponentName(pkg, cls));
6523 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006524 }
6525 }
6526 } catch (FileNotFoundException e) {
6527 } catch (IOException e) {
6528 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6529 } finally {
6530 if (fis != null) {
6531 try {
6532 fis.close();
6533 } catch (IOException e) {
6534 }
6535 }
6536 }
6537 return lastDoneReceivers;
6538 }
6539
6540 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
6541 File file = getCalledPreBootReceiversFile();
6542 FileOutputStream fos = null;
6543 DataOutputStream dos = null;
6544 try {
6545 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
6546 fos = new FileOutputStream(file);
6547 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006548 dos.writeInt(LAST_DONE_VERSION);
6549 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006550 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07006551 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006552 dos.writeInt(list.size());
6553 for (int i=0; i<list.size(); i++) {
6554 dos.writeUTF(list.get(i).getPackageName());
6555 dos.writeUTF(list.get(i).getClassName());
6556 }
6557 } catch (IOException e) {
6558 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
6559 file.delete();
6560 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006561 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006562 if (dos != null) {
6563 try {
6564 dos.close();
6565 } catch (IOException e) {
6566 // TODO Auto-generated catch block
6567 e.printStackTrace();
6568 }
6569 }
6570 }
6571 }
6572
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006573 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006574 synchronized(this) {
6575 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006576 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 return;
6578 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006579
6580 // Check to see if there are any update receivers to run.
6581 if (!mDidUpdate) {
6582 if (mWaitingUpdate) {
6583 return;
6584 }
6585 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6586 List<ResolveInfo> ris = null;
6587 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006588 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006589 intent, null, 0);
6590 } catch (RemoteException e) {
6591 }
6592 if (ris != null) {
6593 for (int i=ris.size()-1; i>=0; i--) {
6594 if ((ris.get(i).activityInfo.applicationInfo.flags
6595 &ApplicationInfo.FLAG_SYSTEM) == 0) {
6596 ris.remove(i);
6597 }
6598 }
6599 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006600
6601 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
6602
6603 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006604 for (int i=0; i<ris.size(); i++) {
6605 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006606 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6607 if (lastDoneReceivers.contains(comp)) {
6608 ris.remove(i);
6609 i--;
6610 }
6611 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07006612
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006613 for (int i=0; i<ris.size(); i++) {
6614 ActivityInfo ai = ris.get(i).activityInfo;
6615 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6616 doneReceivers.add(comp);
6617 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006618 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08006619 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006620 finisher = new IIntentReceiver.Stub() {
6621 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07006622 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006623 boolean sticky) {
6624 // The raw IIntentReceiver interface is called
6625 // with the AM lock held, so redispatch to
6626 // execute our code without the lock.
6627 mHandler.post(new Runnable() {
6628 public void run() {
6629 synchronized (ActivityManagerService.this) {
6630 mDidUpdate = true;
6631 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006632 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07006633 showBootMessage(mContext.getText(
6634 R.string.android_upgrading_complete),
6635 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006636 systemReady(goingCallback);
6637 }
6638 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006639 }
6640 };
6641 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006642 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006643 broadcastIntentLocked(null, null, intent, null, finisher,
6644 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackbornd6847842010-01-12 18:14:19 -08006645 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006646 mWaitingUpdate = true;
6647 }
6648 }
6649 }
6650 if (mWaitingUpdate) {
6651 return;
6652 }
6653 mDidUpdate = true;
6654 }
6655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006656 mSystemReady = true;
6657 if (!mStartRunning) {
6658 return;
6659 }
6660 }
6661
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006662 ArrayList<ProcessRecord> procsToKill = null;
6663 synchronized(mPidsSelfLocked) {
6664 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
6665 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
6666 if (!isAllowedWhileBooting(proc.info)){
6667 if (procsToKill == null) {
6668 procsToKill = new ArrayList<ProcessRecord>();
6669 }
6670 procsToKill.add(proc);
6671 }
6672 }
6673 }
6674
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006675 synchronized(this) {
6676 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006677 for (int i=procsToKill.size()-1; i>=0; i--) {
6678 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006679 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07006680 removeProcessLocked(proc, true, false);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006681 }
6682 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006683
6684 // Now that we have cleaned up any update processes, we
6685 // are ready to start launching real processes and know that
6686 // we won't trample on them any more.
6687 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006688 }
6689
Joe Onorato8a9b2202010-02-26 18:56:32 -08006690 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006691 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 SystemClock.uptimeMillis());
6693
6694 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006695 // Make sure we have no pre-ready processes sitting around.
6696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
6698 ResolveInfo ri = mContext.getPackageManager()
6699 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07006700 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 CharSequence errorMsg = null;
6702 if (ri != null) {
6703 ActivityInfo ai = ri.activityInfo;
6704 ApplicationInfo app = ai.applicationInfo;
6705 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6706 mTopAction = Intent.ACTION_FACTORY_TEST;
6707 mTopData = null;
6708 mTopComponent = new ComponentName(app.packageName,
6709 ai.name);
6710 } else {
6711 errorMsg = mContext.getResources().getText(
6712 com.android.internal.R.string.factorytest_not_system);
6713 }
6714 } else {
6715 errorMsg = mContext.getResources().getText(
6716 com.android.internal.R.string.factorytest_no_action);
6717 }
6718 if (errorMsg != null) {
6719 mTopAction = null;
6720 mTopData = null;
6721 mTopComponent = null;
6722 Message msg = Message.obtain();
6723 msg.what = SHOW_FACTORY_ERROR_MSG;
6724 msg.getData().putCharSequence("msg", errorMsg);
6725 mHandler.sendMessage(msg);
6726 }
6727 }
6728 }
6729
6730 retrieveSettings();
6731
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006732 if (goingCallback != null) goingCallback.run();
6733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 synchronized (this) {
6735 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
6736 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006737 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006738 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006739 if (apps != null) {
6740 int N = apps.size();
6741 int i;
6742 for (i=0; i<N; i++) {
6743 ApplicationInfo info
6744 = (ApplicationInfo)apps.get(i);
6745 if (info != null &&
6746 !info.packageName.equals("android")) {
6747 addAppLocked(info);
6748 }
6749 }
6750 }
6751 } catch (RemoteException ex) {
6752 // pm is in same process, this will never happen.
6753 }
6754 }
6755
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006756 // Start up initial activity.
6757 mBooting = true;
6758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006760 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761 Message msg = Message.obtain();
6762 msg.what = SHOW_UID_ERROR_MSG;
6763 mHandler.sendMessage(msg);
6764 }
6765 } catch (RemoteException e) {
6766 }
6767
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006768 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 }
6770 }
6771
Dan Egnorb7f03672009-12-09 16:22:32 -08006772 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006773 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08006775 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08006776 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777 startAppProblemLocked(app);
6778 app.stopFreezingAllLocked();
6779 return handleAppCrashLocked(app);
6780 }
6781
Dan Egnorb7f03672009-12-09 16:22:32 -08006782 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006783 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006784 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08006785 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08006786 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
6787 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006788 startAppProblemLocked(app);
6789 app.stopFreezingAllLocked();
6790 }
6791
6792 /**
6793 * Generate a process error record, suitable for attachment to a ProcessRecord.
6794 *
6795 * @param app The ProcessRecord in which the error occurred.
6796 * @param condition Crashing, Application Not Responding, etc. Values are defined in
6797 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08006798 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 * @param shortMsg Short message describing the crash.
6800 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08006801 * @param stackTrace Full crash stack trace, may be null.
6802 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006803 * @return Returns a fully-formed AppErrorStateInfo record.
6804 */
6805 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006806 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006807 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08006808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 report.condition = condition;
6810 report.processName = app.processName;
6811 report.pid = app.pid;
6812 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08006813 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006814 report.shortMsg = shortMsg;
6815 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08006816 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006817
6818 return report;
6819 }
6820
Dan Egnor42471dd2010-01-07 17:25:22 -08006821 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006822 synchronized (this) {
6823 app.crashing = false;
6824 app.crashingReport = null;
6825 app.notResponding = false;
6826 app.notRespondingReport = null;
6827 if (app.anrDialog == fromDialog) {
6828 app.anrDialog = null;
6829 }
6830 if (app.waitDialog == fromDialog) {
6831 app.waitDialog = null;
6832 }
6833 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08006834 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006835 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07006836 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
6837 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006838 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 }
6841 }
Dan Egnor42471dd2010-01-07 17:25:22 -08006842
Dan Egnorb7f03672009-12-09 16:22:32 -08006843 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844 long now = SystemClock.uptimeMillis();
6845
6846 Long crashTime = mProcessCrashTimes.get(app.info.processName,
6847 app.info.uid);
Dianne Hackborn7d608422011-08-07 16:24:18 -07006848 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006849 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08006850 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006851 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006852 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006853 app.info.processName, app.info.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006854 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6855 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006856 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006857 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006859 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006860 }
6861 }
6862 if (!app.persistent) {
6863 // We don't want to start this process again until the user
6864 // explicitly does so... but for persistent process, we really
6865 // need to keep it running. If a persistent process is actually
6866 // repeatedly crashing, then badness for everyone.
Doug Zongker2bec3d42009-12-04 12:52:44 -08006867 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868 app.info.processName);
6869 mBadProcesses.put(app.info.processName, app.info.uid, now);
6870 app.bad = true;
6871 mProcessCrashTimes.remove(app.info.processName, app.info.uid);
6872 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07006873 // Don't let services in this process be restarted and potentially
6874 // annoy the user repeatedly. Unless it is persistent, since those
6875 // processes run critical code.
6876 removeProcessLocked(app, false, false);
Dianne Hackborncb44d962011-03-10 17:02:27 -08006877 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006878 return false;
6879 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08006880 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006881 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006882 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006883 if (r.app == app) {
6884 // If the top running activity is from this crashing
6885 // process, then terminate it to avoid getting in a loop.
6886 Slog.w(TAG, " Force finishing activity "
6887 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006888 int index = mMainStack.indexOfTokenLocked(r);
6889 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006890 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08006891 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006892 // stopped, to avoid a situation where one will get
6893 // re-start our crashing activity once it gets resumed again.
6894 index--;
6895 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006896 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006897 if (r.state == ActivityState.RESUMED
6898 || r.state == ActivityState.PAUSING
6899 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08006900 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006901 Slog.w(TAG, " Force finishing activity "
6902 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006903 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006904 Activity.RESULT_CANCELED, null, "crashed");
6905 }
6906 }
6907 }
6908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 }
6910
6911 // Bump up the crash count of any services currently running in the proc.
6912 if (app.services.size() != 0) {
6913 // Any services running in the application need to be placed
6914 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07006915 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006916 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07006917 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918 sr.crashCount++;
6919 }
6920 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02006921
6922 // If the crashing process is what we consider to be the "home process" and it has been
6923 // replaced by a third-party app, clear the package preferred activities from packages
6924 // with a home activity running in the process to prevent a repeatedly crashing app
6925 // from blocking the user to manually clear the list.
6926 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
6927 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
6928 Iterator it = mHomeProcess.activities.iterator();
6929 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07006930 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02006931 if (r.isHomeActivity) {
6932 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
6933 try {
6934 ActivityThread.getPackageManager()
6935 .clearPackagePreferredActivities(r.packageName);
6936 } catch (RemoteException c) {
6937 // pm is in same process, this will never happen.
6938 }
6939 }
6940 }
6941 }
6942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943 mProcessCrashTimes.put(app.info.processName, app.info.uid, now);
6944 return true;
6945 }
6946
6947 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006948 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
6949 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 skipCurrentReceiverLocked(app);
6951 }
6952
6953 void skipCurrentReceiverLocked(ProcessRecord app) {
6954 boolean reschedule = false;
6955 BroadcastRecord r = app.curReceiver;
6956 if (r != null) {
6957 // The current broadcast is waiting for this app's receiver
6958 // to be finished. Looks like that's not going to happen, so
6959 // let the broadcast continue.
Jeff Brown4d94a762010-09-23 11:33:28 -07006960 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006961 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
6962 r.resultExtras, r.resultAbort, true);
6963 reschedule = true;
6964 }
6965 r = mPendingBroadcast;
6966 if (r != null && r.curApp == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006967 if (DEBUG_BROADCAST) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006968 "skip & discard pending app " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -07006969 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006970 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
6971 r.resultExtras, r.resultAbort, true);
6972 reschedule = true;
6973 }
6974 if (reschedule) {
6975 scheduleBroadcastsLocked();
6976 }
6977 }
6978
Dan Egnor60d87622009-12-16 16:32:58 -08006979 /**
6980 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
6981 * The application process will exit immediately after this call returns.
6982 * @param app object of the crashing app, null for the system server
6983 * @param crashInfo describing the exception
6984 */
6985 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08006986 ProcessRecord r = findAppProcess(app, "Crash");
Dan Egnor60d87622009-12-16 16:32:58 -08006987
6988 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
6989 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08006990 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08006991 crashInfo.exceptionClassName,
6992 crashInfo.exceptionMessage,
6993 crashInfo.throwFileName,
6994 crashInfo.throwLineNumber);
6995
Dan Egnor42471dd2010-01-07 17:25:22 -08006996 addErrorToDropBox("crash", r, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08006997
6998 crashApplication(r, crashInfo);
6999 }
7000
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007001 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007002 IBinder app,
7003 int violationMask,
7004 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007005 ProcessRecord r = findAppProcess(app, "StrictMode");
7006 if (r == null) {
7007 return;
7008 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007009
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007010 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007011 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007012 boolean logIt = true;
7013 synchronized (mAlreadyLoggedViolatedStacks) {
7014 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7015 logIt = false;
7016 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007017 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007018 // the relative pain numbers, without logging all
7019 // the stack traces repeatedly. We'd want to do
7020 // likewise in the client code, which also does
7021 // dup suppression, before the Binder call.
7022 } else {
7023 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7024 mAlreadyLoggedViolatedStacks.clear();
7025 }
7026 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7027 }
7028 }
7029 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007030 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007031 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007032 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007033
7034 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7035 AppErrorResult result = new AppErrorResult();
7036 synchronized (this) {
7037 final long origId = Binder.clearCallingIdentity();
7038
7039 Message msg = Message.obtain();
7040 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7041 HashMap<String, Object> data = new HashMap<String, Object>();
7042 data.put("result", result);
7043 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007044 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007045 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007046 msg.obj = data;
7047 mHandler.sendMessage(msg);
7048
7049 Binder.restoreCallingIdentity(origId);
7050 }
7051 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007052 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007053 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007054 }
7055
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007056 // Depending on the policy in effect, there could be a bunch of
7057 // these in quick succession so we try to batch these together to
7058 // minimize disk writes, number of dropbox entries, and maximize
7059 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007060 private void logStrictModeViolationToDropBox(
7061 ProcessRecord process,
7062 StrictMode.ViolationInfo info) {
7063 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007064 return;
7065 }
7066 final boolean isSystemApp = process == null ||
7067 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7068 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
7069 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7070 final DropBoxManager dbox = (DropBoxManager)
7071 mContext.getSystemService(Context.DROPBOX_SERVICE);
7072
7073 // Exit early if the dropbox isn't configured to accept this report type.
7074 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7075
7076 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007077 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007078 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7079 synchronized (sb) {
7080 bufferWasEmpty = sb.length() == 0;
7081 appendDropBoxProcessHeaders(process, sb);
7082 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7083 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007084 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7085 if (info.violationNumThisLoop != 0) {
7086 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7087 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007088 if (info.numAnimationsRunning != 0) {
7089 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7090 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007091 if (info.broadcastIntentAction != null) {
7092 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7093 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007094 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007095 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007096 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007097 if (info.numInstances != -1) {
7098 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7099 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007100 if (info.tags != null) {
7101 for (String tag : info.tags) {
7102 sb.append("Span-Tag: ").append(tag).append("\n");
7103 }
7104 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007105 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007106 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7107 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007108 }
7109 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007110
7111 // Only buffer up to ~64k. Various logging bits truncate
7112 // things at 128k.
7113 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007114 }
7115
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007116 // Flush immediately if the buffer's grown too large, or this
7117 // is a non-system app. Non-system apps are isolated with a
7118 // different tag & policy and not batched.
7119 //
7120 // Batching is useful during internal testing with
7121 // StrictMode settings turned up high. Without batching,
7122 // thousands of separate files could be created on boot.
7123 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007124 new Thread("Error dump: " + dropboxTag) {
7125 @Override
7126 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007127 String report;
7128 synchronized (sb) {
7129 report = sb.toString();
7130 sb.delete(0, sb.length());
7131 sb.trimToSize();
7132 }
7133 if (report.length() != 0) {
7134 dbox.addText(dropboxTag, report);
7135 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007136 }
7137 }.start();
7138 return;
7139 }
7140
7141 // System app batching:
7142 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007143 // An existing dropbox-writing thread is outstanding, so
7144 // we don't need to start it up. The existing thread will
7145 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007146 return;
7147 }
7148
7149 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7150 // (After this point, we shouldn't access AMS internal data structures.)
7151 new Thread("Error dump: " + dropboxTag) {
7152 @Override
7153 public void run() {
7154 // 5 second sleep to let stacks arrive and be batched together
7155 try {
7156 Thread.sleep(5000); // 5 seconds
7157 } catch (InterruptedException e) {}
7158
7159 String errorReport;
7160 synchronized (mStrictModeBuffer) {
7161 errorReport = mStrictModeBuffer.toString();
7162 if (errorReport.length() == 0) {
7163 return;
7164 }
7165 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7166 mStrictModeBuffer.trimToSize();
7167 }
7168 dbox.addText(dropboxTag, errorReport);
7169 }
7170 }.start();
7171 }
7172
Dan Egnor60d87622009-12-16 16:32:58 -08007173 /**
7174 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7175 * @param app object of the crashing app, null for the system server
7176 * @param tag reported by the caller
7177 * @param crashInfo describing the context of the error
7178 * @return true if the process should exit immediately (WTF is fatal)
7179 */
7180 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007181 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007182 ProcessRecord r = findAppProcess(app, "WTF");
Dan Egnor60d87622009-12-16 16:32:58 -08007183
7184 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
7185 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08007186 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007187 tag, crashInfo.exceptionMessage);
7188
Dan Egnor42471dd2010-01-07 17:25:22 -08007189 addErrorToDropBox("wtf", r, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007190
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007191 if (r != null && r.pid != Process.myPid() &&
7192 Settings.Secure.getInt(mContext.getContentResolver(),
7193 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007194 crashApplication(r, crashInfo);
7195 return true;
7196 } else {
7197 return false;
7198 }
7199 }
7200
7201 /**
7202 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7203 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7204 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007205 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007206 if (app == null) {
7207 return null;
7208 }
7209
7210 synchronized (this) {
7211 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7212 final int NA = apps.size();
7213 for (int ia=0; ia<NA; ia++) {
7214 ProcessRecord p = apps.valueAt(ia);
7215 if (p.thread != null && p.thread.asBinder() == app) {
7216 return p;
7217 }
7218 }
7219 }
7220
Dianne Hackborncb44d962011-03-10 17:02:27 -08007221 Slog.w(TAG, "Can't find mystery application for " + reason
7222 + " from pid=" + Binder.getCallingPid()
7223 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007224 return null;
7225 }
7226 }
7227
7228 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007229 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7230 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007231 */
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007232 private void appendDropBoxProcessHeaders(ProcessRecord process, StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007233 // Watchdog thread ends up invoking this function (with
7234 // a null ProcessRecord) to add the stack file to dropbox.
7235 // Do not acquire a lock on this (am) in such cases, as it
7236 // could cause a potential deadlock, if and when watchdog
7237 // is invoked due to unavailability of lock on am and it
7238 // would prevent watchdog from killing system_server.
7239 if (process == null) {
7240 sb.append("Process: system_server\n");
7241 return;
7242 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007243 // Note: ProcessRecord 'process' is guarded by the service
7244 // instance. (notably process.pkgList, which could otherwise change
7245 // concurrently during execution of this method)
7246 synchronized (this) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007247 if (process.pid == MY_PID) {
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007248 sb.append("Process: system_server\n");
7249 } else {
7250 sb.append("Process: ").append(process.processName).append("\n");
7251 }
Dan Egnora455d192010-03-12 08:52:28 -08007252 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007253 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007254 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7255 for (String pkg : process.pkgList) {
7256 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007257 try {
Dan Egnora455d192010-03-12 08:52:28 -08007258 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7259 if (pi != null) {
7260 sb.append(" v").append(pi.versionCode);
7261 if (pi.versionName != null) {
7262 sb.append(" (").append(pi.versionName).append(")");
7263 }
7264 }
7265 } catch (RemoteException e) {
7266 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007267 }
Dan Egnora455d192010-03-12 08:52:28 -08007268 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007269 }
Dan Egnora455d192010-03-12 08:52:28 -08007270 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007271 }
7272
7273 private static String processClass(ProcessRecord process) {
7274 if (process == null || process.pid == MY_PID) {
7275 return "system_server";
7276 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7277 return "system_app";
7278 } else {
7279 return "data_app";
7280 }
7281 }
7282
7283 /**
7284 * Write a description of an error (crash, WTF, ANR) to the drop box.
7285 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7286 * @param process which caused the error, null means the system server
7287 * @param activity which triggered the error, null if unknown
7288 * @param parent activity related to the error, null if unknown
7289 * @param subject line related to the error, null if absent
7290 * @param report in long form describing the error, null if absent
7291 * @param logFile to include in the report, null if none
7292 * @param crashInfo giving an application stack trace, null if absent
7293 */
7294 public void addErrorToDropBox(String eventType,
7295 ProcessRecord process, ActivityRecord activity, ActivityRecord parent, String subject,
7296 final String report, final File logFile,
7297 final ApplicationErrorReport.CrashInfo crashInfo) {
7298 // NOTE -- this must never acquire the ActivityManagerService lock,
7299 // otherwise the watchdog may be prevented from resetting the system.
7300
7301 final String dropboxTag = processClass(process) + "_" + eventType;
7302 final DropBoxManager dbox = (DropBoxManager)
7303 mContext.getSystemService(Context.DROPBOX_SERVICE);
7304
7305 // Exit early if the dropbox isn't configured to accept this report type.
7306 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7307
7308 final StringBuilder sb = new StringBuilder(1024);
7309 appendDropBoxProcessHeaders(process, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007310 if (activity != null) {
7311 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7312 }
7313 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7314 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7315 }
7316 if (parent != null && parent != activity) {
7317 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7318 }
7319 if (subject != null) {
7320 sb.append("Subject: ").append(subject).append("\n");
7321 }
7322 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007323 if (Debug.isDebuggerConnected()) {
7324 sb.append("Debugger: Connected\n");
7325 }
Dan Egnora455d192010-03-12 08:52:28 -08007326 sb.append("\n");
7327
7328 // Do the rest in a worker thread to avoid blocking the caller on I/O
7329 // (After this point, we shouldn't access AMS internal data structures.)
7330 Thread worker = new Thread("Error dump: " + dropboxTag) {
7331 @Override
7332 public void run() {
7333 if (report != null) {
7334 sb.append(report);
7335 }
7336 if (logFile != null) {
7337 try {
7338 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7339 } catch (IOException e) {
7340 Slog.e(TAG, "Error reading " + logFile, e);
7341 }
7342 }
7343 if (crashInfo != null && crashInfo.stackTrace != null) {
7344 sb.append(crashInfo.stackTrace);
7345 }
7346
7347 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7348 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7349 if (lines > 0) {
7350 sb.append("\n");
7351
7352 // Merge several logcat streams, and take the last N lines
7353 InputStreamReader input = null;
7354 try {
7355 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7356 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7357 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7358
7359 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7360 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7361 input = new InputStreamReader(logcat.getInputStream());
7362
7363 int num;
7364 char[] buf = new char[8192];
7365 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7366 } catch (IOException e) {
7367 Slog.e(TAG, "Error running logcat", e);
7368 } finally {
7369 if (input != null) try { input.close(); } catch (IOException e) {}
7370 }
7371 }
7372
7373 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007374 }
Dan Egnora455d192010-03-12 08:52:28 -08007375 };
7376
7377 if (process == null || process.pid == MY_PID) {
7378 worker.run(); // We may be about to die -- need to run this synchronously
7379 } else {
7380 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007381 }
7382 }
7383
7384 /**
7385 * Bring up the "unexpected error" dialog box for a crashing app.
7386 * Deal with edge cases (intercepts from instrumented applications,
7387 * ActivityController, error intent receivers, that sort of thing).
7388 * @param r the application crashing
7389 * @param crashInfo describing the failure
7390 */
7391 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007392 long timeMillis = System.currentTimeMillis();
7393 String shortMsg = crashInfo.exceptionClassName;
7394 String longMsg = crashInfo.exceptionMessage;
7395 String stackTrace = crashInfo.stackTrace;
7396 if (shortMsg != null && longMsg != null) {
7397 longMsg = shortMsg + ": " + longMsg;
7398 } else if (shortMsg != null) {
7399 longMsg = shortMsg;
7400 }
7401
Dan Egnor60d87622009-12-16 16:32:58 -08007402 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007403 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007404 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007405 try {
7406 String name = r != null ? r.processName : null;
7407 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007408 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007409 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007410 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007411 + " at watcher's request");
7412 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007413 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007414 }
7415 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007416 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007417 }
7418 }
7419
7420 final long origId = Binder.clearCallingIdentity();
7421
7422 // If this process is running instrumentation, finish it.
7423 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007424 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007425 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007426 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7427 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007428 Bundle info = new Bundle();
7429 info.putString("shortMsg", shortMsg);
7430 info.putString("longMsg", longMsg);
7431 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7432 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007433 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007434 }
7435
Dan Egnor60d87622009-12-16 16:32:58 -08007436 // If we can't identify the process or it's already exceeded its crash quota,
7437 // quit right away without showing a crash dialog.
7438 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007439 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007440 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 }
7442
7443 Message msg = Message.obtain();
7444 msg.what = SHOW_ERROR_MSG;
7445 HashMap data = new HashMap();
7446 data.put("result", result);
7447 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007448 msg.obj = data;
7449 mHandler.sendMessage(msg);
7450
7451 Binder.restoreCallingIdentity(origId);
7452 }
7453
7454 int res = result.get();
7455
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007456 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007457 synchronized (this) {
7458 if (r != null) {
7459 mProcessCrashTimes.put(r.info.processName, r.info.uid,
7460 SystemClock.uptimeMillis());
7461 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007462 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007463 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007464 }
7465 }
7466
7467 if (appErrorIntent != null) {
7468 try {
7469 mContext.startActivity(appErrorIntent);
7470 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007471 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007475
7476 Intent createAppErrorIntentLocked(ProcessRecord r,
7477 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7478 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007479 if (report == null) {
7480 return null;
7481 }
7482 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7483 result.setComponent(r.errorReportReceiver);
7484 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7485 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7486 return result;
7487 }
7488
Dan Egnorb7f03672009-12-09 16:22:32 -08007489 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7490 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007491 if (r.errorReportReceiver == null) {
7492 return null;
7493 }
7494
7495 if (!r.crashing && !r.notResponding) {
7496 return null;
7497 }
7498
Dan Egnorb7f03672009-12-09 16:22:32 -08007499 ApplicationErrorReport report = new ApplicationErrorReport();
7500 report.packageName = r.info.packageName;
7501 report.installerPackageName = r.errorReportReceiver.getPackageName();
7502 report.processName = r.processName;
7503 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007504 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007505
Dan Egnorb7f03672009-12-09 16:22:32 -08007506 if (r.crashing) {
7507 report.type = ApplicationErrorReport.TYPE_CRASH;
7508 report.crashInfo = crashInfo;
7509 } else if (r.notResponding) {
7510 report.type = ApplicationErrorReport.TYPE_ANR;
7511 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007512
Dan Egnorb7f03672009-12-09 16:22:32 -08007513 report.anrInfo.activity = r.notRespondingReport.tag;
7514 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7515 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007516 }
7517
Dan Egnorb7f03672009-12-09 16:22:32 -08007518 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007519 }
7520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007521 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
7522 // assume our apps are happy - lazy create the list
7523 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7524
7525 synchronized (this) {
7526
7527 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007528 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7529 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007530 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7531 // This one's in trouble, so we'll generate a report for it
7532 // crashes are higher priority (in case there's a crash *and* an anr)
7533 ActivityManager.ProcessErrorStateInfo report = null;
7534 if (app.crashing) {
7535 report = app.crashingReport;
7536 } else if (app.notResponding) {
7537 report = app.notRespondingReport;
7538 }
7539
7540 if (report != null) {
7541 if (errList == null) {
7542 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
7543 }
7544 errList.add(report);
7545 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007546 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007547 " crashing = " + app.crashing +
7548 " notResponding = " + app.notResponding);
7549 }
7550 }
7551 }
7552 }
7553
7554 return errList;
7555 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07007556
7557 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
7558 if (adj >= ProcessList.EMPTY_APP_ADJ) {
7559 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY;
7560 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
7561 if (currApp != null) {
7562 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
7563 }
7564 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
7565 } else if (adj >= ProcessList.HOME_APP_ADJ) {
7566 if (currApp != null) {
7567 currApp.lru = 0;
7568 }
7569 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
7570 } else if (adj >= ProcessList.SECONDARY_SERVER_ADJ) {
7571 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
7572 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
7573 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
7574 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
7575 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
7576 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
7577 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
7578 } else {
7579 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
7580 }
7581 }
7582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
7584 // Lazy instantiation of list
7585 List<ActivityManager.RunningAppProcessInfo> runList = null;
7586 synchronized (this) {
7587 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007588 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7589 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
7591 // Generate process state info for running application
7592 ActivityManager.RunningAppProcessInfo currApp =
7593 new ActivityManager.RunningAppProcessInfo(app.processName,
7594 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07007595 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007596 if (mHeavyWeightProcess == app) {
Dianne Hackborn482566e2010-09-03 12:51:28 -07007597 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007598 }
Dianne Hackborn42499172010-10-15 18:45:07 -07007599 if (app.persistent) {
7600 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
7601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007602 int adj = app.curAdj;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007603 currApp.importance = oomAdjToImportance(adj, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007604 currApp.importanceReasonCode = app.adjTypeCode;
7605 if (app.adjSource instanceof ProcessRecord) {
7606 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007607 currApp.importanceReasonImportance = oomAdjToImportance(
7608 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007609 } else if (app.adjSource instanceof ActivityRecord) {
7610 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007611 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
7612 }
7613 if (app.adjTarget instanceof ComponentName) {
7614 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
7615 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007616 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007617 // + " lru=" + currApp.lru);
7618 if (runList == null) {
7619 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
7620 }
7621 runList.add(currApp);
7622 }
7623 }
7624 }
7625 return runList;
7626 }
7627
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007628 public List<ApplicationInfo> getRunningExternalApplications() {
7629 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
7630 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
7631 if (runningApps != null && runningApps.size() > 0) {
7632 Set<String> extList = new HashSet<String>();
7633 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
7634 if (app.pkgList != null) {
7635 for (String pkg : app.pkgList) {
7636 extList.add(pkg);
7637 }
7638 }
7639 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007640 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007641 for (String pkg : extList) {
7642 try {
7643 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
7644 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
7645 retList.add(info);
7646 }
7647 } catch (RemoteException e) {
7648 }
7649 }
7650 }
7651 return retList;
7652 }
7653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007654 @Override
7655 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007656 if (checkCallingPermission(android.Manifest.permission.DUMP)
7657 != PackageManager.PERMISSION_GRANTED) {
7658 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7659 + Binder.getCallingPid()
7660 + ", uid=" + Binder.getCallingUid()
7661 + " without permission "
7662 + android.Manifest.permission.DUMP);
7663 return;
7664 }
7665
7666 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007667 boolean dumpClient = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007668
7669 int opti = 0;
7670 while (opti < args.length) {
7671 String opt = args[opti];
7672 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7673 break;
7674 }
7675 opti++;
7676 if ("-a".equals(opt)) {
7677 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007678 } else if ("-c".equals(opt)) {
7679 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007680 } else if ("-h".equals(opt)) {
7681 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007682 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007683 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07007684 pw.println(" a[ctivities]: activity stack state");
7685 pw.println(" b[roadcasts]: broadcast state");
7686 pw.println(" i[ntents]: pending intent state");
7687 pw.println(" p[rocesses]: process state");
7688 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07007689 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
7690 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007691 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07007692 pw.println(" all: dump all activities");
7693 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007694 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07007695 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
7696 pw.println(" a partial substring in a component name, a");
7697 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007698 pw.println(" -a: include all available server state.");
7699 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007700 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007701 } else {
7702 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007703 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007704 }
7705
7706 // Is the caller requesting to dump a particular piece of data?
7707 if (opti < args.length) {
7708 String cmd = args[opti];
7709 opti++;
7710 if ("activities".equals(cmd) || "a".equals(cmd)) {
7711 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007712 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007713 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007714 return;
7715 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
7716 synchronized (this) {
7717 dumpBroadcastsLocked(fd, pw, args, opti, true);
7718 }
7719 return;
7720 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
7721 synchronized (this) {
7722 dumpPendingIntentsLocked(fd, pw, args, opti, true);
7723 }
7724 return;
7725 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
7726 synchronized (this) {
7727 dumpProcessesLocked(fd, pw, args, opti, true);
7728 }
7729 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07007730 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
7731 synchronized (this) {
7732 dumpOomLocked(fd, pw, args, opti, true);
7733 }
7734 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007735 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
7736 synchronized (this) {
7737 dumpProvidersLocked(fd, pw, args, opti, true);
7738 }
7739 return;
7740 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007741 String[] newArgs;
7742 String name;
7743 if (opti >= args.length) {
7744 name = null;
7745 newArgs = EMPTY_STRING_ARRAY;
7746 } else {
7747 name = args[opti];
7748 opti++;
7749 newArgs = new String[args.length - opti];
7750 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
7751 }
7752 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
7753 pw.println("No services match: " + name);
7754 pw.println("Use -h for help.");
7755 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007756 return;
7757 } else if ("services".equals(cmd) || "s".equals(cmd)) {
7758 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007759 dumpServicesLocked(fd, pw, args, opti, true, dumpClient);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007760 }
7761 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07007762 } else {
7763 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007764 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
7765 pw.println("Bad activity command, or no activities match: " + cmd);
7766 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07007767 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08007768 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007770 }
7771
7772 // No piece of data specified, dump everything.
7773 synchronized (this) {
7774 boolean needSep;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007775 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007776 if (needSep) {
7777 pw.println(" ");
7778 }
7779 if (dumpAll) {
7780 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007781 }
7782 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll);
7783 if (needSep) {
7784 pw.println(" ");
7785 }
7786 if (dumpAll) {
7787 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007788 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007789 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007790 if (needSep) {
7791 pw.println(" ");
7792 }
7793 if (dumpAll) {
7794 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007795 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007796 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007797 if (needSep) {
7798 pw.println(" ");
7799 }
7800 if (dumpAll) {
7801 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007802 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007803 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007804 if (needSep) {
7805 pw.println(" ");
7806 }
7807 if (dumpAll) {
7808 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007809 }
7810 dumpProcessesLocked(fd, pw, args, opti, dumpAll);
7811 }
7812 }
7813
7814 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007815 int opti, boolean dumpAll, boolean dumpClient) {
7816 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
7817 pw.println(" Main stack:");
7818 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007819 pw.println(" ");
7820 pw.println(" Running activities (most recent first):");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007821 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007822 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007824 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007825 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
7826 !dumpAll, false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007827 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007828 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007829 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007830 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007831 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
7832 !dumpAll, false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007833 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007834 if (mMainStack.mGoingToSleepActivities.size() > 0) {
7835 pw.println(" ");
7836 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007837 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
7838 !dumpAll, false);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007839 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007840 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007841 pw.println(" ");
7842 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007843 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
7844 !dumpAll, false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007846
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007847 pw.println(" ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007848 if (mMainStack.mPausingActivity != null) {
7849 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
7850 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007851 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007852 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007853 if (dumpAll) {
7854 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
7855 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
7856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007858 if (mRecentTasks.size() > 0) {
7859 pw.println();
7860 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007861
7862 final int N = mRecentTasks.size();
7863 for (int i=0; i<N; i++) {
7864 TaskRecord tr = mRecentTasks.get(i);
7865 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
7866 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007867 if (dumpAll) {
7868 mRecentTasks.get(i).dump(pw, " ");
7869 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007870 }
7871 }
7872
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007873 if (dumpAll) {
7874 pw.println(" ");
7875 pw.println(" mCurTask: " + mCurTask);
7876 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007877
7878 return true;
7879 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07007880
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007881 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7882 int opti, boolean dumpAll) {
7883 boolean needSep = false;
7884 int numPers = 0;
7885
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007886 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
7887
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007888 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
7890 final int NA = procs.size();
7891 for (int ia=0; ia<NA; ia++) {
7892 if (!needSep) {
7893 pw.println(" All known processes:");
7894 needSep = true;
7895 }
7896 ProcessRecord r = procs.valueAt(ia);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007897 pw.print(r.persistent ? " *PERS*" : " *APP*");
7898 pw.print(" UID "); pw.print(procs.keyAt(ia));
7899 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007900 r.dump(pw, " ");
7901 if (r.persistent) {
7902 numPers++;
7903 }
7904 }
7905 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007906 }
7907
7908 if (mLruProcesses.size() > 0) {
7909 if (needSep) pw.println(" ");
7910 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007911 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07007912 dumpProcessOomList(pw, this, mLruProcesses, " ",
7913 "Proc", "PERS", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007914 needSep = true;
7915 }
7916
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007917 if (dumpAll) {
7918 synchronized (mPidsSelfLocked) {
7919 if (mPidsSelfLocked.size() > 0) {
7920 if (needSep) pw.println(" ");
7921 needSep = true;
7922 pw.println(" PID mappings:");
7923 for (int i=0; i<mPidsSelfLocked.size(); i++) {
7924 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
7925 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
7926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927 }
7928 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007929 }
7930
7931 if (mForegroundProcesses.size() > 0) {
7932 if (needSep) pw.println(" ");
7933 needSep = true;
7934 pw.println(" Foreground Processes:");
7935 for (int i=0; i<mForegroundProcesses.size(); i++) {
7936 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
7937 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007938 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007939 }
7940
7941 if (mPersistentStartingProcesses.size() > 0) {
7942 if (needSep) pw.println(" ");
7943 needSep = true;
7944 pw.println(" Persisent processes that are starting:");
7945 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007946 "Starting Norm", "Restarting PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007948
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007949 if (mRemovedProcesses.size() > 0) {
7950 if (needSep) pw.println(" ");
7951 needSep = true;
7952 pw.println(" Processes that are being removed:");
7953 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007954 "Removed Norm", "Removed PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007955 }
7956
7957 if (mProcessesOnHold.size() > 0) {
7958 if (needSep) pw.println(" ");
7959 needSep = true;
7960 pw.println(" Processes that are on old until the system is ready:");
7961 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007962 "OnHold Norm", "OnHold PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007964
Dianne Hackborn287952c2010-09-22 22:34:31 -07007965 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007966
7967 if (mProcessCrashTimes.getMap().size() > 0) {
7968 if (needSep) pw.println(" ");
7969 needSep = true;
7970 pw.println(" Time since processes crashed:");
7971 long now = SystemClock.uptimeMillis();
7972 for (Map.Entry<String, SparseArray<Long>> procs
7973 : mProcessCrashTimes.getMap().entrySet()) {
7974 SparseArray<Long> uids = procs.getValue();
7975 final int N = uids.size();
7976 for (int i=0; i<N; i++) {
7977 pw.print(" Process "); pw.print(procs.getKey());
7978 pw.print(" uid "); pw.print(uids.keyAt(i));
7979 pw.print(": last crashed ");
7980 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07007981 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07007982 }
7983 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007985
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007986 if (mBadProcesses.getMap().size() > 0) {
7987 if (needSep) pw.println(" ");
7988 needSep = true;
7989 pw.println(" Bad processes:");
7990 for (Map.Entry<String, SparseArray<Long>> procs
7991 : mBadProcesses.getMap().entrySet()) {
7992 SparseArray<Long> uids = procs.getValue();
7993 final int N = uids.size();
7994 for (int i=0; i<N; i++) {
7995 pw.print(" Bad process "); pw.print(procs.getKey());
7996 pw.print(" uid "); pw.print(uids.keyAt(i));
7997 pw.print(": crashed at time ");
7998 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007999 }
8000 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008002
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008003 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008004 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackborn860755f2010-06-03 18:47:52 -07008005 if (mHeavyWeightProcess != null) {
8006 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8007 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008008 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008009 if (dumpAll) {
8010 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008011 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008012 pw.println(" mScreenCompatPackages:");
8013 for (Map.Entry<String, Integer> entry
8014 : mCompatModePackages.getPackages().entrySet()) {
8015 String pkg = entry.getKey();
8016 int mode = entry.getValue();
8017 pw.print(" "); pw.print(pkg); pw.print(": ");
8018 pw.print(mode); pw.println();
8019 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008020 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008021 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008022 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8023 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8024 || mOrigWaitForDebugger) {
8025 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8026 + " mDebugTransient=" + mDebugTransient
8027 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8028 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008029 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8030 || mProfileFd != null) {
8031 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8032 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8033 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8034 + mAutoStopProfiler);
8035 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008036 if (mAlwaysFinishActivities || mController != null) {
8037 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8038 + " mController=" + mController);
8039 }
8040 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008041 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008042 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008043 + " mProcessesReady=" + mProcessesReady
8044 + " mSystemReady=" + mSystemReady);
8045 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008046 + " mBooted=" + mBooted
8047 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008048 pw.print(" mLastPowerCheckRealtime=");
8049 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8050 pw.println("");
8051 pw.print(" mLastPowerCheckUptime=");
8052 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8053 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008054 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8055 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008056 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008058
8059 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 }
8061
Dianne Hackborn287952c2010-09-22 22:34:31 -07008062 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
8063 int opti, boolean needSep, boolean dumpAll) {
8064 if (mProcessesToGc.size() > 0) {
8065 if (needSep) pw.println(" ");
8066 needSep = true;
8067 pw.println(" Processes that are waiting to GC:");
8068 long now = SystemClock.uptimeMillis();
8069 for (int i=0; i<mProcessesToGc.size(); i++) {
8070 ProcessRecord proc = mProcessesToGc.get(i);
8071 pw.print(" Process "); pw.println(proc);
8072 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8073 pw.print(", last gced=");
8074 pw.print(now-proc.lastRequestedGc);
8075 pw.print(" ms ago, last lowMem=");
8076 pw.print(now-proc.lastLowMemory);
8077 pw.println(" ms ago");
8078
8079 }
8080 }
8081 return needSep;
8082 }
8083
8084 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8085 int opti, boolean dumpAll) {
8086 boolean needSep = false;
8087
8088 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008089 if (needSep) pw.println(" ");
8090 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008091 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008092 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
8093 pw.print(" CORE_SERVER_ADJ: "); pw.println(ProcessList.CORE_SERVER_ADJ);
8094 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8095 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8096 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8097 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8098 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
8099 pw.print(" SECONDARY_SERVER_ADJ: "); pw.println(ProcessList.SECONDARY_SERVER_ADJ);
8100 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
8101 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
8102 pw.print(" EMPTY_APP_ADJ: "); pw.println(ProcessList.EMPTY_APP_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008103
8104 if (needSep) pw.println(" ");
8105 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008106 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008107 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07008108 "Proc", "PERS", true);
8109 needSep = true;
8110 }
8111
8112 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll);
8113
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008114 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008115 pw.println(" mHomeProcess: " + mHomeProcess);
8116 if (mHeavyWeightProcess != null) {
8117 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8118 }
8119
8120 return true;
8121 }
8122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008123 /**
8124 * There are three ways to call this:
8125 * - no service specified: dump all the services
8126 * - a flattened component name that matched an existing service was specified as the
8127 * first arg: dump that one service
8128 * - the first arg isn't the flattened component name of an existing service:
8129 * dump all services whose component contains the first arg as a substring
8130 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008131 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8132 int opti, boolean dumpAll) {
8133 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008134
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008135 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008136 synchronized (this) {
8137 for (ServiceRecord r1 : mServices.values()) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008138 services.add(r1);
8139 }
8140 }
8141 } else {
8142 ComponentName componentName = name != null
8143 ? ComponentName.unflattenFromString(name) : null;
8144 int objectId = 0;
8145 if (componentName == null) {
8146 // Not a '/' separated full component name; maybe an object ID?
8147 try {
8148 objectId = Integer.parseInt(name, 16);
8149 name = null;
8150 componentName = null;
8151 } catch (RuntimeException e) {
8152 }
8153 }
8154
8155 synchronized (this) {
8156 for (ServiceRecord r1 : mServices.values()) {
8157 if (componentName != null) {
8158 if (r1.name.equals(componentName)) {
8159 services.add(r1);
8160 }
8161 } else if (name != null) {
8162 if (r1.name.flattenToString().contains(name)) {
8163 services.add(r1);
8164 }
8165 } else if (System.identityHashCode(r1) == objectId) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008166 services.add(r1);
8167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008168 }
8169 }
8170 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008171
8172 if (services.size() <= 0) {
8173 return false;
8174 }
8175
8176 boolean needSep = false;
8177 for (int i=0; i<services.size(); i++) {
8178 if (needSep) {
8179 pw.println();
8180 }
8181 needSep = true;
8182 dumpService("", fd, pw, services.get(i), args, dumpAll);
8183 }
8184 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 }
8186
8187 /**
8188 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8189 * there is a thread associated with the service.
8190 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008191 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8192 final ServiceRecord r, String[] args, boolean dumpAll) {
8193 String innerPrefix = prefix + " ";
8194 synchronized (this) {
8195 pw.print(prefix); pw.print("SERVICE ");
8196 pw.print(r.shortName); pw.print(" ");
8197 pw.print(Integer.toHexString(System.identityHashCode(r)));
8198 pw.print(" pid=");
8199 if (r.app != null) pw.println(r.app.pid);
8200 else pw.println("(not running)");
8201 if (dumpAll) {
8202 r.dump(pw, innerPrefix);
8203 }
8204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008205 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008206 pw.print(prefix); pw.println(" Client:");
8207 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008208 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008209 TransferPipe tp = new TransferPipe();
8210 try {
8211 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8212 tp.setBufferPrefix(prefix + " ");
8213 tp.go(fd);
8214 } finally {
8215 tp.kill();
8216 }
8217 } catch (IOException e) {
8218 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008219 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008220 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008221 }
8222 }
8223 }
8224
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008225 static class ItemMatcher {
8226 ArrayList<ComponentName> components;
8227 ArrayList<String> strings;
8228 ArrayList<Integer> objects;
8229 boolean all;
8230
8231 ItemMatcher() {
8232 all = true;
8233 }
8234
8235 void build(String name) {
8236 ComponentName componentName = ComponentName.unflattenFromString(name);
8237 if (componentName != null) {
8238 if (components == null) {
8239 components = new ArrayList<ComponentName>();
8240 }
8241 components.add(componentName);
8242 all = false;
8243 } else {
8244 int objectId = 0;
8245 // Not a '/' separated full component name; maybe an object ID?
8246 try {
8247 objectId = Integer.parseInt(name, 16);
8248 if (objects == null) {
8249 objects = new ArrayList<Integer>();
8250 }
8251 objects.add(objectId);
8252 all = false;
8253 } catch (RuntimeException e) {
8254 // Not an integer; just do string match.
8255 if (strings == null) {
8256 strings = new ArrayList<String>();
8257 }
8258 strings.add(name);
8259 all = false;
8260 }
8261 }
8262 }
8263
8264 int build(String[] args, int opti) {
8265 for (; opti<args.length; opti++) {
8266 String name = args[opti];
8267 if ("--".equals(name)) {
8268 return opti+1;
8269 }
8270 build(name);
8271 }
8272 return opti;
8273 }
8274
8275 boolean match(Object object, ComponentName comp) {
8276 if (all) {
8277 return true;
8278 }
8279 if (components != null) {
8280 for (int i=0; i<components.size(); i++) {
8281 if (components.get(i).equals(comp)) {
8282 return true;
8283 }
8284 }
8285 }
8286 if (objects != null) {
8287 for (int i=0; i<objects.size(); i++) {
8288 if (System.identityHashCode(object) == objects.get(i)) {
8289 return true;
8290 }
8291 }
8292 }
8293 if (strings != null) {
8294 String flat = comp.flattenToString();
8295 for (int i=0; i<strings.size(); i++) {
8296 if (flat.contains(strings.get(i))) {
8297 return true;
8298 }
8299 }
8300 }
8301 return false;
8302 }
8303 }
8304
Dianne Hackborn625ac272010-09-17 18:29:22 -07008305 /**
8306 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008307 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07008308 * - the cmd arg isn't the flattened component name of an existing activity:
8309 * dump all activity whose component contains the cmd as a substring
8310 * - A hex number of the ActivityRecord object instance.
8311 */
8312 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8313 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008314 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008315
8316 if ("all".equals(name)) {
8317 synchronized (this) {
8318 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008319 activities.add(r1);
8320 }
8321 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07008322 } else if ("top".equals(name)) {
8323 synchronized (this) {
8324 final int N = mMainStack.mHistory.size();
8325 if (N > 0) {
8326 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
8327 }
8328 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008329 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008330 ItemMatcher matcher = new ItemMatcher();
8331 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008332
8333 synchronized (this) {
8334 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008335 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008336 activities.add(r1);
8337 }
8338 }
8339 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008340 }
8341
8342 if (activities.size() <= 0) {
8343 return false;
8344 }
8345
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008346 String[] newArgs = new String[args.length - opti];
8347 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8348
Dianne Hackborn30d71892010-12-11 10:37:55 -08008349 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008350 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08008351 for (int i=activities.size()-1; i>=0; i--) {
8352 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008353 if (needSep) {
8354 pw.println();
8355 }
8356 needSep = true;
8357 synchronized (this) {
8358 if (lastTask != r.task) {
8359 lastTask = r.task;
8360 pw.print("TASK "); pw.print(lastTask.affinity);
8361 pw.print(" id="); pw.println(lastTask.taskId);
8362 if (dumpAll) {
8363 lastTask.dump(pw, " ");
8364 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008365 }
8366 }
8367 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008368 }
8369 return true;
8370 }
8371
8372 /**
8373 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
8374 * there is a thread associated with the activity.
8375 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08008376 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008377 final ActivityRecord r, String[] args, boolean dumpAll) {
8378 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08008379 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008380 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
8381 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
8382 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08008383 if (r.app != null) pw.println(r.app.pid);
8384 else pw.println("(not running)");
8385 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008386 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008387 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008388 }
8389 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008390 // flush anything that is already in the PrintWriter since the thread is going
8391 // to write to the file descriptor directly
8392 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07008393 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008394 TransferPipe tp = new TransferPipe();
8395 try {
8396 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(), r,
8397 innerPrefix, args);
8398 tp.go(fd);
8399 } finally {
8400 tp.kill();
8401 }
8402 } catch (IOException e) {
8403 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008404 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008405 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008406 }
8407 }
8408 }
8409
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008410 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8411 int opti, boolean dumpAll) {
8412 boolean needSep = false;
8413
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008414 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008415 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008416 if (mRegisteredReceivers.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008417 pw.println(" Registered Receivers:");
8418 Iterator it = mRegisteredReceivers.values().iterator();
8419 while (it.hasNext()) {
8420 ReceiverList r = (ReceiverList)it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008421 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008422 r.dump(pw, " ");
8423 }
8424 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008425
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008426 pw.println();
8427 pw.println(" Receiver Resolver Table:");
8428 mReceiverResolver.dump(pw, null, " ", null, false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008429 needSep = true;
8430 }
8431
8432 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
8433 || mPendingBroadcast != null) {
8434 if (mParallelBroadcasts.size() > 0) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008435 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008436 pw.println(" Active broadcasts:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008437 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008438 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
8439 pw.println(" Broadcast #" + i + ":");
8440 mParallelBroadcasts.get(i).dump(pw, " ");
8441 }
8442 if (mOrderedBroadcasts.size() > 0) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008443 pw.println();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07008444 pw.println(" Active ordered broadcasts:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008445 }
8446 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
8447 pw.println(" Serialized Broadcast #" + i + ":");
8448 mOrderedBroadcasts.get(i).dump(pw, " ");
8449 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008450 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008451 pw.println(" Pending broadcast:");
8452 if (mPendingBroadcast != null) {
8453 mPendingBroadcast.dump(pw, " ");
8454 } else {
8455 pw.println(" (null)");
8456 }
8457 needSep = true;
8458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008459
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008460 if (needSep) {
8461 pw.println();
8462 }
8463 pw.println(" Historical broadcasts:");
8464 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
8465 BroadcastRecord r = mBroadcastHistory[i];
8466 if (r == null) {
8467 break;
8468 }
8469 if (dumpAll) {
8470 pw.print(" Historical Broadcast #"); pw.print(i); pw.println(":");
8471 r.dump(pw, " ");
8472 } else {
8473 if (i >= 50) {
8474 pw.println(" ...");
Dianne Hackborn12527f92009-11-11 17:39:50 -08008475 break;
8476 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008477 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
Dianne Hackborn12527f92009-11-11 17:39:50 -08008478 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008479 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008480 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008481
8482 if (mStickyBroadcasts != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008483 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008484 pw.println(" Sticky broadcasts:");
8485 StringBuilder sb = new StringBuilder(128);
8486 for (Map.Entry<String, ArrayList<Intent>> ent
8487 : mStickyBroadcasts.entrySet()) {
8488 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008489 if (dumpAll) {
8490 pw.println(":");
8491 ArrayList<Intent> intents = ent.getValue();
8492 final int N = intents.size();
8493 for (int i=0; i<N; i++) {
8494 sb.setLength(0);
8495 sb.append(" Intent: ");
8496 intents.get(i).toShortString(sb, true, false);
8497 pw.println(sb.toString());
8498 Bundle bundle = intents.get(i).getExtras();
8499 if (bundle != null) {
8500 pw.print(" ");
8501 pw.println(bundle.toString());
8502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008504 } else {
8505 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 }
8507 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008508 needSep = true;
8509 }
8510
8511 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008512 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008513 pw.println(" mBroadcastsScheduled=" + mBroadcastsScheduled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008514 pw.println(" mHandler:");
8515 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008516 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008518
8519 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008520 }
8521
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008522 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008523 int opti, boolean dumpAll, boolean dumpClient) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008524 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008526 ItemMatcher matcher = new ItemMatcher();
8527 matcher.build(args, opti);
8528
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008529 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
8530 if (mServices.size() > 0) {
8531 pw.println(" Active services:");
8532 long nowReal = SystemClock.elapsedRealtime();
8533 Iterator<ServiceRecord> it = mServices.values().iterator();
8534 needSep = false;
8535 while (it.hasNext()) {
8536 ServiceRecord r = it.next();
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008537 if (!matcher.match(r, r.name)) {
8538 continue;
8539 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008540 if (needSep) {
8541 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008542 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008543 pw.print(" * "); pw.println(r);
8544 if (dumpAll) {
8545 r.dump(pw, " ");
8546 needSep = true;
8547 } else {
8548 pw.print(" app="); pw.println(r.app);
8549 pw.print(" created=");
8550 TimeUtils.formatDuration(r.createTime, nowReal, pw);
8551 pw.print(" started="); pw.print(r.startRequested);
8552 pw.print(" connections="); pw.println(r.connections.size());
8553 }
8554 if (dumpClient && r.app != null && r.app.thread != null) {
8555 pw.println(" Client:");
8556 pw.flush();
8557 try {
8558 TransferPipe tp = new TransferPipe();
8559 try {
8560 r.app.thread.dumpService(
8561 tp.getWriteFd().getFileDescriptor(), r, args);
8562 tp.setBufferPrefix(" ");
8563 // Short timeout, since blocking here can
8564 // deadlock with the application.
8565 tp.go(fd, 2000);
8566 } finally {
8567 tp.kill();
8568 }
8569 } catch (IOException e) {
8570 pw.println(" Failure while dumping the service: " + e);
8571 } catch (RemoteException e) {
8572 pw.println(" Got a RemoteException while dumping the service");
8573 }
8574 needSep = true;
8575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008576 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008577 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008580 if (mPendingServices.size() > 0) {
8581 if (needSep) pw.println(" ");
8582 pw.println(" Pending services:");
8583 for (int i=0; i<mPendingServices.size(); i++) {
8584 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008585 if (!matcher.match(r, r.name)) {
8586 continue;
8587 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008588 pw.print(" * Pending "); pw.println(r);
8589 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008591 needSep = true;
8592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008594 if (mRestartingServices.size() > 0) {
8595 if (needSep) pw.println(" ");
8596 pw.println(" Restarting services:");
8597 for (int i=0; i<mRestartingServices.size(); i++) {
8598 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008599 if (!matcher.match(r, r.name)) {
8600 continue;
8601 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008602 pw.print(" * Restarting "); pw.println(r);
8603 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008604 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008605 needSep = true;
8606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008607
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008608 if (mStoppingServices.size() > 0) {
8609 if (needSep) pw.println(" ");
8610 pw.println(" Stopping services:");
8611 for (int i=0; i<mStoppingServices.size(); i++) {
8612 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008613 if (!matcher.match(r, r.name)) {
8614 continue;
8615 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008616 pw.print(" * Stopping "); pw.println(r);
8617 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008618 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008619 needSep = true;
8620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008621
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008622 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008623 if (mServiceConnections.size() > 0) {
8624 if (needSep) pw.println(" ");
8625 pw.println(" Connection bindings to services:");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008626 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008627 = mServiceConnections.values().iterator();
8628 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008629 ArrayList<ConnectionRecord> r = it.next();
8630 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008631 ConnectionRecord cr = r.get(i);
8632 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
8633 continue;
8634 }
8635 pw.print(" * "); pw.println(cr);
8636 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008638 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008639 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 }
8641 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008642
8643 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 }
8645
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008646 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8647 int opti, boolean dumpAll) {
8648 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008649
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008650 ItemMatcher matcher = new ItemMatcher();
8651 matcher.build(args, opti);
8652
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008653 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
8654 if (mProvidersByClass.size() > 0) {
8655 if (needSep) pw.println(" ");
8656 pw.println(" Published content providers (by class):");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008657 Iterator<Map.Entry<ComponentName, ContentProviderRecord>> it
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008658 = mProvidersByClass.entrySet().iterator();
8659 while (it.hasNext()) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008660 Map.Entry<ComponentName, ContentProviderRecord> e = it.next();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008661 ContentProviderRecord r = e.getValue();
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008662 ComponentName comp = e.getKey();
8663 String cls = comp.getClassName();
8664 int end = cls.lastIndexOf('.');
8665 if (end > 0 && end < (cls.length()-2)) {
8666 cls = cls.substring(end+1);
8667 }
8668 if (!matcher.match(r, comp)) {
8669 continue;
8670 }
8671 pw.print(" * "); pw.print(cls); pw.print(" (");
8672 pw.print(comp.flattenToShortString()); pw.print(")");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008673 if (dumpAll) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008674 pw.println();
8675 r.dump(pw, " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008676 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008677 pw.print(" * "); pw.print(e.getKey().flattenToShortString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008678 if (r.app != null) {
8679 pw.println(":");
8680 pw.print(" "); pw.println(r.app);
8681 } else {
8682 pw.println();
8683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008685 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008686 needSep = true;
8687 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008688
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008689 if (dumpAll) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008690 if (mProvidersByName.size() > 0) {
8691 pw.println(" ");
8692 pw.println(" Authority to provider mappings:");
Dianne Hackborn860755f2010-06-03 18:47:52 -07008693 Iterator<Map.Entry<String, ContentProviderRecord>> it
8694 = mProvidersByName.entrySet().iterator();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008695 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008696 Map.Entry<String, ContentProviderRecord> e = it.next();
8697 ContentProviderRecord r = e.getValue();
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008698 if (!matcher.match(r, r.name)) {
8699 continue;
8700 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008701 pw.print(" "); pw.print(e.getKey()); pw.print(": ");
8702 pw.println(r);
8703 }
8704 needSep = true;
8705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008707
8708 if (mLaunchingProviders.size() > 0) {
8709 if (needSep) pw.println(" ");
8710 pw.println(" Launching content providers:");
8711 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
8712 pw.print(" Launching #"); pw.print(i); pw.print(": ");
8713 pw.println(mLaunchingProviders.get(i));
8714 }
8715 needSep = true;
8716 }
8717
8718 if (mGrantedUriPermissions.size() > 0) {
8719 pw.println();
8720 pw.println("Granted Uri Permissions:");
8721 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
8722 int uid = mGrantedUriPermissions.keyAt(i);
8723 HashMap<Uri, UriPermission> perms
8724 = mGrantedUriPermissions.valueAt(i);
8725 pw.print(" * UID "); pw.print(uid);
8726 pw.println(" holds:");
8727 for (UriPermission perm : perms.values()) {
8728 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008729 if (dumpAll) {
8730 perm.dump(pw, " ");
8731 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008732 }
8733 }
8734 needSep = true;
8735 }
8736
8737 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008738 }
8739
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008740 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8741 int opti, boolean dumpAll) {
8742 boolean needSep = false;
8743
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008744 if (this.mIntentSenderRecords.size() > 0) {
8745 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
8746 Iterator<WeakReference<PendingIntentRecord>> it
8747 = mIntentSenderRecords.values().iterator();
8748 while (it.hasNext()) {
8749 WeakReference<PendingIntentRecord> ref = it.next();
8750 PendingIntentRecord rec = ref != null ? ref.get(): null;
8751 needSep = true;
8752 if (rec != null) {
8753 pw.print(" * "); pw.println(rec);
8754 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008755 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008756 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008757 } else {
8758 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008759 }
8760 }
8761 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008762
8763 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008764 }
8765
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008766 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
8767 String prefix, String label, boolean complete, boolean brief, boolean client) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008768 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008769 boolean needNL = false;
8770 final String innerPrefix = prefix + " ";
8771 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008772 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008773 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07008774 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008775 if (needNL) {
8776 pw.println(" ");
8777 needNL = false;
8778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779 if (lastTask != r.task) {
8780 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008781 pw.print(prefix);
8782 pw.print(full ? "* " : " ");
8783 pw.println(lastTask);
8784 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008785 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008786 } else if (complete) {
8787 // Complete + brief == give a summary. Isn't that obvious?!?
8788 if (lastTask.intent != null) {
8789 pw.print(prefix); pw.print(" "); pw.println(lastTask.intent);
8790 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008792 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008793 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
8794 pw.print(" #"); pw.print(i); pw.print(": ");
8795 pw.println(r);
8796 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008797 r.dump(pw, innerPrefix);
8798 } else if (complete) {
8799 // Complete + brief == give a summary. Isn't that obvious?!?
8800 pw.print(innerPrefix); pw.println(r.intent);
8801 if (r.app != null) {
8802 pw.print(innerPrefix); pw.println(r.app);
8803 }
8804 }
8805 if (client && r.app != null && r.app.thread != null) {
8806 // flush anything that is already in the PrintWriter since the thread is going
8807 // to write to the file descriptor directly
8808 pw.flush();
8809 try {
8810 TransferPipe tp = new TransferPipe();
8811 try {
8812 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(), r,
8813 innerPrefix, args);
8814 // Short timeout, since blocking here can
8815 // deadlock with the application.
8816 tp.go(fd, 2000);
8817 } finally {
8818 tp.kill();
8819 }
8820 } catch (IOException e) {
8821 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
8822 } catch (RemoteException e) {
8823 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
8824 }
8825 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008827 }
8828 }
8829
Dianne Hackborn09c916b2009-12-08 14:50:51 -08008830 private static String buildOomTag(String prefix, String space, int val, int base) {
8831 if (val == base) {
8832 if (space == null) return prefix;
8833 return prefix + " ";
8834 }
8835 return prefix + "+" + Integer.toString(val-base);
8836 }
8837
8838 private static final int dumpProcessList(PrintWriter pw,
8839 ActivityManagerService service, List list,
Dianne Hackborn287952c2010-09-22 22:34:31 -07008840 String prefix, String normalLabel, String persistentLabel) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008841 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07008842 final int N = list.size()-1;
8843 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008844 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008845 pw.println(String.format("%s%s #%2d: %s",
8846 prefix, (r.persistent ? persistentLabel : normalLabel),
8847 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008848 if (r.persistent) {
8849 numPers++;
8850 }
8851 }
8852 return numPers;
8853 }
8854
Dianne Hackborn287952c2010-09-22 22:34:31 -07008855 private static final void dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07008856 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07008857 String prefix, String normalLabel, String persistentLabel,
8858 boolean inclDetails) {
8859
Dianne Hackborn905577f2011-09-07 18:31:28 -07008860 ArrayList<Pair<ProcessRecord, Integer>> list
8861 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
8862 for (int i=0; i<origList.size(); i++) {
8863 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
8864 }
8865
8866 Comparator<Pair<ProcessRecord, Integer>> comparator
8867 = new Comparator<Pair<ProcessRecord, Integer>>() {
8868 @Override
8869 public int compare(Pair<ProcessRecord, Integer> object1,
8870 Pair<ProcessRecord, Integer> object2) {
8871 if (object1.first.setAdj != object2.first.setAdj) {
8872 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
8873 }
8874 if (object1.second.intValue() != object2.second.intValue()) {
8875 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
8876 }
8877 return 0;
8878 }
8879 };
8880
8881 Collections.sort(list, comparator);
8882
Dianne Hackborn287952c2010-09-22 22:34:31 -07008883 final long curRealtime = SystemClock.elapsedRealtime();
8884 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
8885 final long curUptime = SystemClock.uptimeMillis();
8886 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
8887
8888 final int N = list.size()-1;
8889 for (int i=N; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008890 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008891 String oomAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -07008892 if (r.setAdj >= ProcessList.EMPTY_APP_ADJ) {
8893 oomAdj = buildOomTag("empty", null, r.setAdj, ProcessList.EMPTY_APP_ADJ);
8894 } else if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
8895 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
8896 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
8897 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
8898 } else if (r.setAdj >= ProcessList.SECONDARY_SERVER_ADJ) {
8899 oomAdj = buildOomTag("svc", " ", r.setAdj, ProcessList.SECONDARY_SERVER_ADJ);
8900 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
8901 oomAdj = buildOomTag("bckup", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
8902 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8903 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
8904 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8905 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
8906 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
8907 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
8908 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
8909 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
8910 } else if (r.setAdj >= ProcessList.CORE_SERVER_ADJ) {
8911 oomAdj = buildOomTag("core ", null, r.setAdj, ProcessList.CORE_SERVER_ADJ);
8912 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
8913 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008914 } else {
8915 oomAdj = Integer.toString(r.setAdj);
8916 }
8917 String schedGroup;
8918 switch (r.setSchedGroup) {
8919 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
8920 schedGroup = "B";
8921 break;
8922 case Process.THREAD_GROUP_DEFAULT:
8923 schedGroup = "F";
8924 break;
8925 default:
8926 schedGroup = Integer.toString(r.setSchedGroup);
8927 break;
8928 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07008929 String foreground;
8930 if (r.foregroundActivities) {
8931 foreground = "A";
8932 } else if (r.foregroundServices) {
8933 foreground = "S";
8934 } else {
8935 foreground = " ";
8936 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07008937 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07008938 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackborn905577f2011-09-07 18:31:28 -07008939 N-list.get(i).second, oomAdj, schedGroup, foreground, r.trimMemoryLevel,
Dianne Hackbornce86ba82011-07-13 19:33:41 -07008940 r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07008941 if (r.adjSource != null || r.adjTarget != null) {
8942 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008943 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008944 if (r.adjTarget instanceof ComponentName) {
8945 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
8946 } else if (r.adjTarget != null) {
8947 pw.print(r.adjTarget.toString());
8948 } else {
8949 pw.print("{null}");
8950 }
8951 pw.print("<=");
8952 if (r.adjSource instanceof ProcessRecord) {
8953 pw.print("Proc{");
8954 pw.print(((ProcessRecord)r.adjSource).toShortString());
8955 pw.println("}");
8956 } else if (r.adjSource != null) {
8957 pw.println(r.adjSource.toString());
8958 } else {
8959 pw.println("{null}");
8960 }
8961 }
8962 if (inclDetails) {
8963 pw.print(prefix);
8964 pw.print(" ");
8965 pw.print("oom: max="); pw.print(r.maxAdj);
8966 pw.print(" hidden="); pw.print(r.hiddenAdj);
8967 pw.print(" curRaw="); pw.print(r.curRawAdj);
8968 pw.print(" setRaw="); pw.print(r.setRawAdj);
8969 pw.print(" cur="); pw.print(r.curAdj);
8970 pw.print(" set="); pw.println(r.setAdj);
8971 pw.print(prefix);
8972 pw.print(" ");
8973 pw.print("keeping="); pw.print(r.keeping);
8974 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008975 pw.print(" empty="); pw.print(r.empty);
8976 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008977
8978 if (!r.keeping) {
8979 if (r.lastWakeTime != 0) {
8980 long wtime;
8981 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
8982 synchronized (stats) {
8983 wtime = stats.getProcessWakeTime(r.info.uid,
8984 r.pid, curRealtime);
8985 }
8986 long timeUsed = wtime - r.lastWakeTime;
8987 pw.print(prefix);
8988 pw.print(" ");
8989 pw.print("keep awake over ");
8990 TimeUtils.formatDuration(realtimeSince, pw);
8991 pw.print(" used ");
8992 TimeUtils.formatDuration(timeUsed, pw);
8993 pw.print(" (");
8994 pw.print((timeUsed*100)/realtimeSince);
8995 pw.println("%)");
8996 }
8997 if (r.lastCpuTime != 0) {
8998 long timeUsed = r.curCpuTime - r.lastCpuTime;
8999 pw.print(prefix);
9000 pw.print(" ");
9001 pw.print("run cpu over ");
9002 TimeUtils.formatDuration(uptimeSince, pw);
9003 pw.print(" used ");
9004 TimeUtils.formatDuration(timeUsed, pw);
9005 pw.print(" (");
9006 pw.print((timeUsed*100)/uptimeSince);
9007 pw.println("%)");
9008 }
9009 }
9010 }
9011 }
9012 }
9013
Dianne Hackbornb437e092011-08-05 17:50:29 -07009014 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009015 ArrayList<ProcessRecord> procs;
9016 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009017 if (args != null && args.length > start
9018 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009019 procs = new ArrayList<ProcessRecord>();
9020 int pid = -1;
9021 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009022 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009023 } catch (NumberFormatException e) {
9024
9025 }
9026 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9027 ProcessRecord proc = mLruProcesses.get(i);
9028 if (proc.pid == pid) {
9029 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009030 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009031 procs.add(proc);
9032 }
9033 }
9034 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009035 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009036 return null;
9037 }
9038 } else {
9039 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9040 }
9041 }
9042 return procs;
9043 }
9044
9045 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9046 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009047 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009048 if (procs == null) {
9049 return;
9050 }
9051
9052 long uptime = SystemClock.uptimeMillis();
9053 long realtime = SystemClock.elapsedRealtime();
9054 pw.println("Applications Graphics Acceleration Info:");
9055 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9056
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009057 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9058 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009059 if (r.thread != null) {
9060 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9061 pw.flush();
9062 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009063 TransferPipe tp = new TransferPipe();
9064 try {
9065 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9066 tp.go(fd);
9067 } finally {
9068 tp.kill();
9069 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009070 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009071 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009072 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009073 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009074 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009075 pw.flush();
9076 }
9077 }
9078 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009079 }
9080
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009081 final static class MemItem {
9082 final String label;
9083 final long pss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009084 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009085
9086 public MemItem(String _label, long _pss) {
9087 label = _label;
9088 pss = _pss;
9089 }
9090 }
9091
Dianne Hackbornb437e092011-08-05 17:50:29 -07009092 final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
9093 boolean sort) {
9094 if (sort) {
9095 Collections.sort(items, new Comparator<MemItem>() {
9096 @Override
9097 public int compare(MemItem lhs, MemItem rhs) {
9098 if (lhs.pss < rhs.pss) {
9099 return 1;
9100 } else if (lhs.pss > rhs.pss) {
9101 return -1;
9102 }
9103 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009104 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009105 });
9106 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009107
9108 for (int i=0; i<items.size(); i++) {
9109 MemItem mi = items.get(i);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009110 pw.print(prefix); pw.printf("%7d Kb: ", mi.pss); pw.println(mi.label);
9111 if (mi.subitems != null) {
9112 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9113 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009114 }
9115 }
9116
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009117 final void dumpApplicationMemoryUsage(FileDescriptor fd,
9118 PrintWriter pw, String prefix, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009119 boolean dumpAll = false;
9120
9121 int opti = 0;
9122 while (opti < args.length) {
9123 String opt = args[opti];
9124 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9125 break;
9126 }
9127 opti++;
9128 if ("-a".equals(opt)) {
9129 dumpAll = true;
9130 } else if ("-h".equals(opt)) {
9131 pw.println("meminfo dump options: [-a] [process]");
9132 pw.println(" -a: include all available information for each process.");
9133 pw.println("If [process] is specified it can be the name or ");
9134 pw.println("pid of a specific process to dump.");
9135 return;
9136 } else {
9137 pw.println("Unknown argument: " + opt + "; use -h for help");
9138 }
9139 }
9140
9141 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009142 if (procs == null) {
9143 return;
9144 }
9145
Dianne Hackborn6447ca32009-04-07 19:50:08 -07009146 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147 long uptime = SystemClock.uptimeMillis();
9148 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -07009149
9150 if (procs.size() == 1 || isCheckinRequest) {
9151 dumpAll = true;
9152 }
9153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009154 if (isCheckinRequest) {
9155 // short checkin version
9156 pw.println(uptime + "," + realtime);
9157 pw.flush();
9158 } else {
9159 pw.println("Applications Memory Usage (kB):");
9160 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9161 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009162
Dianne Hackbornb437e092011-08-05 17:50:29 -07009163 String[] innerArgs = new String[args.length-opti];
9164 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
9165
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009166 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
9167 long nativePss=0, dalvikPss=0, otherPss=0;
9168 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
9169
Dianne Hackbornb437e092011-08-05 17:50:29 -07009170 final int[] oomAdj = new int[] {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009171 ProcessList.SYSTEM_ADJ, ProcessList.CORE_SERVER_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9172 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9173 ProcessList.BACKUP_APP_ADJ, ProcessList.SECONDARY_SERVER_ADJ, ProcessList.HOME_APP_ADJ, ProcessList.EMPTY_APP_ADJ
Dianne Hackbornb437e092011-08-05 17:50:29 -07009174 };
9175 final String[] oomLabel = new String[] {
9176 "System", "Persistent", "Foreground",
9177 "Visible", "Perceptible", "Heavy Weight",
9178 "Backup", "Services", "Home", "Background"
9179 };
9180 long oomPss[] = new long[oomLabel.length];
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009181 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])new ArrayList[oomLabel.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -07009182
9183 long totalPss = 0;
9184
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009185 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9186 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009187 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009188 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009189 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
9190 pw.flush();
9191 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009192 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009193 if (dumpAll) {
9194 try {
9195 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
9196 } catch (RemoteException e) {
9197 if (!isCheckinRequest) {
9198 pw.println("Got RemoteException!");
9199 pw.flush();
9200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009201 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009202 } else {
9203 mi = new Debug.MemoryInfo();
9204 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009205 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009206
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009207 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009208 long myTotalPss = mi.getTotalPss();
9209 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009210 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
9211 myTotalPss);
9212 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009213
9214 nativePss += mi.nativePss;
9215 dalvikPss += mi.dalvikPss;
9216 otherPss += mi.otherPss;
9217 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
9218 long mem = mi.getOtherPss(j);
9219 miscPss[j] += mem;
9220 otherPss -= mem;
9221 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009222
9223 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
9224 if (r.setAdj <= oomAdj[oomIndex] || oomIndex == (oomPss.length-1)) {
9225 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009226 if (oomProcs[oomIndex] == null) {
9227 oomProcs[oomIndex] = new ArrayList<MemItem>();
9228 }
9229 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009230 break;
9231 }
9232 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009234 }
9235 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009236
9237 if (!isCheckinRequest && procs.size() > 1) {
9238 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
9239
9240 catMems.add(new MemItem("Native", nativePss));
9241 catMems.add(new MemItem("Dalvik", dalvikPss));
9242 catMems.add(new MemItem("Unknown", otherPss));
9243 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
9244 catMems.add(new MemItem(Debug.MemoryInfo.getOtherLabel(j), miscPss[j]));
9245 }
9246
Dianne Hackbornb437e092011-08-05 17:50:29 -07009247 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
9248 for (int j=0; j<oomPss.length; j++) {
9249 if (oomPss[j] != 0) {
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009250 MemItem item = new MemItem(oomLabel[j], oomPss[j]);
9251 item.subitems = oomProcs[j];
9252 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009253 }
9254 }
9255
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009256 pw.println();
9257 pw.println("Total PSS by process:");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009258 dumpMemItems(pw, " ", procMems, true);
9259 pw.println();
9260 pw.println("Total PSS by OOM adjustment:");
9261 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009262 pw.println();
9263 pw.println("Total PSS by category:");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009264 dumpMemItems(pw, " ", catMems, true);
9265 pw.println();
9266 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" Kb");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009268 }
9269
9270 /**
9271 * Searches array of arguments for the specified string
9272 * @param args array of argument strings
9273 * @param value value to search for
9274 * @return true if the value is contained in the array
9275 */
9276 private static boolean scanArgs(String[] args, String value) {
9277 if (args != null) {
9278 for (String arg : args) {
9279 if (value.equals(arg)) {
9280 return true;
9281 }
9282 }
9283 }
9284 return false;
9285 }
9286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009287 private final void killServicesLocked(ProcessRecord app,
9288 boolean allowRestart) {
9289 // Report disconnected services.
9290 if (false) {
9291 // XXX we are letting the client link to the service for
9292 // death notifications.
9293 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07009294 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009295 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07009296 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009298 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009299 = r.connections.values().iterator();
9300 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009301 ArrayList<ConnectionRecord> cl = jt.next();
9302 for (int i=0; i<cl.size(); i++) {
9303 ConnectionRecord c = cl.get(i);
9304 if (c.binding.client != app) {
9305 try {
9306 //c.conn.connected(r.className, null);
9307 } catch (Exception e) {
9308 // todo: this should be asynchronous!
9309 Slog.w(TAG, "Exception thrown disconnected servce "
9310 + r.shortName
9311 + " from app " + app.processName, e);
9312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009313 }
9314 }
9315 }
9316 }
9317 }
9318 }
9319 }
9320
9321 // Clean up any connections this application has to other services.
9322 if (app.connections.size() > 0) {
9323 Iterator<ConnectionRecord> it = app.connections.iterator();
9324 while (it.hasNext()) {
9325 ConnectionRecord r = it.next();
9326 removeConnectionLocked(r, app, null);
9327 }
9328 }
9329 app.connections.clear();
9330
9331 if (app.services.size() != 0) {
9332 // Any services running in the application need to be placed
9333 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07009334 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009335 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07009336 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 synchronized (sr.stats.getBatteryStats()) {
9338 sr.stats.stopLaunchedLocked();
9339 }
9340 sr.app = null;
9341 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009342 if (mStoppingServices.remove(sr)) {
9343 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
9344 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009345
9346 boolean hasClients = sr.bindings.size() > 0;
9347 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009348 Iterator<IntentBindRecord> bindings
9349 = sr.bindings.values().iterator();
9350 while (bindings.hasNext()) {
9351 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -08009352 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353 + ": shouldUnbind=" + b.hasBound);
9354 b.binder = null;
9355 b.requested = b.received = b.hasBound = false;
9356 }
9357 }
9358
Dianne Hackborn070783f2010-12-29 16:46:28 -08009359 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
9360 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009361 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009362 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -08009363 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009364 sr.crashCount, sr.shortName, app.pid);
9365 bringDownServiceLocked(sr, true);
9366 } else if (!allowRestart) {
9367 bringDownServiceLocked(sr, true);
9368 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009369 boolean canceled = scheduleServiceRestartLocked(sr, true);
9370
9371 // Should the service remain running? Note that in the
9372 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -07009373 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009374 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
9375 if (sr.pendingStarts.size() == 0) {
9376 sr.startRequested = false;
9377 if (!hasClients) {
9378 // Whoops, no reason to restart!
9379 bringDownServiceLocked(sr, true);
9380 }
9381 }
9382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009383 }
9384 }
9385
9386 if (!allowRestart) {
9387 app.services.clear();
9388 }
9389 }
9390
Dianne Hackbornde42bb62009-08-05 12:26:15 -07009391 // Make sure we have no more records on the stopping list.
9392 int i = mStoppingServices.size();
9393 while (i > 0) {
9394 i--;
9395 ServiceRecord sr = mStoppingServices.get(i);
9396 if (sr.app == app) {
9397 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009398 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -07009399 }
9400 }
9401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009402 app.executingServices.clear();
9403 }
9404
9405 private final void removeDyingProviderLocked(ProcessRecord proc,
9406 ContentProviderRecord cpr) {
9407 synchronized (cpr) {
9408 cpr.launchingApp = null;
9409 cpr.notifyAll();
9410 }
9411
9412 mProvidersByClass.remove(cpr.info.name);
9413 String names[] = cpr.info.authority.split(";");
9414 for (int j = 0; j < names.length; j++) {
9415 mProvidersByName.remove(names[j]);
9416 }
9417
9418 Iterator<ProcessRecord> cit = cpr.clients.iterator();
9419 while (cit.hasNext()) {
9420 ProcessRecord capp = cit.next();
9421 if (!capp.persistent && capp.thread != null
9422 && capp.pid != 0
9423 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07009424 Slog.i(TAG, "Kill " + capp.processName
9425 + " (pid " + capp.pid + "): provider " + cpr.info.name
9426 + " in dying process " + proc.processName);
9427 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
9428 capp.processName, capp.setAdj, "dying provider " + proc.processName);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07009429 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009430 }
9431 }
9432
9433 mLaunchingProviders.remove(cpr);
9434 }
9435
9436 /**
9437 * Main code for cleaning up a process when it has gone away. This is
9438 * called both as a result of the process dying, or directly when stopping
9439 * a process when running in single process mode.
9440 */
9441 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07009442 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009443 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009444 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009445 }
9446
Dianne Hackborn36124872009-10-08 16:22:03 -07009447 mProcessesToGc.remove(app);
9448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009449 // Dismiss any open dialogs.
9450 if (app.crashDialog != null) {
9451 app.crashDialog.dismiss();
9452 app.crashDialog = null;
9453 }
9454 if (app.anrDialog != null) {
9455 app.anrDialog.dismiss();
9456 app.anrDialog = null;
9457 }
9458 if (app.waitDialog != null) {
9459 app.waitDialog.dismiss();
9460 app.waitDialog = null;
9461 }
9462
9463 app.crashing = false;
9464 app.notResponding = false;
9465
9466 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07009467 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009468 app.thread = null;
9469 app.forcingToForeground = null;
9470 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009471 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07009472 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009473 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009474
Dianne Hackborn130b0d22011-07-26 22:07:48 -07009475 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476
9477 boolean restart = false;
9478
9479 int NL = mLaunchingProviders.size();
9480
9481 // Remove published content providers.
9482 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07009483 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009484 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07009485 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486 cpr.provider = null;
9487 cpr.app = null;
9488
9489 // See if someone is waiting for this provider... in which
9490 // case we don't remove it, but just let it restart.
9491 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07009492 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009493 for (; i<NL; i++) {
9494 if (mLaunchingProviders.get(i) == cpr) {
9495 restart = true;
9496 break;
9497 }
9498 }
9499 } else {
9500 i = NL;
9501 }
9502
9503 if (i >= NL) {
9504 removeDyingProviderLocked(app, cpr);
9505 NL = mLaunchingProviders.size();
9506 }
9507 }
9508 app.pubProviders.clear();
9509 }
9510
Dianne Hackbornf670ef72009-11-16 13:59:16 -08009511 // Take care of any launching providers waiting for this process.
9512 if (checkAppInLaunchingProvidersLocked(app, false)) {
9513 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009514 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08009515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009516 // Unregister from connected content providers.
9517 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07009518 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009519 while (it.hasNext()) {
9520 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
9521 cpr.clients.remove(app);
9522 }
9523 app.conProviders.clear();
9524 }
9525
Dianne Hackbornde42bb62009-08-05 12:26:15 -07009526 // At this point there may be remaining entries in mLaunchingProviders
9527 // where we were the only one waiting, so they are no longer of use.
9528 // Look for these and clean up if found.
9529 // XXX Commented out for now. Trying to figure out a way to reproduce
9530 // the actual situation to identify what is actually going on.
9531 if (false) {
9532 for (int i=0; i<NL; i++) {
9533 ContentProviderRecord cpr = (ContentProviderRecord)
9534 mLaunchingProviders.get(i);
9535 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
9536 synchronized (cpr) {
9537 cpr.launchingApp = null;
9538 cpr.notifyAll();
9539 }
9540 }
9541 }
9542 }
9543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009544 skipCurrentReceiverLocked(app);
9545
9546 // Unregister any receivers.
9547 if (app.receivers.size() > 0) {
9548 Iterator<ReceiverList> it = app.receivers.iterator();
9549 while (it.hasNext()) {
9550 removeReceiverLocked(it.next());
9551 }
9552 app.receivers.clear();
9553 }
9554
Christopher Tate181fafa2009-05-14 11:12:14 -07009555 // If the app is undergoing backup, tell the backup manager about it
9556 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009557 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -07009558 try {
9559 IBackupManager bm = IBackupManager.Stub.asInterface(
9560 ServiceManager.getService(Context.BACKUP_SERVICE));
9561 bm.agentDisconnected(app.info.packageName);
9562 } catch (RemoteException e) {
9563 // can't happen; backup manager is local
9564 }
9565 }
9566
Jeff Sharkey287bd832011-05-28 19:36:26 -07009567 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569 // If the caller is restarting this app, then leave it in its
9570 // current lists and let the caller take care of it.
9571 if (restarting) {
9572 return;
9573 }
9574
9575 if (!app.persistent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009576 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009577 "Removing non-persistent process during cleanup: " + app);
9578 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07009579 if (mHeavyWeightProcess == app) {
9580 mHeavyWeightProcess = null;
9581 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
9582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009583 } else if (!app.removed) {
9584 // This app is persistent, so we need to keep its record around.
9585 // If it is not already on the pending app list, add it there
9586 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009587 if (mPersistentStartingProcesses.indexOf(app) < 0) {
9588 mPersistentStartingProcesses.add(app);
9589 restart = true;
9590 }
9591 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009592 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
9593 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009594 mProcessesOnHold.remove(app);
9595
The Android Open Source Project4df24232009-03-05 14:34:35 -08009596 if (app == mHomeProcess) {
9597 mHomeProcess = null;
9598 }
9599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009600 if (restart) {
9601 // We have components that still need to be running in the
9602 // process, so re-launch it.
9603 mProcessNames.put(app.processName, app.info.uid, app);
9604 startProcessLocked(app, "restart", app.processName);
9605 } else if (app.pid > 0 && app.pid != MY_PID) {
9606 // Goodbye!
9607 synchronized (mPidsSelfLocked) {
9608 mPidsSelfLocked.remove(app.pid);
9609 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
9610 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009611 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009612 }
9613 }
9614
Dianne Hackbornf670ef72009-11-16 13:59:16 -08009615 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
9616 // Look through the content providers we are waiting to have launched,
9617 // and if any run in this process then either schedule a restart of
9618 // the process or kill the client waiting for it if this process has
9619 // gone bad.
9620 int NL = mLaunchingProviders.size();
9621 boolean restart = false;
9622 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07009623 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08009624 if (cpr.launchingApp == app) {
9625 if (!alwaysBad && !app.bad) {
9626 restart = true;
9627 } else {
9628 removeDyingProviderLocked(app, cpr);
9629 NL = mLaunchingProviders.size();
9630 }
9631 }
9632 }
9633 return restart;
9634 }
9635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009636 // =========================================================
9637 // SERVICES
9638 // =========================================================
9639
9640 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
9641 ActivityManager.RunningServiceInfo info =
9642 new ActivityManager.RunningServiceInfo();
9643 info.service = r.name;
9644 if (r.app != null) {
9645 info.pid = r.app.pid;
9646 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -07009647 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009648 info.process = r.processName;
9649 info.foreground = r.isForeground;
9650 info.activeSince = r.createTime;
9651 info.started = r.startRequested;
9652 info.clientCount = r.connections.size();
9653 info.crashCount = r.crashCount;
9654 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07009655 if (r.isForeground) {
9656 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
9657 }
9658 if (r.startRequested) {
9659 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
9660 }
Dan Egnor42471dd2010-01-07 17:25:22 -08009661 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -07009662 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
9663 }
9664 if (r.app != null && r.app.persistent) {
9665 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
9666 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009667
9668 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
9669 for (int i=0; i<connl.size(); i++) {
9670 ConnectionRecord conn = connl.get(i);
9671 if (conn.clientLabel != 0) {
9672 info.clientPackage = conn.binding.client.info.packageName;
9673 info.clientLabel = conn.clientLabel;
9674 return info;
9675 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009676 }
9677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009678 return info;
9679 }
9680
9681 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
9682 int flags) {
9683 synchronized (this) {
9684 ArrayList<ActivityManager.RunningServiceInfo> res
9685 = new ArrayList<ActivityManager.RunningServiceInfo>();
9686
9687 if (mServices.size() > 0) {
9688 Iterator<ServiceRecord> it = mServices.values().iterator();
9689 while (it.hasNext() && res.size() < maxNum) {
9690 res.add(makeRunningServiceInfoLocked(it.next()));
9691 }
9692 }
9693
9694 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
9695 ServiceRecord r = mRestartingServices.get(i);
9696 ActivityManager.RunningServiceInfo info =
9697 makeRunningServiceInfoLocked(r);
9698 info.restarting = r.nextRestartTime;
9699 res.add(info);
9700 }
9701
9702 return res;
9703 }
9704 }
9705
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009706 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
9707 synchronized (this) {
9708 ServiceRecord r = mServices.get(name);
9709 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009710 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
9711 for (int i=0; i<conn.size(); i++) {
9712 if (conn.get(i).clientIntent != null) {
9713 return conn.get(i).clientIntent;
9714 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009715 }
9716 }
9717 }
9718 }
9719 return null;
9720 }
9721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009722 private final ServiceRecord findServiceLocked(ComponentName name,
9723 IBinder token) {
9724 ServiceRecord r = mServices.get(name);
9725 return r == token ? r : null;
9726 }
9727
9728 private final class ServiceLookupResult {
9729 final ServiceRecord record;
9730 final String permission;
9731
9732 ServiceLookupResult(ServiceRecord _record, String _permission) {
9733 record = _record;
9734 permission = _permission;
9735 }
9736 };
9737
9738 private ServiceLookupResult findServiceLocked(Intent service,
9739 String resolvedType) {
9740 ServiceRecord r = null;
9741 if (service.getComponent() != null) {
9742 r = mServices.get(service.getComponent());
9743 }
9744 if (r == null) {
9745 Intent.FilterComparison filter = new Intent.FilterComparison(service);
9746 r = mServicesByIntent.get(filter);
9747 }
9748
9749 if (r == null) {
9750 try {
9751 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009752 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009753 service, resolvedType, 0);
9754 ServiceInfo sInfo =
9755 rInfo != null ? rInfo.serviceInfo : null;
9756 if (sInfo == null) {
9757 return null;
9758 }
9759
9760 ComponentName name = new ComponentName(
9761 sInfo.applicationInfo.packageName, sInfo.name);
9762 r = mServices.get(name);
9763 } catch (RemoteException ex) {
9764 // pm is in same process, this will never happen.
9765 }
9766 }
9767 if (r != null) {
9768 int callingPid = Binder.getCallingPid();
9769 int callingUid = Binder.getCallingUid();
9770 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009771 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009772 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009773 if (!r.exported) {
9774 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
9775 + " from pid=" + callingPid
9776 + ", uid=" + callingUid
9777 + " that is not exported from uid " + r.appInfo.uid);
9778 return new ServiceLookupResult(null, "not exported from uid "
9779 + r.appInfo.uid);
9780 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08009781 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009782 + " from pid=" + callingPid
9783 + ", uid=" + callingUid
9784 + " requires " + r.permission);
9785 return new ServiceLookupResult(null, r.permission);
9786 }
9787 return new ServiceLookupResult(r, null);
9788 }
9789 return null;
9790 }
9791
9792 private class ServiceRestarter implements Runnable {
9793 private ServiceRecord mService;
9794
9795 void setService(ServiceRecord service) {
9796 mService = service;
9797 }
9798
9799 public void run() {
9800 synchronized(ActivityManagerService.this) {
9801 performServiceRestartLocked(mService);
9802 }
9803 }
9804 }
9805
9806 private ServiceLookupResult retrieveServiceLocked(Intent service,
9807 String resolvedType, int callingPid, int callingUid) {
9808 ServiceRecord r = null;
9809 if (service.getComponent() != null) {
9810 r = mServices.get(service.getComponent());
9811 }
9812 Intent.FilterComparison filter = new Intent.FilterComparison(service);
9813 r = mServicesByIntent.get(filter);
9814 if (r == null) {
9815 try {
9816 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009817 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -07009818 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009819 ServiceInfo sInfo =
9820 rInfo != null ? rInfo.serviceInfo : null;
9821 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009822 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009823 ": not found");
9824 return null;
9825 }
9826
9827 ComponentName name = new ComponentName(
9828 sInfo.applicationInfo.packageName, sInfo.name);
9829 r = mServices.get(name);
9830 if (r == null) {
9831 filter = new Intent.FilterComparison(service.cloneFilter());
9832 ServiceRestarter res = new ServiceRestarter();
9833 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
9834 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
9835 synchronized (stats) {
9836 ss = stats.getServiceStatsLocked(
9837 sInfo.applicationInfo.uid, sInfo.packageName,
9838 sInfo.name);
9839 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -08009840 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009841 res.setService(r);
9842 mServices.put(name, r);
9843 mServicesByIntent.put(filter, r);
9844
9845 // Make sure this component isn't in the pending list.
9846 int N = mPendingServices.size();
9847 for (int i=0; i<N; i++) {
9848 ServiceRecord pr = mPendingServices.get(i);
9849 if (pr.name.equals(name)) {
9850 mPendingServices.remove(i);
9851 i--;
9852 N--;
9853 }
9854 }
9855 }
9856 } catch (RemoteException ex) {
9857 // pm is in same process, this will never happen.
9858 }
9859 }
9860 if (r != null) {
9861 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009862 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009863 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009864 if (!r.exported) {
9865 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
9866 + " from pid=" + callingPid
9867 + ", uid=" + callingUid
9868 + " that is not exported from uid " + r.appInfo.uid);
9869 return new ServiceLookupResult(null, "not exported from uid "
9870 + r.appInfo.uid);
9871 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08009872 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009873 + " from pid=" + callingPid
9874 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009875 + " requires " + r.permission);
9876 return new ServiceLookupResult(null, r.permission);
9877 }
9878 return new ServiceLookupResult(r, null);
9879 }
9880 return null;
9881 }
9882
Dianne Hackborn287952c2010-09-22 22:34:31 -07009883 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
9884 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
9885 + why + " of " + r + " in app " + r.app);
9886 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
9887 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009888 long now = SystemClock.uptimeMillis();
9889 if (r.executeNesting == 0 && r.app != null) {
9890 if (r.app.executingServices.size() == 0) {
9891 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
9892 msg.obj = r.app;
9893 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
9894 }
9895 r.app.executingServices.add(r);
9896 }
9897 r.executeNesting++;
9898 r.executingStart = now;
9899 }
9900
9901 private final void sendServiceArgsLocked(ServiceRecord r,
9902 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009903 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009904 if (N == 0) {
9905 return;
9906 }
9907
Dianne Hackborn39792d22010-08-19 18:01:52 -07009908 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009909 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -07009910 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009911 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
9912 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -08009913 if (si.intent == null && N > 1) {
9914 // If somehow we got a dummy null intent in the middle,
9915 // then skip it. DO NOT skip a null intent when it is
9916 // the only one in the list -- this is to support the
9917 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009918 continue;
9919 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07009920 si.deliveredTime = SystemClock.uptimeMillis();
9921 r.deliveredStarts.add(si);
9922 si.deliveryCount++;
Dianne Hackborn3a28f222011-03-01 12:25:54 -08009923 if (si.targetPermissionUid >= 0 && si.intent != null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07009924 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -07009925 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07009926 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009927 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009928 if (!oomAdjusted) {
9929 oomAdjusted = true;
9930 updateOomAdjLocked(r.app);
9931 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009932 int flags = 0;
9933 if (si.deliveryCount > 0) {
9934 flags |= Service.START_FLAG_RETRY;
9935 }
9936 if (si.doneExecutingCount > 0) {
9937 flags |= Service.START_FLAG_REDELIVERY;
9938 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07009939 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009940 } catch (RemoteException e) {
9941 // Remote process gone... we'll let the normal cleanup take
9942 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009943 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009944 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009945 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009946 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009947 break;
9948 }
9949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009950 }
9951
9952 private final boolean requestServiceBindingLocked(ServiceRecord r,
9953 IntentBindRecord i, boolean rebind) {
9954 if (r.app == null || r.app.thread == null) {
9955 // If service is not currently running, can't yet bind.
9956 return false;
9957 }
9958 if ((!i.requested || rebind) && i.apps.size() > 0) {
9959 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009960 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009961 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
9962 if (!rebind) {
9963 i.requested = true;
9964 }
9965 i.hasBound = true;
9966 i.doRebind = false;
9967 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009968 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009969 return false;
9970 }
9971 }
9972 return true;
9973 }
9974
9975 private final void requestServiceBindingsLocked(ServiceRecord r) {
9976 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
9977 while (bindings.hasNext()) {
9978 IntentBindRecord i = bindings.next();
9979 if (!requestServiceBindingLocked(r, i, false)) {
9980 break;
9981 }
9982 }
9983 }
9984
9985 private final void realStartServiceLocked(ServiceRecord r,
9986 ProcessRecord app) throws RemoteException {
9987 if (app.thread == null) {
9988 throw new RemoteException();
9989 }
9990
9991 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -07009992 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009993
9994 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009995 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009996 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009997
9998 boolean created = false;
9999 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010000 mStringBuilder.setLength(0);
10001 r.intent.getIntent().toShortString(mStringBuilder, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010002 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010003 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010004 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010005 synchronized (r.stats.getBatteryStats()) {
10006 r.stats.startLaunchedLocked();
10007 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010008 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010009 app.thread.scheduleCreateService(r, r.serviceInfo,
10010 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010011 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010012 created = true;
10013 } finally {
10014 if (!created) {
10015 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010016 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010017 }
10018 }
10019
10020 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010021
10022 // If the service is in the started state, and there are no
10023 // pending arguments, then fake up one so its onStartCommand() will
10024 // be called.
10025 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010026 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
10027 null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010028 }
10029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010030 sendServiceArgsLocked(r, true);
10031 }
10032
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010033 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10034 boolean allowCancel) {
10035 boolean canceled = false;
10036
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010037 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010038 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010039 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010040
Dianne Hackborn070783f2010-12-29 16:46:28 -080010041 if ((r.serviceInfo.applicationInfo.flags
10042 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10043 minDuration /= 4;
10044 }
10045
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010046 // Any delivered but not yet finished starts should be put back
10047 // on the pending list.
10048 final int N = r.deliveredStarts.size();
10049 if (N > 0) {
10050 for (int i=N-1; i>=0; i--) {
10051 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070010052 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010053 if (si.intent == null) {
10054 // We'll generate this again if needed.
10055 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
10056 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
10057 r.pendingStarts.add(0, si);
10058 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
10059 dur *= 2;
10060 if (minDuration < dur) minDuration = dur;
10061 if (resetTime < dur) resetTime = dur;
10062 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010063 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010064 + r.name);
10065 canceled = true;
10066 }
10067 }
10068 r.deliveredStarts.clear();
10069 }
10070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010071 r.totalRestartCount++;
10072 if (r.restartDelay == 0) {
10073 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010074 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010075 } else {
10076 // If it has been a "reasonably long time" since the service
10077 // was started, then reset our restart duration back to
10078 // the beginning, so we don't infinitely increase the duration
10079 // on a service that just occasionally gets killed (which is
10080 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010081 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010082 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010083 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010084 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080010085 if ((r.serviceInfo.applicationInfo.flags
10086 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10087 // Services in peristent processes will restart much more
10088 // quickly, since they are pretty important. (Think SystemUI).
10089 r.restartDelay += minDuration/2;
10090 } else {
10091 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
10092 if (r.restartDelay < minDuration) {
10093 r.restartDelay = minDuration;
10094 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010096 }
10097 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010098
10099 r.nextRestartTime = now + r.restartDelay;
10100
10101 // Make sure that we don't end up restarting a bunch of services
10102 // all at the same time.
10103 boolean repeat;
10104 do {
10105 repeat = false;
10106 for (int i=mRestartingServices.size()-1; i>=0; i--) {
10107 ServiceRecord r2 = mRestartingServices.get(i);
10108 if (r2 != r && r.nextRestartTime
10109 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
10110 && r.nextRestartTime
10111 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
10112 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
10113 r.restartDelay = r.nextRestartTime - now;
10114 repeat = true;
10115 break;
10116 }
10117 }
10118 } while (repeat);
10119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010120 if (!mRestartingServices.contains(r)) {
10121 mRestartingServices.add(r);
10122 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010123
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010124 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010126 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010127 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010128 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010129 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010130 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080010131 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010132 r.shortName, r.restartDelay);
10133
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010134 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010135 }
10136
10137 final void performServiceRestartLocked(ServiceRecord r) {
10138 if (!mRestartingServices.contains(r)) {
10139 return;
10140 }
10141 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
10142 }
10143
10144 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
10145 if (r.restartDelay == 0) {
10146 return false;
10147 }
10148 r.resetRestartCounter();
10149 mRestartingServices.remove(r);
10150 mHandler.removeCallbacks(r.restarter);
10151 return true;
10152 }
10153
10154 private final boolean bringUpServiceLocked(ServiceRecord r,
10155 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010156 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010157 //r.dump(" ");
10158
Dianne Hackborn36124872009-10-08 16:22:03 -070010159 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010160 sendServiceArgsLocked(r, false);
10161 return true;
10162 }
10163
10164 if (!whileRestarting && r.restartDelay > 0) {
10165 // If waiting for a restart, then do nothing.
10166 return true;
10167 }
10168
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010169 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010170
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010171 // We are now bringing the service up, so no longer in the
10172 // restarting state.
10173 mRestartingServices.remove(r);
10174
Dianne Hackborne7f97212011-02-24 14:40:20 -080010175 // Service is now being launched, its package can't be stopped.
10176 try {
10177 AppGlobals.getPackageManager().setPackageStoppedState(
10178 r.packageName, false);
10179 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010180 } catch (IllegalArgumentException e) {
10181 Slog.w(TAG, "Failed trying to unstop package "
10182 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010183 }
10184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010185 final String appName = r.processName;
10186 ProcessRecord app = getProcessRecordLocked(appName, r.appInfo.uid);
10187 if (app != null && app.thread != null) {
10188 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010189 app.addPackage(r.appInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010190 realStartServiceLocked(r, app);
10191 return true;
10192 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010193 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010194 }
10195
10196 // If a dead object exception was thrown -- fall through to
10197 // restart the application.
10198 }
10199
Dianne Hackborn36124872009-10-08 16:22:03 -070010200 // Not running -- get it started, and enqueue this service record
10201 // to be executed when the app comes up.
10202 if (startProcessLocked(appName, r.appInfo, true, intentFlags,
10203 "service", r.name, false) == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010204 Slog.w(TAG, "Unable to launch app "
Dianne Hackborn36124872009-10-08 16:22:03 -070010205 + r.appInfo.packageName + "/"
10206 + r.appInfo.uid + " for service "
10207 + r.intent.getIntent() + ": process is bad");
10208 bringDownServiceLocked(r, true);
10209 return false;
10210 }
10211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010212 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010213 mPendingServices.add(r);
10214 }
Dianne Hackborn36124872009-10-08 16:22:03 -070010215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010216 return true;
10217 }
10218
10219 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010220 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010221 //r.dump(" ");
10222
10223 // Does it still need to run?
10224 if (!force && r.startRequested) {
10225 return;
10226 }
10227 if (r.connections.size() > 0) {
10228 if (!force) {
10229 // XXX should probably keep a count of the number of auto-create
10230 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010231 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010232 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010233 ArrayList<ConnectionRecord> cr = it.next();
10234 for (int i=0; i<cr.size(); i++) {
10235 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
10236 return;
10237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010238 }
10239 }
10240 }
10241
10242 // Report to all of the connections that the service is no longer
10243 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010244 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010245 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010246 ArrayList<ConnectionRecord> c = it.next();
10247 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010248 ConnectionRecord cr = c.get(i);
10249 // There is still a connection to the service that is
10250 // being brought down. Mark it as dead.
10251 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010252 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010253 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010254 } catch (Exception e) {
10255 Slog.w(TAG, "Failure disconnecting service " + r.name +
10256 " to connection " + c.get(i).conn.asBinder() +
10257 " (in " + c.get(i).binding.client.processName + ")", e);
10258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010259 }
10260 }
10261 }
10262
10263 // Tell the service that it has been unbound.
10264 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
10265 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
10266 while (it.hasNext()) {
10267 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010268 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010269 + ": hasBound=" + ibr.hasBound);
10270 if (r.app != null && r.app.thread != null && ibr.hasBound) {
10271 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010272 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010273 updateOomAdjLocked(r.app);
10274 ibr.hasBound = false;
10275 r.app.thread.scheduleUnbindService(r,
10276 ibr.intent.getIntent());
10277 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010278 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010279 + r.shortName, e);
10280 serviceDoneExecutingLocked(r, true);
10281 }
10282 }
10283 }
10284 }
10285
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010286 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010287 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010288 System.identityHashCode(r), r.shortName,
10289 (r.app != null) ? r.app.pid : -1);
10290
10291 mServices.remove(r.name);
10292 mServicesByIntent.remove(r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010293 r.totalRestartCount = 0;
10294 unscheduleServiceRestartLocked(r);
10295
10296 // Also make sure it is not on the pending list.
10297 int N = mPendingServices.size();
10298 for (int i=0; i<N; i++) {
10299 if (mPendingServices.get(i) == r) {
10300 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010301 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010302 i--;
10303 N--;
10304 }
10305 }
10306
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010307 r.cancelNotification();
10308 r.isForeground = false;
10309 r.foregroundId = 0;
10310 r.foregroundNoti = null;
10311
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010312 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070010313 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010314 r.pendingStarts.clear();
10315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010316 if (r.app != null) {
10317 synchronized (r.stats.getBatteryStats()) {
10318 r.stats.stopLaunchedLocked();
10319 }
10320 r.app.services.remove(r);
10321 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010322 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010323 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010324 mStoppingServices.add(r);
10325 updateOomAdjLocked(r.app);
10326 r.app.thread.scheduleStopService(r);
10327 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010328 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010329 + r.shortName, e);
10330 serviceDoneExecutingLocked(r, true);
10331 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010332 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010333 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010334 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010335 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010336 }
10337 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010338 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010339 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010340 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080010341
10342 if (r.bindings.size() > 0) {
10343 r.bindings.clear();
10344 }
10345
10346 if (r.restarter instanceof ServiceRestarter) {
10347 ((ServiceRestarter)r.restarter).setService(null);
10348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010349 }
10350
10351 ComponentName startServiceLocked(IApplicationThread caller,
10352 Intent service, String resolvedType,
10353 int callingPid, int callingUid) {
10354 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010355 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010356 + " type=" + resolvedType + " args=" + service.getExtras());
10357
10358 if (caller != null) {
10359 final ProcessRecord callerApp = getRecordForAppLocked(caller);
10360 if (callerApp == null) {
10361 throw new SecurityException(
10362 "Unable to find app for caller " + caller
10363 + " (pid=" + Binder.getCallingPid()
10364 + ") when starting service " + service);
10365 }
10366 }
10367
10368 ServiceLookupResult res =
10369 retrieveServiceLocked(service, resolvedType,
10370 callingPid, callingUid);
10371 if (res == null) {
10372 return null;
10373 }
10374 if (res.record == null) {
10375 return new ComponentName("!", res.permission != null
10376 ? res.permission : "private to package");
10377 }
10378 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -070010379 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
10380 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010381 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010382 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010383 }
10384 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010385 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010386 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn39792d22010-08-19 18:01:52 -070010387 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010388 r.lastActivity = SystemClock.uptimeMillis();
10389 synchronized (r.stats.getBatteryStats()) {
10390 r.stats.startRunningLocked();
10391 }
10392 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
10393 return new ComponentName("!", "Service process is bad");
10394 }
10395 return r.name;
10396 }
10397 }
10398
10399 public ComponentName startService(IApplicationThread caller, Intent service,
10400 String resolvedType) {
10401 // Refuse possible leaked file descriptors
10402 if (service != null && service.hasFileDescriptors() == true) {
10403 throw new IllegalArgumentException("File descriptors passed in Intent");
10404 }
10405
10406 synchronized(this) {
10407 final int callingPid = Binder.getCallingPid();
10408 final int callingUid = Binder.getCallingUid();
10409 final long origId = Binder.clearCallingIdentity();
10410 ComponentName res = startServiceLocked(caller, service,
10411 resolvedType, callingPid, callingUid);
10412 Binder.restoreCallingIdentity(origId);
10413 return res;
10414 }
10415 }
10416
10417 ComponentName startServiceInPackage(int uid,
10418 Intent service, String resolvedType) {
10419 synchronized(this) {
10420 final long origId = Binder.clearCallingIdentity();
10421 ComponentName res = startServiceLocked(null, service,
10422 resolvedType, -1, uid);
10423 Binder.restoreCallingIdentity(origId);
10424 return res;
10425 }
10426 }
10427
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010428 private void stopServiceLocked(ServiceRecord service) {
10429 synchronized (service.stats.getBatteryStats()) {
10430 service.stats.stopRunningLocked();
10431 }
10432 service.startRequested = false;
10433 service.callStart = false;
10434 bringDownServiceLocked(service, false);
10435 }
10436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010437 public int stopService(IApplicationThread caller, Intent service,
10438 String resolvedType) {
10439 // Refuse possible leaked file descriptors
10440 if (service != null && service.hasFileDescriptors() == true) {
10441 throw new IllegalArgumentException("File descriptors passed in Intent");
10442 }
10443
10444 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010445 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010446 + " type=" + resolvedType);
10447
10448 final ProcessRecord callerApp = getRecordForAppLocked(caller);
10449 if (caller != null && callerApp == null) {
10450 throw new SecurityException(
10451 "Unable to find app for caller " + caller
10452 + " (pid=" + Binder.getCallingPid()
10453 + ") when stopping service " + service);
10454 }
10455
10456 // If this service is active, make sure it is stopped.
10457 ServiceLookupResult r = findServiceLocked(service, resolvedType);
10458 if (r != null) {
10459 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010460 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010461 try {
10462 stopServiceLocked(r.record);
10463 } finally {
10464 Binder.restoreCallingIdentity(origId);
10465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010466 return 1;
10467 }
10468 return -1;
10469 }
10470 }
10471
10472 return 0;
10473 }
10474
10475 public IBinder peekService(Intent service, String resolvedType) {
10476 // Refuse possible leaked file descriptors
10477 if (service != null && service.hasFileDescriptors() == true) {
10478 throw new IllegalArgumentException("File descriptors passed in Intent");
10479 }
10480
10481 IBinder ret = null;
10482
10483 synchronized(this) {
10484 ServiceLookupResult r = findServiceLocked(service, resolvedType);
10485
10486 if (r != null) {
10487 // r.record is null if findServiceLocked() failed the caller permission check
10488 if (r.record == null) {
10489 throw new SecurityException(
10490 "Permission Denial: Accessing service " + r.record.name
10491 + " from pid=" + Binder.getCallingPid()
10492 + ", uid=" + Binder.getCallingUid()
10493 + " requires " + r.permission);
10494 }
10495 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
10496 if (ib != null) {
10497 ret = ib.binder;
10498 }
10499 }
10500 }
10501
10502 return ret;
10503 }
10504
10505 public boolean stopServiceToken(ComponentName className, IBinder token,
10506 int startId) {
10507 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010508 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010509 + " " + token + " startId=" + startId);
10510 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010511 if (r != null) {
10512 if (startId >= 0) {
10513 // Asked to only stop if done with all work. Note that
10514 // to avoid leaks, we will take this as dropping all
10515 // start items up to and including this one.
10516 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
10517 if (si != null) {
10518 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010519 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
10520 cur.removeUriPermissionsLocked();
10521 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010522 break;
10523 }
10524 }
10525 }
10526
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010527 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010528 return false;
10529 }
10530
10531 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010532 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010533 + " is last, but have " + r.deliveredStarts.size()
10534 + " remaining args");
10535 }
10536 }
10537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010538 synchronized (r.stats.getBatteryStats()) {
10539 r.stats.stopRunningLocked();
10540 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010541 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 }
10543 final long origId = Binder.clearCallingIdentity();
10544 bringDownServiceLocked(r, false);
10545 Binder.restoreCallingIdentity(origId);
10546 return true;
10547 }
10548 }
10549 return false;
10550 }
10551
10552 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010553 int id, Notification notification, boolean removeNotification) {
10554 final long origId = Binder.clearCallingIdentity();
10555 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010556 synchronized(this) {
10557 ServiceRecord r = findServiceLocked(className, token);
10558 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010559 if (id != 0) {
10560 if (notification == null) {
10561 throw new IllegalArgumentException("null notification");
10562 }
10563 if (r.foregroundId != id) {
10564 r.cancelNotification();
10565 r.foregroundId = id;
10566 }
10567 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
10568 r.foregroundNoti = notification;
10569 r.isForeground = true;
10570 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010571 if (r.app != null) {
10572 updateServiceForegroundLocked(r.app, true);
10573 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010574 } else {
10575 if (r.isForeground) {
10576 r.isForeground = false;
10577 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010578 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010579 updateServiceForegroundLocked(r.app, true);
10580 }
10581 }
10582 if (removeNotification) {
10583 r.cancelNotification();
10584 r.foregroundId = 0;
10585 r.foregroundNoti = null;
10586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010587 }
10588 }
10589 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010590 } finally {
10591 Binder.restoreCallingIdentity(origId);
10592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010593 }
10594
10595 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
10596 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010597 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010598 if (sr.isForeground) {
10599 anyForeground = true;
10600 break;
10601 }
10602 }
10603 if (anyForeground != proc.foregroundServices) {
10604 proc.foregroundServices = anyForeground;
10605 if (oomAdj) {
10606 updateOomAdjLocked();
10607 }
10608 }
10609 }
10610
10611 public int bindService(IApplicationThread caller, IBinder token,
10612 Intent service, String resolvedType,
10613 IServiceConnection connection, int flags) {
10614 // Refuse possible leaked file descriptors
10615 if (service != null && service.hasFileDescriptors() == true) {
10616 throw new IllegalArgumentException("File descriptors passed in Intent");
10617 }
10618
10619 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010620 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010621 + " type=" + resolvedType + " conn=" + connection.asBinder()
10622 + " flags=0x" + Integer.toHexString(flags));
10623 final ProcessRecord callerApp = getRecordForAppLocked(caller);
10624 if (callerApp == null) {
10625 throw new SecurityException(
10626 "Unable to find app for caller " + caller
10627 + " (pid=" + Binder.getCallingPid()
10628 + ") when binding service " + service);
10629 }
10630
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010631 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010632 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010633 activity = mMainStack.isInStackLocked(token);
10634 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010635 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010636 return 0;
10637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010638 }
10639
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010640 int clientLabel = 0;
10641 PendingIntent clientIntent = null;
10642
10643 if (callerApp.info.uid == Process.SYSTEM_UID) {
10644 // Hacky kind of thing -- allow system stuff to tell us
10645 // what they are, so we can report this elsewhere for
10646 // others to know why certain services are running.
10647 try {
10648 clientIntent = (PendingIntent)service.getParcelableExtra(
10649 Intent.EXTRA_CLIENT_INTENT);
10650 } catch (RuntimeException e) {
10651 }
10652 if (clientIntent != null) {
10653 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
10654 if (clientLabel != 0) {
10655 // There are no useful extras in the intent, trash them.
10656 // System code calling with this stuff just needs to know
10657 // this will happen.
10658 service = service.cloneFilter();
10659 }
10660 }
10661 }
10662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010663 ServiceLookupResult res =
10664 retrieveServiceLocked(service, resolvedType,
10665 Binder.getCallingPid(), Binder.getCallingUid());
10666 if (res == null) {
10667 return 0;
10668 }
10669 if (res.record == null) {
10670 return -1;
10671 }
10672 ServiceRecord s = res.record;
10673
10674 final long origId = Binder.clearCallingIdentity();
10675
10676 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010677 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010678 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010679 }
10680
10681 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
10682 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010683 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010684
10685 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010686 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
10687 if (clist == null) {
10688 clist = new ArrayList<ConnectionRecord>();
10689 s.connections.put(binder, clist);
10690 }
10691 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010692 b.connections.add(c);
10693 if (activity != null) {
10694 if (activity.connections == null) {
10695 activity.connections = new HashSet<ConnectionRecord>();
10696 }
10697 activity.connections.add(c);
10698 }
10699 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010700 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
10701 b.client.hasAboveClient = true;
10702 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010703 clist = mServiceConnections.get(binder);
10704 if (clist == null) {
10705 clist = new ArrayList<ConnectionRecord>();
10706 mServiceConnections.put(binder, clist);
10707 }
10708 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010709
10710 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
10711 s.lastActivity = SystemClock.uptimeMillis();
10712 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
10713 return 0;
10714 }
10715 }
10716
10717 if (s.app != null) {
10718 // This could have made the service more important.
10719 updateOomAdjLocked(s.app);
10720 }
10721
Joe Onorato8a9b2202010-02-26 18:56:32 -080010722 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010723 + ": received=" + b.intent.received
10724 + " apps=" + b.intent.apps.size()
10725 + " doRebind=" + b.intent.doRebind);
10726
10727 if (s.app != null && b.intent.received) {
10728 // Service is already running, so we can immediately
10729 // publish the connection.
10730 try {
10731 c.conn.connected(s.name, b.intent.binder);
10732 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010733 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010734 + " to connection " + c.conn.asBinder()
10735 + " (in " + c.binding.client.processName + ")", e);
10736 }
10737
10738 // If this is the first app connected back to this binding,
10739 // and the service had previously asked to be told when
10740 // rebound, then do so.
10741 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
10742 requestServiceBindingLocked(s, b.intent, true);
10743 }
10744 } else if (!b.intent.requested) {
10745 requestServiceBindingLocked(s, b.intent, false);
10746 }
10747
10748 Binder.restoreCallingIdentity(origId);
10749 }
10750
10751 return 1;
10752 }
10753
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070010754 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010755 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010756 IBinder binder = c.conn.asBinder();
10757 AppBindRecord b = c.binding;
10758 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010759 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
10760 if (clist != null) {
10761 clist.remove(c);
10762 if (clist.size() == 0) {
10763 s.connections.remove(binder);
10764 }
10765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766 b.connections.remove(c);
10767 if (c.activity != null && c.activity != skipAct) {
10768 if (c.activity.connections != null) {
10769 c.activity.connections.remove(c);
10770 }
10771 }
10772 if (b.client != skipApp) {
10773 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010774 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
10775 b.client.updateHasAboveClientLocked();
10776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010777 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010778 clist = mServiceConnections.get(binder);
10779 if (clist != null) {
10780 clist.remove(c);
10781 if (clist.size() == 0) {
10782 mServiceConnections.remove(binder);
10783 }
10784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010785
10786 if (b.connections.size() == 0) {
10787 b.intent.apps.remove(b.client);
10788 }
10789
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010790 if (!c.serviceDead) {
10791 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
10792 + ": shouldUnbind=" + b.intent.hasBound);
10793 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
10794 && b.intent.hasBound) {
10795 try {
10796 bumpServiceExecutingLocked(s, "unbind");
10797 updateOomAdjLocked(s.app);
10798 b.intent.hasBound = false;
10799 // Assume the client doesn't want to know about a rebind;
10800 // we will deal with that later if it asks for one.
10801 b.intent.doRebind = false;
10802 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
10803 } catch (Exception e) {
10804 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
10805 serviceDoneExecutingLocked(s, true);
10806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010807 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010808
10809 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
10810 bringDownServiceLocked(s, false);
10811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010812 }
10813 }
10814
10815 public boolean unbindService(IServiceConnection connection) {
10816 synchronized (this) {
10817 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010818 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010819 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
10820 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010821 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010822 + connection.asBinder());
10823 return false;
10824 }
10825
10826 final long origId = Binder.clearCallingIdentity();
10827
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010828 while (clist.size() > 0) {
10829 ConnectionRecord r = clist.get(0);
10830 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010831
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010832 if (r.binding.service.app != null) {
10833 // This could have made the service less important.
10834 updateOomAdjLocked(r.binding.service.app);
10835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010836 }
10837
10838 Binder.restoreCallingIdentity(origId);
10839 }
10840
10841 return true;
10842 }
10843
10844 public void publishService(IBinder token, Intent intent, IBinder service) {
10845 // Refuse possible leaked file descriptors
10846 if (intent != null && intent.hasFileDescriptors() == true) {
10847 throw new IllegalArgumentException("File descriptors passed in Intent");
10848 }
10849
10850 synchronized(this) {
10851 if (!(token instanceof ServiceRecord)) {
10852 throw new IllegalArgumentException("Invalid service token");
10853 }
10854 ServiceRecord r = (ServiceRecord)token;
10855
10856 final long origId = Binder.clearCallingIdentity();
10857
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010858 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010859 + " " + intent + ": " + service);
10860 if (r != null) {
10861 Intent.FilterComparison filter
10862 = new Intent.FilterComparison(intent);
10863 IntentBindRecord b = r.bindings.get(filter);
10864 if (b != null && !b.received) {
10865 b.binder = service;
10866 b.requested = true;
10867 b.received = true;
10868 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010869 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010870 = r.connections.values().iterator();
10871 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010872 ArrayList<ConnectionRecord> clist = it.next();
10873 for (int i=0; i<clist.size(); i++) {
10874 ConnectionRecord c = clist.get(i);
10875 if (!filter.equals(c.binding.intent.intent)) {
10876 if (DEBUG_SERVICE) Slog.v(
10877 TAG, "Not publishing to: " + c);
10878 if (DEBUG_SERVICE) Slog.v(
10879 TAG, "Bound intent: " + c.binding.intent.intent);
10880 if (DEBUG_SERVICE) Slog.v(
10881 TAG, "Published intent: " + intent);
10882 continue;
10883 }
10884 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
10885 try {
10886 c.conn.connected(r.name, service);
10887 } catch (Exception e) {
10888 Slog.w(TAG, "Failure sending service " + r.name +
10889 " to connection " + c.conn.asBinder() +
10890 " (in " + c.binding.client.processName + ")", e);
10891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010892 }
10893 }
10894 }
10895 }
10896
10897 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
10898
10899 Binder.restoreCallingIdentity(origId);
10900 }
10901 }
10902 }
10903
10904 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10905 // Refuse possible leaked file descriptors
10906 if (intent != null && intent.hasFileDescriptors() == true) {
10907 throw new IllegalArgumentException("File descriptors passed in Intent");
10908 }
10909
10910 synchronized(this) {
10911 if (!(token instanceof ServiceRecord)) {
10912 throw new IllegalArgumentException("Invalid service token");
10913 }
10914 ServiceRecord r = (ServiceRecord)token;
10915
10916 final long origId = Binder.clearCallingIdentity();
10917
10918 if (r != null) {
10919 Intent.FilterComparison filter
10920 = new Intent.FilterComparison(intent);
10921 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010922 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010923 + " at " + b + ": apps="
10924 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020010925
10926 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010927 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020010928 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010929 // Applications have already bound since the last
10930 // unbind, so just rebind right here.
10931 requestServiceBindingLocked(r, b, true);
10932 } else {
10933 // Note to tell the service the next time there is
10934 // a new client.
10935 b.doRebind = true;
10936 }
10937 }
10938
Per Edelberg78f9fff2010-08-30 20:01:35 +020010939 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010940
10941 Binder.restoreCallingIdentity(origId);
10942 }
10943 }
10944 }
10945
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010946 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010947 synchronized(this) {
10948 if (!(token instanceof ServiceRecord)) {
10949 throw new IllegalArgumentException("Invalid service token");
10950 }
10951 ServiceRecord r = (ServiceRecord)token;
10952 boolean inStopping = mStoppingServices.contains(token);
10953 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010954 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010955 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010956 + " with incorrect token: given " + token
10957 + ", expected " + r);
10958 return;
10959 }
10960
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010961 if (type == 1) {
10962 // This is a call from a service start... take care of
10963 // book-keeping.
10964 r.callStart = true;
10965 switch (res) {
10966 case Service.START_STICKY_COMPATIBILITY:
10967 case Service.START_STICKY: {
10968 // We are done with the associated start arguments.
10969 r.findDeliveredStart(startId, true);
10970 // Don't stop if killed.
10971 r.stopIfKilled = false;
10972 break;
10973 }
10974 case Service.START_NOT_STICKY: {
10975 // We are done with the associated start arguments.
10976 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010977 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010978 // There is no more work, and this service
10979 // doesn't want to hang around if killed.
10980 r.stopIfKilled = true;
10981 }
10982 break;
10983 }
10984 case Service.START_REDELIVER_INTENT: {
10985 // We'll keep this item until they explicitly
10986 // call stop for it, but keep track of the fact
10987 // that it was delivered.
10988 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
10989 if (si != null) {
10990 si.deliveryCount = 0;
10991 si.doneExecutingCount++;
10992 // Don't stop if killed.
10993 r.stopIfKilled = true;
10994 }
10995 break;
10996 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010997 case Service.START_TASK_REMOVED_COMPLETE: {
10998 // Special processing for onTaskRemoved(). Don't
10999 // impact normal onStartCommand() processing.
11000 r.findDeliveredStart(startId, true);
11001 break;
11002 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011003 default:
11004 throw new IllegalArgumentException(
11005 "Unknown service start result: " + res);
11006 }
11007 if (res == Service.START_STICKY_COMPATIBILITY) {
11008 r.callStart = false;
11009 }
11010 }
11011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011012 final long origId = Binder.clearCallingIdentity();
11013 serviceDoneExecutingLocked(r, inStopping);
11014 Binder.restoreCallingIdentity(origId);
11015 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011016 Slog.w(TAG, "Done executing unknown service from pid "
11017 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011018 }
11019 }
11020 }
11021
11022 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011023 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
11024 + ": nesting=" + r.executeNesting
11025 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011026 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011027 r.executeNesting--;
11028 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011029 if (DEBUG_SERVICE) Slog.v(TAG,
11030 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011031 r.app.executingServices.remove(r);
11032 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011033 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
11034 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011035 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
11036 }
11037 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011038 if (DEBUG_SERVICE) Slog.v(TAG,
11039 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011040 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020011041 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011042 }
11043 updateOomAdjLocked(r.app);
11044 }
11045 }
11046
11047 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011048 String anrMessage = null;
11049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011050 synchronized(this) {
11051 if (proc.executingServices.size() == 0 || proc.thread == null) {
11052 return;
11053 }
11054 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
11055 Iterator<ServiceRecord> it = proc.executingServices.iterator();
11056 ServiceRecord timeout = null;
11057 long nextTime = 0;
11058 while (it.hasNext()) {
11059 ServiceRecord sr = it.next();
11060 if (sr.executingStart < maxTime) {
11061 timeout = sr;
11062 break;
11063 }
11064 if (sr.executingStart > nextTime) {
11065 nextTime = sr.executingStart;
11066 }
11067 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011068 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011069 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011070 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011071 } else {
11072 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11073 msg.obj = proc;
11074 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
11075 }
11076 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011077
11078 if (anrMessage != null) {
11079 appNotResponding(proc, null, null, anrMessage);
11080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011081 }
11082
11083 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011084 // BACKUP AND RESTORE
11085 // =========================================================
11086
11087 // Cause the target app to be launched if necessary and its backup agent
11088 // instantiated. The backup agent will invoke backupAgentCreated() on the
11089 // activity manager to announce its creation.
11090 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011091 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011092 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11093
11094 synchronized(this) {
11095 // !!! TODO: currently no check here that we're already bound
11096 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11097 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11098 synchronized (stats) {
11099 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11100 }
11101
Dianne Hackborne7f97212011-02-24 14:40:20 -080011102 // Backup agent is now in use, its package can't be stopped.
11103 try {
11104 AppGlobals.getPackageManager().setPackageStoppedState(
11105 app.packageName, false);
11106 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011107 } catch (IllegalArgumentException e) {
11108 Slog.w(TAG, "Failed trying to unstop package "
11109 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011110 }
11111
Christopher Tate181fafa2009-05-14 11:12:14 -070011112 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011113 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11114 ? new ComponentName(app.packageName, app.backupAgentName)
11115 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011116 // startProcessLocked() returns existing proc's record if it's already running
11117 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011118 false, 0, "backup", hostingName, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011119 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011120 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011121 return false;
11122 }
11123
11124 r.app = proc;
11125 mBackupTarget = r;
11126 mBackupAppName = app.packageName;
11127
Christopher Tate6fa95972009-06-05 18:43:55 -070011128 // Try not to kill the process during backup
11129 updateOomAdjLocked(proc);
11130
Christopher Tate181fafa2009-05-14 11:12:14 -070011131 // If the process is already attached, schedule the creation of the backup agent now.
11132 // If it is not yet live, this will be done when it attaches to the framework.
11133 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011134 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011135 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011136 proc.thread.scheduleCreateBackupAgent(app,
11137 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011138 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011139 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011140 }
11141 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011142 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011143 }
11144 // Invariants: at this point, the target app process exists and the application
11145 // is either already running or in the process of coming up. mBackupTarget and
11146 // mBackupAppName describe the app, so that when it binds back to the AM we
11147 // know that it's scheduled for a backup-agent operation.
11148 }
11149
11150 return true;
11151 }
11152
11153 // A backup agent has just come up
11154 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011155 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011156 + " = " + agent);
11157
11158 synchronized(this) {
11159 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011160 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011161 return;
11162 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011163 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011164
Dianne Hackborn06740692010-09-22 22:46:21 -070011165 long oldIdent = Binder.clearCallingIdentity();
11166 try {
11167 IBackupManager bm = IBackupManager.Stub.asInterface(
11168 ServiceManager.getService(Context.BACKUP_SERVICE));
11169 bm.agentConnected(agentPackageName, agent);
11170 } catch (RemoteException e) {
11171 // can't happen; the backup manager service is local
11172 } catch (Exception e) {
11173 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11174 e.printStackTrace();
11175 } finally {
11176 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011177 }
11178 }
11179
11180 // done with this agent
11181 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011182 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011183 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011184 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011185 return;
11186 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011187
11188 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011189 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011190 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011191 return;
11192 }
11193
Christopher Tate181fafa2009-05-14 11:12:14 -070011194 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011195 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011196 return;
11197 }
11198
Christopher Tate6fa95972009-06-05 18:43:55 -070011199 ProcessRecord proc = mBackupTarget.app;
11200 mBackupTarget = null;
11201 mBackupAppName = null;
11202
11203 // Not backing this app up any more; reset its OOM adjustment
11204 updateOomAdjLocked(proc);
11205
Christopher Tatec7b31e32009-06-10 15:49:30 -070011206 // If the app crashed during backup, 'thread' will be null here
11207 if (proc.thread != null) {
11208 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011209 proc.thread.scheduleDestroyBackupAgent(appInfo,
11210 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070011211 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011212 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070011213 e.printStackTrace();
11214 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011215 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011216 }
11217 }
11218 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011219 // BROADCASTS
11220 // =========================================================
11221
Josh Bartel7f208742010-02-25 11:01:44 -060011222 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011223 List cur) {
11224 final ContentResolver resolver = mContext.getContentResolver();
11225 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
11226 if (list == null) {
11227 return cur;
11228 }
11229 int N = list.size();
11230 for (int i=0; i<N; i++) {
11231 Intent intent = list.get(i);
11232 if (filter.match(resolver, intent, true, TAG) >= 0) {
11233 if (cur == null) {
11234 cur = new ArrayList<Intent>();
11235 }
11236 cur.add(intent);
11237 }
11238 }
11239 return cur;
11240 }
11241
11242 private final void scheduleBroadcastsLocked() {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011243 if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts: current="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011244 + mBroadcastsScheduled);
11245
11246 if (mBroadcastsScheduled) {
11247 return;
11248 }
11249 mHandler.sendEmptyMessage(BROADCAST_INTENT_MSG);
11250 mBroadcastsScheduled = true;
11251 }
11252
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011253 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011254 IIntentReceiver receiver, IntentFilter filter, String permission) {
11255 synchronized(this) {
11256 ProcessRecord callerApp = null;
11257 if (caller != null) {
11258 callerApp = getRecordForAppLocked(caller);
11259 if (callerApp == null) {
11260 throw new SecurityException(
11261 "Unable to find app for caller " + caller
11262 + " (pid=" + Binder.getCallingPid()
11263 + ") when registering receiver " + receiver);
11264 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011265 if (callerApp.info.uid != Process.SYSTEM_UID &&
11266 !callerApp.pkgList.contains(callerPackage)) {
11267 throw new SecurityException("Given caller package " + callerPackage
11268 + " is not running in process " + callerApp);
11269 }
11270 } else {
11271 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011272 }
11273
11274 List allSticky = null;
11275
11276 // Look for any matching sticky broadcasts...
11277 Iterator actions = filter.actionsIterator();
11278 if (actions != null) {
11279 while (actions.hasNext()) {
11280 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060011281 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282 }
11283 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060011284 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011285 }
11286
11287 // The first sticky in the list is returned directly back to
11288 // the client.
11289 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11290
Joe Onorato8a9b2202010-02-26 18:56:32 -080011291 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011292 + ": " + sticky);
11293
11294 if (receiver == null) {
11295 return sticky;
11296 }
11297
11298 ReceiverList rl
11299 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11300 if (rl == null) {
11301 rl = new ReceiverList(this, callerApp,
11302 Binder.getCallingPid(),
11303 Binder.getCallingUid(), receiver);
11304 if (rl.app != null) {
11305 rl.app.receivers.add(rl);
11306 } else {
11307 try {
11308 receiver.asBinder().linkToDeath(rl, 0);
11309 } catch (RemoteException e) {
11310 return sticky;
11311 }
11312 rl.linkedToDeath = true;
11313 }
11314 mRegisteredReceivers.put(receiver.asBinder(), rl);
11315 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011316 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011317 rl.add(bf);
11318 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011319 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011320 }
11321 mReceiverResolver.addFilter(bf);
11322
11323 // Enqueue broadcasts for all existing stickies that match
11324 // this filter.
11325 if (allSticky != null) {
11326 ArrayList receivers = new ArrayList();
11327 receivers.add(bf);
11328
11329 int N = allSticky.size();
11330 for (int i=0; i<N; i++) {
11331 Intent intent = (Intent)allSticky.get(i);
11332 BroadcastRecord r = new BroadcastRecord(intent, null,
11333 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011334 false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011335 if (mParallelBroadcasts.size() == 0) {
11336 scheduleBroadcastsLocked();
11337 }
11338 mParallelBroadcasts.add(r);
11339 }
11340 }
11341
11342 return sticky;
11343 }
11344 }
11345
11346 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011347 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011348
11349 boolean doNext = false;
11350
11351 synchronized(this) {
11352 ReceiverList rl
11353 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11354 if (rl != null) {
11355 if (rl.curBroadcast != null) {
11356 BroadcastRecord r = rl.curBroadcast;
11357 doNext = finishReceiverLocked(
11358 receiver.asBinder(), r.resultCode, r.resultData,
11359 r.resultExtras, r.resultAbort, true);
11360 }
11361
11362 if (rl.app != null) {
11363 rl.app.receivers.remove(rl);
11364 }
11365 removeReceiverLocked(rl);
11366 if (rl.linkedToDeath) {
11367 rl.linkedToDeath = false;
11368 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11369 }
11370 }
11371 }
11372
11373 if (!doNext) {
11374 return;
11375 }
11376
11377 final long origId = Binder.clearCallingIdentity();
11378 processNextBroadcast(false);
11379 trimApplications();
11380 Binder.restoreCallingIdentity(origId);
11381 }
11382
11383 void removeReceiverLocked(ReceiverList rl) {
11384 mRegisteredReceivers.remove(rl.receiver.asBinder());
11385 int N = rl.size();
11386 for (int i=0; i<N; i++) {
11387 mReceiverResolver.removeFilter(rl.get(i));
11388 }
11389 }
11390
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011391 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
11392 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11393 ProcessRecord r = mLruProcesses.get(i);
11394 if (r.thread != null) {
11395 try {
11396 r.thread.dispatchPackageBroadcast(cmd, packages);
11397 } catch (RemoteException ex) {
11398 }
11399 }
11400 }
11401 }
11402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011403 private final int broadcastIntentLocked(ProcessRecord callerApp,
11404 String callerPackage, Intent intent, String resolvedType,
11405 IIntentReceiver resultTo, int resultCode, String resultData,
11406 Bundle map, String requiredPermission,
11407 boolean ordered, boolean sticky, int callingPid, int callingUid) {
11408 intent = new Intent(intent);
11409
Dianne Hackborne7f97212011-02-24 14:40:20 -080011410 // By default broadcasts do not go to stopped apps.
11411 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11412
Joe Onorato8a9b2202010-02-26 18:56:32 -080011413 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011414 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
11415 + " ordered=" + ordered);
11416 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011417 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 }
11419
11420 // Handle special intents: if this broadcast is from the package
11421 // manager about a package being removed, we need to remove all of
11422 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011423 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011424 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011425 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11426 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011427 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011428 || uidRemoved) {
11429 if (checkComponentPermission(
11430 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011431 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011432 == PackageManager.PERMISSION_GRANTED) {
11433 if (uidRemoved) {
11434 final Bundle intentExtras = intent.getExtras();
11435 final int uid = intentExtras != null
11436 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11437 if (uid >= 0) {
11438 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11439 synchronized (bs) {
11440 bs.removeUidStatsLocked(uid);
11441 }
11442 }
11443 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011444 // If resources are unvailble just force stop all
11445 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011446 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011447 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11448 if (list != null && (list.length > 0)) {
11449 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070011450 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011451 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011452 sendPackageBroadcastLocked(
11453 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011454 }
11455 } else {
11456 Uri data = intent.getData();
11457 String ssp;
11458 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11459 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11460 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070011461 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011462 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011463 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011464 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
11465 new String[] {ssp});
11466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011467 }
11468 }
11469 }
11470 } else {
11471 String msg = "Permission Denial: " + intent.getAction()
11472 + " broadcast from " + callerPackage + " (pid=" + callingPid
11473 + ", uid=" + callingUid + ")"
11474 + " requires "
11475 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011476 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011477 throw new SecurityException(msg);
11478 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011479
11480 // Special case for adding a package: by default turn on compatibility
11481 // mode.
11482 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011483 Uri data = intent.getData();
11484 String ssp;
11485 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11486 mCompatModePackages.handlePackageAddedLocked(ssp,
11487 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 }
11490
11491 /*
11492 * If this is the time zone changed action, queue up a message that will reset the timezone
11493 * of all currently running processes. This message will get queued up before the broadcast
11494 * happens.
11495 */
11496 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11497 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11498 }
11499
Robert Greenwalt03595d02010-11-02 14:08:23 -070011500 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11501 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11502 }
11503
Robert Greenwalt434203a2010-10-11 16:00:27 -070011504 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11505 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11506 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11507 }
11508
Dianne Hackborn854060af2009-07-09 18:14:31 -070011509 /*
11510 * Prevent non-system code (defined here to be non-persistent
11511 * processes) from sending protected broadcasts.
11512 */
11513 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11514 || callingUid == Process.SHELL_UID || callingUid == 0) {
11515 // Always okay.
11516 } else if (callerApp == null || !callerApp.persistent) {
11517 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011518 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070011519 intent.getAction())) {
11520 String msg = "Permission Denial: not allowed to send broadcast "
11521 + intent.getAction() + " from pid="
11522 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011523 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070011524 throw new SecurityException(msg);
11525 }
11526 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011527 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070011528 return BROADCAST_SUCCESS;
11529 }
11530 }
11531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011532 // Add to the sticky list if requested.
11533 if (sticky) {
11534 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11535 callingPid, callingUid)
11536 != PackageManager.PERMISSION_GRANTED) {
11537 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11538 + callingPid + ", uid=" + callingUid
11539 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011540 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011541 throw new SecurityException(msg);
11542 }
11543 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011544 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011545 + " and enforce permission " + requiredPermission);
11546 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
11547 }
11548 if (intent.getComponent() != null) {
11549 throw new SecurityException(
11550 "Sticky broadcasts can't target a specific component");
11551 }
11552 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11553 if (list == null) {
11554 list = new ArrayList<Intent>();
11555 mStickyBroadcasts.put(intent.getAction(), list);
11556 }
11557 int N = list.size();
11558 int i;
11559 for (i=0; i<N; i++) {
11560 if (intent.filterEquals(list.get(i))) {
11561 // This sticky already exists, replace it.
11562 list.set(i, new Intent(intent));
11563 break;
11564 }
11565 }
11566 if (i >= N) {
11567 list.add(new Intent(intent));
11568 }
11569 }
11570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011571 // Figure out who all will receive this broadcast.
11572 List receivers = null;
11573 List<BroadcastFilter> registeredReceivers = null;
11574 try {
11575 if (intent.getComponent() != null) {
11576 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011577 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070011578 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011579 if (ai != null) {
11580 receivers = new ArrayList();
11581 ResolveInfo ri = new ResolveInfo();
11582 ri.activityInfo = ai;
11583 receivers.add(ri);
11584 }
11585 } else {
11586 // Need to resolve the intent to interested receivers...
11587 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11588 == 0) {
11589 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011590 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011591 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011592 }
Mihai Preda074edef2009-05-18 17:13:31 +020011593 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011594 }
11595 } catch (RemoteException ex) {
11596 // pm is in same process, this will never happen.
11597 }
11598
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011599 final boolean replacePending =
11600 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11601
Joe Onorato8a9b2202010-02-26 18:56:32 -080011602 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011603 + " replacePending=" + replacePending);
11604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011605 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11606 if (!ordered && NR > 0) {
11607 // If we are not serializing this broadcast, then send the
11608 // registered receivers separately so they don't wait for the
11609 // components to be launched.
11610 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
11611 callerPackage, callingPid, callingUid, requiredPermission,
11612 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011613 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011614 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011615 TAG, "Enqueueing parallel broadcast " + r
11616 + ": prev had " + mParallelBroadcasts.size());
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011617 boolean replaced = false;
11618 if (replacePending) {
11619 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
11620 if (intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011621 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011622 "***** DROPPING PARALLEL: " + intent);
11623 mParallelBroadcasts.set(i, r);
11624 replaced = true;
11625 break;
11626 }
11627 }
11628 }
11629 if (!replaced) {
11630 mParallelBroadcasts.add(r);
11631 scheduleBroadcastsLocked();
11632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011633 registeredReceivers = null;
11634 NR = 0;
11635 }
11636
11637 // Merge into one list.
11638 int ir = 0;
11639 if (receivers != null) {
11640 // A special case for PACKAGE_ADDED: do not allow the package
11641 // being added to see this broadcast. This prevents them from
11642 // using this as a back door to get run as soon as they are
11643 // installed. Maybe in the future we want to have a special install
11644 // broadcast or such for apps, but we'd like to deliberately make
11645 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011646 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011647 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11648 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11649 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011650 Uri data = intent.getData();
11651 if (data != null) {
11652 String pkgName = data.getSchemeSpecificPart();
11653 if (pkgName != null) {
11654 skipPackages = new String[] { pkgName };
11655 }
11656 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011657 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011658 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011659 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011660 if (skipPackages != null && (skipPackages.length > 0)) {
11661 for (String skipPackage : skipPackages) {
11662 if (skipPackage != null) {
11663 int NT = receivers.size();
11664 for (int it=0; it<NT; it++) {
11665 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11666 if (curt.activityInfo.packageName.equals(skipPackage)) {
11667 receivers.remove(it);
11668 it--;
11669 NT--;
11670 }
11671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011672 }
11673 }
11674 }
11675
11676 int NT = receivers != null ? receivers.size() : 0;
11677 int it = 0;
11678 ResolveInfo curt = null;
11679 BroadcastFilter curr = null;
11680 while (it < NT && ir < NR) {
11681 if (curt == null) {
11682 curt = (ResolveInfo)receivers.get(it);
11683 }
11684 if (curr == null) {
11685 curr = registeredReceivers.get(ir);
11686 }
11687 if (curr.getPriority() >= curt.priority) {
11688 // Insert this broadcast record into the final list.
11689 receivers.add(it, curr);
11690 ir++;
11691 curr = null;
11692 it++;
11693 NT++;
11694 } else {
11695 // Skip to the next ResolveInfo in the final list.
11696 it++;
11697 curt = null;
11698 }
11699 }
11700 }
11701 while (ir < NR) {
11702 if (receivers == null) {
11703 receivers = new ArrayList();
11704 }
11705 receivers.add(registeredReceivers.get(ir));
11706 ir++;
11707 }
11708
11709 if ((receivers != null && receivers.size() > 0)
11710 || resultTo != null) {
11711 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
11712 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011713 receivers, resultTo, resultCode, resultData, map, ordered,
11714 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011715 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011716 TAG, "Enqueueing ordered broadcast " + r
11717 + ": prev had " + mOrderedBroadcasts.size());
11718 if (DEBUG_BROADCAST) {
11719 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011720 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011721 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011722 boolean replaced = false;
11723 if (replacePending) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011724 for (int i=mOrderedBroadcasts.size()-1; i>0; i--) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011725 if (intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011726 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011727 "***** DROPPING ORDERED: " + intent);
11728 mOrderedBroadcasts.set(i, r);
11729 replaced = true;
11730 break;
11731 }
11732 }
11733 }
11734 if (!replaced) {
11735 mOrderedBroadcasts.add(r);
11736 scheduleBroadcastsLocked();
11737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011738 }
11739
11740 return BROADCAST_SUCCESS;
11741 }
11742
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011743 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011744 // Refuse possible leaked file descriptors
11745 if (intent != null && intent.hasFileDescriptors() == true) {
11746 throw new IllegalArgumentException("File descriptors passed in Intent");
11747 }
11748
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011749 int flags = intent.getFlags();
11750
11751 if (!mProcessesReady) {
11752 // if the caller really truly claims to know what they're doing, go
11753 // ahead and allow the broadcast without launching any receivers
11754 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11755 intent = new Intent(intent);
11756 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11757 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11758 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11759 + " before boot completion");
11760 throw new IllegalStateException("Cannot broadcast before boot completed");
11761 }
11762 }
11763
11764 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11765 throw new IllegalArgumentException(
11766 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11767 }
11768
11769 return intent;
11770 }
11771
11772 public final int broadcastIntent(IApplicationThread caller,
11773 Intent intent, String resolvedType, IIntentReceiver resultTo,
11774 int resultCode, String resultData, Bundle map,
11775 String requiredPermission, boolean serialized, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011776 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011777 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011779 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11780 final int callingPid = Binder.getCallingPid();
11781 final int callingUid = Binder.getCallingUid();
11782 final long origId = Binder.clearCallingIdentity();
11783 int res = broadcastIntentLocked(callerApp,
11784 callerApp != null ? callerApp.info.packageName : null,
11785 intent, resolvedType, resultTo,
11786 resultCode, resultData, map, requiredPermission, serialized,
11787 sticky, callingPid, callingUid);
11788 Binder.restoreCallingIdentity(origId);
11789 return res;
11790 }
11791 }
11792
11793 int broadcastIntentInPackage(String packageName, int uid,
11794 Intent intent, String resolvedType, IIntentReceiver resultTo,
11795 int resultCode, String resultData, Bundle map,
11796 String requiredPermission, boolean serialized, boolean sticky) {
11797 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011798 intent = verifyBroadcastLocked(intent);
11799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011800 final long origId = Binder.clearCallingIdentity();
11801 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11802 resultTo, resultCode, resultData, map, requiredPermission,
11803 serialized, sticky, -1, uid);
11804 Binder.restoreCallingIdentity(origId);
11805 return res;
11806 }
11807 }
11808
11809 public final void unbroadcastIntent(IApplicationThread caller,
11810 Intent intent) {
11811 // Refuse possible leaked file descriptors
11812 if (intent != null && intent.hasFileDescriptors() == true) {
11813 throw new IllegalArgumentException("File descriptors passed in Intent");
11814 }
11815
11816 synchronized(this) {
11817 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11818 != PackageManager.PERMISSION_GRANTED) {
11819 String msg = "Permission Denial: unbroadcastIntent() from pid="
11820 + Binder.getCallingPid()
11821 + ", uid=" + Binder.getCallingUid()
11822 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011823 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011824 throw new SecurityException(msg);
11825 }
11826 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11827 if (list != null) {
11828 int N = list.size();
11829 int i;
11830 for (i=0; i<N; i++) {
11831 if (intent.filterEquals(list.get(i))) {
11832 list.remove(i);
11833 break;
11834 }
11835 }
11836 }
11837 }
11838 }
11839
11840 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11841 String resultData, Bundle resultExtras, boolean resultAbort,
11842 boolean explicit) {
11843 if (mOrderedBroadcasts.size() == 0) {
11844 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011845 Slog.w(TAG, "finishReceiver called but no pending broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011846 }
11847 return false;
11848 }
11849 BroadcastRecord r = mOrderedBroadcasts.get(0);
11850 if (r.receiver == null) {
11851 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011852 Slog.w(TAG, "finishReceiver called but none active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011853 }
11854 return false;
11855 }
11856 if (r.receiver != receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011857 Slog.w(TAG, "finishReceiver called but active receiver is different");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011858 return false;
11859 }
11860 int state = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011861 r.state = BroadcastRecord.IDLE;
11862 if (state == BroadcastRecord.IDLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011863 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011864 Slog.w(TAG, "finishReceiver called but state is IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011865 }
11866 }
11867 r.receiver = null;
11868 r.intent.setComponent(null);
11869 if (r.curApp != null) {
11870 r.curApp.curReceiver = null;
11871 }
11872 if (r.curFilter != null) {
11873 r.curFilter.receiverList.curBroadcast = null;
11874 }
11875 r.curFilter = null;
11876 r.curApp = null;
11877 r.curComponent = null;
11878 r.curReceiver = null;
11879 mPendingBroadcast = null;
11880
11881 r.resultCode = resultCode;
11882 r.resultData = resultData;
11883 r.resultExtras = resultExtras;
11884 r.resultAbort = resultAbort;
11885
11886 // We will process the next receiver right now if this is finishing
11887 // an app receiver (which is always asynchronous) or after we have
11888 // come back from calling a receiver.
11889 return state == BroadcastRecord.APP_RECEIVE
11890 || state == BroadcastRecord.CALL_DONE_RECEIVE;
11891 }
11892
11893 public void finishReceiver(IBinder who, int resultCode, String resultData,
11894 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011895 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896
11897 // Refuse possible leaked file descriptors
11898 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11899 throw new IllegalArgumentException("File descriptors passed in Bundle");
11900 }
11901
11902 boolean doNext;
11903
11904 final long origId = Binder.clearCallingIdentity();
11905
11906 synchronized(this) {
11907 doNext = finishReceiverLocked(
11908 who, resultCode, resultData, resultExtras, resultAbort, true);
11909 }
11910
11911 if (doNext) {
11912 processNextBroadcast(false);
11913 }
11914 trimApplications();
11915
11916 Binder.restoreCallingIdentity(origId);
11917 }
11918
Jeff Brown4d94a762010-09-23 11:33:28 -070011919 private final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011920 if (r.nextReceiver > 0) {
11921 Object curReceiver = r.receivers.get(r.nextReceiver-1);
11922 if (curReceiver instanceof BroadcastFilter) {
11923 BroadcastFilter bf = (BroadcastFilter) curReceiver;
Doug Zongker2bec3d42009-12-04 12:52:44 -080011924 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011925 System.identityHashCode(r),
11926 r.intent.getAction(),
11927 r.nextReceiver - 1,
11928 System.identityHashCode(bf));
11929 } else {
Doug Zongker2bec3d42009-12-04 12:52:44 -080011930 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011931 System.identityHashCode(r),
11932 r.intent.getAction(),
11933 r.nextReceiver - 1,
11934 ((ResolveInfo)curReceiver).toString());
11935 }
11936 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011937 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011938 + r);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011939 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011940 System.identityHashCode(r),
11941 r.intent.getAction(),
11942 r.nextReceiver,
11943 "NONE");
11944 }
11945 }
11946
Jeff Brown4d94a762010-09-23 11:33:28 -070011947 private final void setBroadcastTimeoutLocked(long timeoutTime) {
11948 if (! mPendingBroadcastTimeoutMessage) {
11949 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
11950 mHandler.sendMessageAtTime(msg, timeoutTime);
11951 mPendingBroadcastTimeoutMessage = true;
11952 }
11953 }
11954
11955 private final void cancelBroadcastTimeoutLocked() {
11956 if (mPendingBroadcastTimeoutMessage) {
11957 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG);
11958 mPendingBroadcastTimeoutMessage = false;
11959 }
11960 }
11961
11962 private final void broadcastTimeoutLocked(boolean fromMsg) {
11963 if (fromMsg) {
11964 mPendingBroadcastTimeoutMessage = false;
11965 }
11966
11967 if (mOrderedBroadcasts.size() == 0) {
11968 return;
11969 }
11970
11971 long now = SystemClock.uptimeMillis();
11972 BroadcastRecord r = mOrderedBroadcasts.get(0);
11973 if (fromMsg) {
11974 if (mDidDexOpt) {
11975 // Delay timeouts until dexopt finishes.
11976 mDidDexOpt = false;
11977 long timeoutTime = SystemClock.uptimeMillis() + BROADCAST_TIMEOUT;
11978 setBroadcastTimeoutLocked(timeoutTime);
11979 return;
11980 }
11981 if (! mProcessesReady) {
11982 // Only process broadcast timeouts if the system is ready. That way
11983 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
11984 // to do heavy lifting for system up.
11985 return;
11986 }
11987
11988 long timeoutTime = r.receiverTime + BROADCAST_TIMEOUT;
11989 if (timeoutTime > now) {
11990 // We can observe premature timeouts because we do not cancel and reset the
11991 // broadcast timeout message after each receiver finishes. Instead, we set up
11992 // an initial timeout then kick it down the road a little further as needed
11993 // when it expires.
11994 if (DEBUG_BROADCAST) Slog.v(TAG,
11995 "Premature timeout @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
11996 + timeoutTime);
11997 setBroadcastTimeoutLocked(timeoutTime);
11998 return;
11999 }
12000 }
12001
12002 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
12003 + ", started " + (now - r.receiverTime) + "ms ago");
12004 r.receiverTime = now;
12005 r.anrCount++;
12006
12007 // Current receiver has passed its expiration date.
12008 if (r.nextReceiver <= 0) {
12009 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
12010 return;
12011 }
12012
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012013 ProcessRecord app = null;
12014 String anrMessage = null;
12015
Jeff Brown4d94a762010-09-23 11:33:28 -070012016 Object curReceiver = r.receivers.get(r.nextReceiver-1);
12017 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
12018 logBroadcastReceiverDiscardLocked(r);
12019 if (curReceiver instanceof BroadcastFilter) {
12020 BroadcastFilter bf = (BroadcastFilter)curReceiver;
12021 if (bf.receiverList.pid != 0
12022 && bf.receiverList.pid != MY_PID) {
12023 synchronized (this.mPidsSelfLocked) {
12024 app = this.mPidsSelfLocked.get(
12025 bf.receiverList.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012027 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012028 } else {
12029 app = r.curApp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012030 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012031
Jeff Brown4d94a762010-09-23 11:33:28 -070012032 if (app != null) {
12033 anrMessage = "Broadcast of " + r.intent.toString();
12034 }
12035
12036 if (mPendingBroadcast == r) {
12037 mPendingBroadcast = null;
12038 }
12039
12040 // Move on to the next receiver.
12041 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
12042 r.resultExtras, r.resultAbort, true);
12043 scheduleBroadcastsLocked();
12044
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012045 if (anrMessage != null) {
Jeff Brown4d94a762010-09-23 11:33:28 -070012046 // Post the ANR to the handler since we do not want to process ANRs while
12047 // potentially holding our lock.
12048 mHandler.post(new AppNotResponding(app, anrMessage));
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012050 }
12051
12052 private final void processCurBroadcastLocked(BroadcastRecord r,
12053 ProcessRecord app) throws RemoteException {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012054 if (DEBUG_BROADCAST) Slog.v(TAG,
12055 "Process cur broadcast " + r + " for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012056 if (app.thread == null) {
12057 throw new RemoteException();
12058 }
12059 r.receiver = app.thread.asBinder();
12060 r.curApp = app;
12061 app.curReceiver = r;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012062 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012063
12064 // Tell the application to launch this receiver.
12065 r.intent.setComponent(r.curComponent);
12066
12067 boolean started = false;
12068 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012069 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012070 "Delivering to component " + r.curComponent
12071 + ": " + r);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070012072 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012073 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012074 compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075 r.resultCode, r.resultData, r.resultExtras, r.ordered);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012076 if (DEBUG_BROADCAST) Slog.v(TAG,
12077 "Process cur broadcast " + r + " DELIVERED for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012078 started = true;
12079 } finally {
12080 if (!started) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012081 if (DEBUG_BROADCAST) Slog.v(TAG,
12082 "Process cur broadcast " + r + ": NOT STARTED!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012083 r.receiver = null;
12084 r.curApp = null;
12085 app.curReceiver = null;
12086 }
12087 }
12088
12089 }
12090
Jeff Brown4d94a762010-09-23 11:33:28 -070012091 static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070012092 Intent intent, int resultCode, String data, Bundle extras,
12093 boolean ordered, boolean sticky) throws RemoteException {
Jeff Brown4d94a762010-09-23 11:33:28 -070012094 // Send the intent to the receiver asynchronously using one-way binder calls.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012095 if (app != null && app.thread != null) {
12096 // If we have an app thread, do the call through that so it is
12097 // correctly ordered with other one-way calls.
12098 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070012099 data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012100 } else {
Dianne Hackborn68d881c2009-10-05 13:58:17 -070012101 receiver.performReceive(intent, resultCode, data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012102 }
12103 }
12104
Jeff Brown4d94a762010-09-23 11:33:28 -070012105 private final void deliverToRegisteredReceiverLocked(BroadcastRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012106 BroadcastFilter filter, boolean ordered) {
12107 boolean skip = false;
12108 if (filter.requiredPermission != null) {
12109 int perm = checkComponentPermission(filter.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012110 r.callingPid, r.callingUid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012111 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012112 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012113 + r.intent.toString()
12114 + " from " + r.callerPackage + " (pid="
12115 + r.callingPid + ", uid=" + r.callingUid + ")"
12116 + " requires " + filter.requiredPermission
12117 + " due to registered receiver " + filter);
12118 skip = true;
12119 }
12120 }
12121 if (r.requiredPermission != null) {
12122 int perm = checkComponentPermission(r.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012123 filter.receiverList.pid, filter.receiverList.uid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012124 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012125 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012126 + r.intent.toString()
12127 + " to " + filter.receiverList.app
12128 + " (pid=" + filter.receiverList.pid
12129 + ", uid=" + filter.receiverList.uid + ")"
12130 + " requires " + r.requiredPermission
12131 + " due to sender " + r.callerPackage
12132 + " (uid " + r.callingUid + ")");
12133 skip = true;
12134 }
12135 }
12136
12137 if (!skip) {
12138 // If this is not being sent as an ordered broadcast, then we
12139 // don't want to touch the fields that keep track of the current
12140 // state of ordered broadcasts.
12141 if (ordered) {
12142 r.receiver = filter.receiverList.receiver.asBinder();
12143 r.curFilter = filter;
12144 filter.receiverList.curBroadcast = r;
12145 r.state = BroadcastRecord.CALL_IN_RECEIVE;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012146 if (filter.receiverList.app != null) {
12147 // Bump hosting application to no longer be in background
12148 // scheduling class. Note that we can't do that if there
12149 // isn't an app... but we can only be in that case for
12150 // things that directly call the IActivityManager API, which
12151 // are already core system stuff so don't matter for this.
12152 r.curApp = filter.receiverList.app;
12153 filter.receiverList.app.curReceiver = r;
12154 updateOomAdjLocked();
12155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012156 }
12157 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012158 if (DEBUG_BROADCAST_LIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012159 int seq = r.intent.getIntExtra("seq", -1);
Dianne Hackborn399cccb2010-04-13 22:57:49 -070012160 Slog.i(TAG, "Delivering to " + filter
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012161 + " (seq=" + seq + "): " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012162 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012163 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012164 new Intent(r.intent), r.resultCode,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012165 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012166 if (ordered) {
12167 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
12168 }
12169 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012170 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012171 if (ordered) {
12172 r.receiver = null;
12173 r.curFilter = null;
12174 filter.receiverList.curBroadcast = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012175 if (filter.receiverList.app != null) {
12176 filter.receiverList.app.curReceiver = null;
12177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012178 }
12179 }
12180 }
12181 }
12182
Dianne Hackborn12527f92009-11-11 17:39:50 -080012183 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
12184 if (r.callingUid < 0) {
12185 // This was from a registerReceiver() call; ignore it.
12186 return;
12187 }
12188 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
12189 MAX_BROADCAST_HISTORY-1);
12190 r.finishTime = SystemClock.uptimeMillis();
12191 mBroadcastHistory[0] = r;
12192 }
12193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012194 private final void processNextBroadcast(boolean fromMsg) {
12195 synchronized(this) {
12196 BroadcastRecord r;
12197
Joe Onorato8a9b2202010-02-26 18:56:32 -080012198 if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012199 + mParallelBroadcasts.size() + " broadcasts, "
Dianne Hackborn399cccb2010-04-13 22:57:49 -070012200 + mOrderedBroadcasts.size() + " ordered broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012201
12202 updateCpuStats();
12203
12204 if (fromMsg) {
12205 mBroadcastsScheduled = false;
12206 }
12207
12208 // First, deliver any non-serialized broadcasts right away.
12209 while (mParallelBroadcasts.size() > 0) {
12210 r = mParallelBroadcasts.remove(0);
Dianne Hackborn12527f92009-11-11 17:39:50 -080012211 r.dispatchTime = SystemClock.uptimeMillis();
Dianne Hackbornd99b2932011-08-18 14:39:58 -070012212 r.dispatchClockTime = System.currentTimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012213 final int N = r.receivers.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012214 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012215 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012216 for (int i=0; i<N; i++) {
12217 Object target = r.receivers.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012218 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070012219 "Delivering non-ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012220 + target + ": " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070012221 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012222 }
Dianne Hackborn12527f92009-11-11 17:39:50 -080012223 addBroadcastToHistoryLocked(r);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012224 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012225 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012226 }
12227
12228 // Now take care of the next serialized one...
12229
12230 // If we are waiting for a process to come up to handle the next
12231 // broadcast, then do nothing at this point. Just in case, we
12232 // check that the process we're waiting for still exists.
12233 if (mPendingBroadcast != null) {
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070012234 if (DEBUG_BROADCAST_LIGHT) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012235 Slog.v(TAG, "processNextBroadcast: waiting for "
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070012236 + mPendingBroadcast.curApp);
12237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012238
12239 boolean isDead;
12240 synchronized (mPidsSelfLocked) {
12241 isDead = (mPidsSelfLocked.get(mPendingBroadcast.curApp.pid) == null);
12242 }
12243 if (!isDead) {
12244 // It's still alive, so keep waiting
12245 return;
12246 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012247 Slog.w(TAG, "pending app " + mPendingBroadcast.curApp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012248 + " died before responding to broadcast");
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012249 mPendingBroadcast.state = BroadcastRecord.IDLE;
12250 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012251 mPendingBroadcast = null;
12252 }
12253 }
12254
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012255 boolean looped = false;
12256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012257 do {
12258 if (mOrderedBroadcasts.size() == 0) {
12259 // No more broadcasts pending, so all done!
12260 scheduleAppGcsLocked();
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012261 if (looped) {
12262 // If we had finished the last ordered broadcast, then
12263 // make sure all processes have correct oom and sched
12264 // adjustments.
12265 updateOomAdjLocked();
12266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012267 return;
12268 }
12269 r = mOrderedBroadcasts.get(0);
12270 boolean forceReceive = false;
12271
12272 // Ensure that even if something goes awry with the timeout
12273 // detection, we catch "hung" broadcasts here, discard them,
Jeff Hamiltonacf84742010-05-25 22:10:18 -050012274 // and continue to make progress.
12275 //
12276 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
Jeff Brown4d94a762010-09-23 11:33:28 -070012277 // receivers don't get executed with timeouts. They're intended for
Jeff Hamiltonacf84742010-05-25 22:10:18 -050012278 // one time heavy lifting after system upgrades and can take
12279 // significant amounts of time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012280 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012281 if (mProcessesReady && r.dispatchTime > 0) {
Jeff Hamiltonacf84742010-05-25 22:10:18 -050012282 long now = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012283 if ((numReceivers > 0) &&
12284 (now > r.dispatchTime + (2*BROADCAST_TIMEOUT*numReceivers))) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012285 Slog.w(TAG, "Hung broadcast discarded after timeout failure:"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012286 + " now=" + now
12287 + " dispatchTime=" + r.dispatchTime
Dianne Hackborn12527f92009-11-11 17:39:50 -080012288 + " startTime=" + r.receiverTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012289 + " intent=" + r.intent
12290 + " numReceivers=" + numReceivers
12291 + " nextReceiver=" + r.nextReceiver
12292 + " state=" + r.state);
Jeff Brown4d94a762010-09-23 11:33:28 -070012293 broadcastTimeoutLocked(false); // forcibly finish this broadcast
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012294 forceReceive = true;
12295 r.state = BroadcastRecord.IDLE;
12296 }
12297 }
12298
12299 if (r.state != BroadcastRecord.IDLE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012300 if (DEBUG_BROADCAST) Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012301 "processNextBroadcast() called when not idle (state="
12302 + r.state + ")");
12303 return;
12304 }
12305
12306 if (r.receivers == null || r.nextReceiver >= numReceivers
12307 || r.resultAbort || forceReceive) {
12308 // No more receivers for this broadcast! Send the final
12309 // result if requested...
12310 if (r.resultTo != null) {
12311 try {
12312 if (DEBUG_BROADCAST) {
12313 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012314 Slog.i(TAG, "Finishing broadcast " + r.intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012315 + " seq=" + seq + " app=" + r.callerApp);
12316 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012317 performReceiveLocked(r.callerApp, r.resultTo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012318 new Intent(r.intent), r.resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070012319 r.resultData, r.resultExtras, false, false);
Johannes Carlssonb5a86542010-10-27 10:08:10 +020012320 // Set this to null so that the reference
12321 // (local and remote) isnt kept in the mBroadcastHistory.
12322 r.resultTo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012323 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012324 Slog.w(TAG, "Failure sending broadcast result of " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012325 }
12326 }
12327
Joe Onorato8a9b2202010-02-26 18:56:32 -080012328 if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
Jeff Brown4d94a762010-09-23 11:33:28 -070012329 cancelBroadcastTimeoutLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012330
Joe Onorato8a9b2202010-02-26 18:56:32 -080012331 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012332 + r);
12333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012334 // ... and on to the next...
Dianne Hackborn12527f92009-11-11 17:39:50 -080012335 addBroadcastToHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012336 mOrderedBroadcasts.remove(0);
12337 r = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012338 looped = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012339 continue;
12340 }
12341 } while (r == null);
12342
12343 // Get the next receiver...
12344 int recIdx = r.nextReceiver++;
12345
12346 // Keep track of when this receiver started, and make sure there
12347 // is a timeout message pending to kill it if need be.
Dianne Hackborn12527f92009-11-11 17:39:50 -080012348 r.receiverTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012349 if (recIdx == 0) {
Dianne Hackborn12527f92009-11-11 17:39:50 -080012350 r.dispatchTime = r.receiverTime;
Dianne Hackbornd99b2932011-08-18 14:39:58 -070012351 r.dispatchClockTime = System.currentTimeMillis();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012352 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012353 + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070012354 }
12355 if (! mPendingBroadcastTimeoutMessage) {
12356 long timeoutTime = r.receiverTime + BROADCAST_TIMEOUT;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012357 if (DEBUG_BROADCAST) Slog.v(TAG,
Jeff Brown4d94a762010-09-23 11:33:28 -070012358 "Submitting BROADCAST_TIMEOUT_MSG for " + r + " at " + timeoutTime);
12359 setBroadcastTimeoutLocked(timeoutTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012360 }
12361
12362 Object nextReceiver = r.receivers.get(recIdx);
12363 if (nextReceiver instanceof BroadcastFilter) {
12364 // Simple case: this is a registered receiver who gets
12365 // a direct call.
12366 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012367 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070012368 "Delivering ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012369 + filter + ": " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070012370 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012371 if (r.receiver == null || !r.ordered) {
12372 // The receiver has already finished, so schedule to
12373 // process the next one.
Dianne Hackborn399cccb2010-04-13 22:57:49 -070012374 if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing: ordered="
12375 + r.ordered + " receiver=" + r.receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012376 r.state = BroadcastRecord.IDLE;
12377 scheduleBroadcastsLocked();
12378 }
12379 return;
12380 }
12381
12382 // Hard case: need to instantiate the receiver, possibly
12383 // starting its application process to host it.
12384
12385 ResolveInfo info =
12386 (ResolveInfo)nextReceiver;
12387
12388 boolean skip = false;
12389 int perm = checkComponentPermission(info.activityInfo.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012390 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
12391 info.activityInfo.exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012392 if (perm != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012393 if (!info.activityInfo.exported) {
12394 Slog.w(TAG, "Permission Denial: broadcasting "
12395 + r.intent.toString()
12396 + " from " + r.callerPackage + " (pid=" + r.callingPid
12397 + ", uid=" + r.callingUid + ")"
12398 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
12399 + " due to receiver " + info.activityInfo.packageName
12400 + "/" + info.activityInfo.name);
12401 } else {
12402 Slog.w(TAG, "Permission Denial: broadcasting "
12403 + r.intent.toString()
12404 + " from " + r.callerPackage + " (pid=" + r.callingPid
12405 + ", uid=" + r.callingUid + ")"
12406 + " requires " + info.activityInfo.permission
12407 + " due to receiver " + info.activityInfo.packageName
12408 + "/" + info.activityInfo.name);
12409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012410 skip = true;
12411 }
Dianne Hackbornd99b2932011-08-18 14:39:58 -070012412 if (info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012413 r.requiredPermission != null) {
12414 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012415 perm = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012416 checkPermission(r.requiredPermission,
12417 info.activityInfo.applicationInfo.packageName);
12418 } catch (RemoteException e) {
12419 perm = PackageManager.PERMISSION_DENIED;
12420 }
12421 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012422 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012423 + r.intent + " to "
12424 + info.activityInfo.applicationInfo.packageName
12425 + " requires " + r.requiredPermission
12426 + " due to sender " + r.callerPackage
12427 + " (uid " + r.callingUid + ")");
12428 skip = true;
12429 }
12430 }
12431 if (r.curApp != null && r.curApp.crashing) {
12432 // If the target process is crashing, just skip it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012433 if (DEBUG_BROADCAST) Slog.v(TAG,
12434 "Skipping deliver ordered " + r + " to " + r.curApp
12435 + ": process crashing");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012436 skip = true;
12437 }
12438
12439 if (skip) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012440 if (DEBUG_BROADCAST) Slog.v(TAG,
12441 "Skipping delivery of ordered " + r + " for whatever reason");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012442 r.receiver = null;
12443 r.curFilter = null;
12444 r.state = BroadcastRecord.IDLE;
12445 scheduleBroadcastsLocked();
12446 return;
12447 }
12448
12449 r.state = BroadcastRecord.APP_RECEIVE;
12450 String targetProcess = info.activityInfo.processName;
12451 r.curComponent = new ComponentName(
12452 info.activityInfo.applicationInfo.packageName,
12453 info.activityInfo.name);
12454 r.curReceiver = info.activityInfo;
12455
Dianne Hackborne7f97212011-02-24 14:40:20 -080012456 // Broadcast is being executed, its package can't be stopped.
12457 try {
12458 AppGlobals.getPackageManager().setPackageStoppedState(
12459 r.curComponent.getPackageName(), false);
12460 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012461 } catch (IllegalArgumentException e) {
12462 Slog.w(TAG, "Failed trying to unstop package "
12463 + r.curComponent.getPackageName() + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012464 }
12465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012466 // Is this receiver's application already running?
12467 ProcessRecord app = getProcessRecordLocked(targetProcess,
12468 info.activityInfo.applicationInfo.uid);
12469 if (app != null && app.thread != null) {
12470 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012471 app.addPackage(info.activityInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012472 processCurBroadcastLocked(r, app);
12473 return;
12474 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012475 Slog.w(TAG, "Exception when sending broadcast to "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012476 + r.curComponent, e);
12477 }
12478
12479 // If a dead object exception was thrown -- fall through to
12480 // restart the application.
12481 }
12482
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012483 // Not running -- get it started, to be executed when the app comes up.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012484 if (DEBUG_BROADCAST) Slog.v(TAG,
12485 "Need to start app " + targetProcess + " for broadcast " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012486 if ((r.curApp=startProcessLocked(targetProcess,
12487 info.activityInfo.applicationInfo, true,
12488 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012489 "broadcast", r.curComponent,
12490 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0))
12491 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012492 // Ah, this recipient is unavailable. Finish it if necessary,
12493 // and mark the broadcast record as ready for the next.
Joe Onorato8a9b2202010-02-26 18:56:32 -080012494 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012495 + info.activityInfo.applicationInfo.packageName + "/"
12496 + info.activityInfo.applicationInfo.uid + " for broadcast "
12497 + r.intent + ": process is bad");
Jeff Brown4d94a762010-09-23 11:33:28 -070012498 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012499 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
12500 r.resultExtras, r.resultAbort, true);
12501 scheduleBroadcastsLocked();
12502 r.state = BroadcastRecord.IDLE;
12503 return;
12504 }
12505
12506 mPendingBroadcast = r;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012507 mPendingBroadcastRecvIndex = recIdx;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012508 }
12509 }
12510
12511 // =========================================================
12512 // INSTRUMENTATION
12513 // =========================================================
12514
12515 public boolean startInstrumentation(ComponentName className,
12516 String profileFile, int flags, Bundle arguments,
12517 IInstrumentationWatcher watcher) {
12518 // Refuse possible leaked file descriptors
12519 if (arguments != null && arguments.hasFileDescriptors()) {
12520 throw new IllegalArgumentException("File descriptors passed in Bundle");
12521 }
12522
12523 synchronized(this) {
12524 InstrumentationInfo ii = null;
12525 ApplicationInfo ai = null;
12526 try {
12527 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012528 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012529 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012530 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012531 } catch (PackageManager.NameNotFoundException e) {
12532 }
12533 if (ii == null) {
12534 reportStartInstrumentationFailure(watcher, className,
12535 "Unable to find instrumentation info for: " + className);
12536 return false;
12537 }
12538 if (ai == null) {
12539 reportStartInstrumentationFailure(watcher, className,
12540 "Unable to find instrumentation target package: " + ii.targetPackage);
12541 return false;
12542 }
12543
12544 int match = mContext.getPackageManager().checkSignatures(
12545 ii.targetPackage, ii.packageName);
12546 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12547 String msg = "Permission Denial: starting instrumentation "
12548 + className + " from pid="
12549 + Binder.getCallingPid()
12550 + ", uid=" + Binder.getCallingPid()
12551 + " not allowed because package " + ii.packageName
12552 + " does not have a signature matching the target "
12553 + ii.targetPackage;
12554 reportStartInstrumentationFailure(watcher, className, msg);
12555 throw new SecurityException(msg);
12556 }
12557
12558 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012559 // Instrumentation can kill and relaunch even persistent processes
12560 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012561 ProcessRecord app = addAppLocked(ai);
12562 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012563 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012564 app.instrumentationProfileFile = profileFile;
12565 app.instrumentationArguments = arguments;
12566 app.instrumentationWatcher = watcher;
12567 app.instrumentationResultClass = className;
12568 Binder.restoreCallingIdentity(origId);
12569 }
12570
12571 return true;
12572 }
12573
12574 /**
12575 * Report errors that occur while attempting to start Instrumentation. Always writes the
12576 * error to the logs, but if somebody is watching, send the report there too. This enables
12577 * the "am" command to report errors with more information.
12578 *
12579 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12580 * @param cn The component name of the instrumentation.
12581 * @param report The error report.
12582 */
12583 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12584 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012585 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012586 try {
12587 if (watcher != null) {
12588 Bundle results = new Bundle();
12589 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12590 results.putString("Error", report);
12591 watcher.instrumentationStatus(cn, -1, results);
12592 }
12593 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012594 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012595 }
12596 }
12597
12598 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12599 if (app.instrumentationWatcher != null) {
12600 try {
12601 // NOTE: IInstrumentationWatcher *must* be oneway here
12602 app.instrumentationWatcher.instrumentationFinished(
12603 app.instrumentationClass,
12604 resultCode,
12605 results);
12606 } catch (RemoteException e) {
12607 }
12608 }
12609 app.instrumentationWatcher = null;
12610 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012611 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012612 app.instrumentationProfileFile = null;
12613 app.instrumentationArguments = null;
12614
Christopher Tate3dacd842011-08-19 14:56:15 -070012615 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012616 }
12617
12618 public void finishInstrumentation(IApplicationThread target,
12619 int resultCode, Bundle results) {
12620 // Refuse possible leaked file descriptors
12621 if (results != null && results.hasFileDescriptors()) {
12622 throw new IllegalArgumentException("File descriptors passed in Intent");
12623 }
12624
12625 synchronized(this) {
12626 ProcessRecord app = getRecordForAppLocked(target);
12627 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012628 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 return;
12630 }
12631 final long origId = Binder.clearCallingIdentity();
12632 finishInstrumentationLocked(app, resultCode, results);
12633 Binder.restoreCallingIdentity(origId);
12634 }
12635 }
12636
12637 // =========================================================
12638 // CONFIGURATION
12639 // =========================================================
12640
12641 public ConfigurationInfo getDeviceConfigurationInfo() {
12642 ConfigurationInfo config = new ConfigurationInfo();
12643 synchronized (this) {
12644 config.reqTouchScreen = mConfiguration.touchscreen;
12645 config.reqKeyboardType = mConfiguration.keyboard;
12646 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012647 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12648 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012649 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12650 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012651 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12652 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012653 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12654 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012655 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012656 }
12657 return config;
12658 }
12659
12660 public Configuration getConfiguration() {
12661 Configuration ci;
12662 synchronized(this) {
12663 ci = new Configuration(mConfiguration);
12664 }
12665 return ci;
12666 }
12667
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012668 public void updatePersistentConfiguration(Configuration values) {
12669 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12670 "updateConfiguration()");
12671 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12672 "updateConfiguration()");
12673 if (values == null) {
12674 throw new NullPointerException("Configuration must not be null");
12675 }
12676
12677 synchronized(this) {
12678 final long origId = Binder.clearCallingIdentity();
12679 updateConfigurationLocked(values, null, true);
12680 Binder.restoreCallingIdentity(origId);
12681 }
12682 }
12683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012684 public void updateConfiguration(Configuration values) {
12685 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12686 "updateConfiguration()");
12687
12688 synchronized(this) {
12689 if (values == null && mWindowManager != null) {
12690 // sentinel: fetch the current configuration from the window manager
12691 values = mWindowManager.computeNewConfiguration();
12692 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012693
12694 if (mWindowManager != null) {
12695 mProcessList.applyDisplaySize(mWindowManager);
12696 }
12697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012698 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012699 if (values != null) {
12700 Settings.System.clearConfiguration(values);
12701 }
12702 updateConfigurationLocked(values, null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012703 Binder.restoreCallingIdentity(origId);
12704 }
12705 }
12706
12707 /**
12708 * Do either or both things: (1) change the current configuration, and (2)
12709 * make sure the given activity is running with the (now) current
12710 * configuration. Returns true if the activity has been left running, or
12711 * false if <var>starting</var> is being destroyed to match the new
12712 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012713 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012714 */
12715 public boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012716 ActivityRecord starting, boolean persistent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012717 int changes = 0;
12718
12719 boolean kept = true;
12720
12721 if (values != null) {
12722 Configuration newConfig = new Configuration(mConfiguration);
12723 changes = newConfig.updateFrom(values);
12724 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012725 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012726 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012727 }
12728
Doug Zongker2bec3d42009-12-04 12:52:44 -080012729 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012730
12731 if (values.locale != null) {
12732 saveLocaleLocked(values.locale,
12733 !values.locale.equals(mConfiguration.locale),
12734 values.userSetLocale);
12735 }
12736
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012737 mConfigurationSeq++;
12738 if (mConfigurationSeq <= 0) {
12739 mConfigurationSeq = 1;
12740 }
12741 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012742 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012743 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012744
12745 AttributeCache ac = AttributeCache.instance();
12746 if (ac != null) {
12747 ac.updateConfiguration(mConfiguration);
12748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012749
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012750 // Make sure all resources in our process are updated
12751 // right now, so that anyone who is going to retrieve
12752 // resource values after we return will be sure to get
12753 // the new ones. This is especially important during
12754 // boot, where the first config change needs to guarantee
12755 // all resources have that config before following boot
12756 // code is executed.
12757 mSystemThread.applyConfigurationToResources(newConfig);
12758
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012759 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012760 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
12761 msg.obj = new Configuration(mConfiguration);
12762 mHandler.sendMessage(msg);
12763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012764
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012765 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12766 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012767 try {
12768 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012769 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012770 + app.processName + " new config " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012771 app.thread.scheduleConfigurationChanged(mConfiguration);
12772 }
12773 } catch (Exception e) {
12774 }
12775 }
12776 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012777 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12778 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012779 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
12780 null, false, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012781 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12782 broadcastIntentLocked(null, null,
12783 new Intent(Intent.ACTION_LOCALE_CHANGED),
12784 null, null, 0, null, null,
12785 null, false, false, MY_PID, Process.SYSTEM_UID);
12786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012787 }
12788 }
12789
12790 if (changes != 0 && starting == null) {
12791 // If the configuration changed, and the caller is not already
12792 // in the process of starting an activity, then find the top
12793 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012794 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012795 }
12796
12797 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012798 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012799 // And we need to make sure at this point that all other activities
12800 // are made visible with the correct configuration.
12801 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012802 }
12803
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012804 if (values != null && mWindowManager != null) {
12805 mWindowManager.setNewConfiguration(mConfiguration);
12806 }
12807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012808 return kept;
12809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012810
12811 /**
12812 * Save the locale. You must be inside a synchronized (this) block.
12813 */
12814 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12815 if(isDiff) {
12816 SystemProperties.set("user.language", l.getLanguage());
12817 SystemProperties.set("user.region", l.getCountry());
12818 }
12819
12820 if(isPersist) {
12821 SystemProperties.set("persist.sys.language", l.getLanguage());
12822 SystemProperties.set("persist.sys.country", l.getCountry());
12823 SystemProperties.set("persist.sys.localevar", l.getVariant());
12824 }
12825 }
12826
12827 // =========================================================
12828 // LIFETIME MANAGEMENT
12829 // =========================================================
12830
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012831 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
12832 ProcessRecord TOP_APP, boolean recursed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012833 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012834 // This adjustment has already been computed. If we are calling
12835 // from the top, we may have already computed our adjustment with
12836 // an earlier hidden adjustment that isn't really for us... if
12837 // so, use the new hidden adjustment.
12838 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012839 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012840 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012841 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012842 }
12843
12844 if (app.thread == null) {
12845 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012846 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012847 return (app.curAdj=ProcessList.EMPTY_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012848 }
12849
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012850 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12851 app.adjSource = null;
12852 app.adjTarget = null;
12853 app.empty = false;
12854 app.hidden = false;
12855
12856 final int activitiesSize = app.activities.size();
12857
Dianne Hackborn7d608422011-08-07 16:24:18 -070012858 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012859 // The max adjustment doesn't allow this app to be anything
12860 // below foreground, so it is not worth doing work for it.
12861 app.adjType = "fixed";
12862 app.adjSeq = mAdjSeq;
12863 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012864 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012865 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012866 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012867 // System process can do UI, and when they do we want to have
12868 // them trim their memory after the user leaves the UI. To
12869 // facilitate this, here we need to determine whether or not it
12870 // is currently showing UI.
12871 app.systemNoUi = true;
12872 if (app == TOP_APP) {
12873 app.systemNoUi = false;
12874 } else if (activitiesSize > 0) {
12875 for (int j = 0; j < activitiesSize; j++) {
12876 final ActivityRecord r = app.activities.get(j);
12877 if (r.visible) {
12878 app.systemNoUi = false;
12879 break;
12880 }
12881 }
12882 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012883 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012884 }
12885
12886 final boolean hadForegroundActivities = app.foregroundActivities;
12887
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012888 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012889 app.keeping = false;
12890 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012891
The Android Open Source Project4df24232009-03-05 14:34:35 -080012892 // Determine the importance of the process, starting with most
12893 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012894 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012895 int schedGroup;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012896 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012897 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012898 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012899 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012900 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012901 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012902 } else if (app.instrumentationClass != null) {
12903 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012904 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012905 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012906 app.adjType = "instrumentation";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012907 } else if (app.curReceiver != null ||
12908 (mPendingBroadcast != null && mPendingBroadcast.curApp == app)) {
12909 // An app that is currently receiving a broadcast also
12910 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012911 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012912 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012913 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012914 } else if (app.executingServices.size() > 0) {
12915 // An app that is currently executing a service callback also
12916 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012917 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012918 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012919 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012920 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012921 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012922 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012923 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012924 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012925 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012926 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012927 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012928 // A very not-needed process. If this is lower in the lru list,
12929 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012930 adj = hiddenAdj;
12931 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012932 app.hidden = true;
12933 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012934 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012935 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012936
12937 // Examine all activities if not already foreground.
12938 if (!app.foregroundActivities && activitiesSize > 0) {
12939 for (int j = 0; j < activitiesSize; j++) {
12940 final ActivityRecord r = app.activities.get(j);
12941 if (r.visible) {
12942 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012943 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12944 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012945 app.adjType = "visible";
12946 }
12947 schedGroup = Process.THREAD_GROUP_DEFAULT;
12948 app.hidden = false;
12949 app.foregroundActivities = true;
12950 break;
12951 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
12952 || r.state == ActivityState.STOPPING) {
12953 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012954 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12955 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012956 app.adjType = "stopping";
12957 }
12958 app.foregroundActivities = true;
12959 }
12960 }
12961 }
12962
Dianne Hackborn7d608422011-08-07 16:24:18 -070012963 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012964 if (app.foregroundServices) {
12965 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012966 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012967 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012968 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012969 } else if (app.forcingToForeground != null) {
12970 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012971 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012972 app.adjType = "force-foreground";
12973 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012974 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012975 }
12976 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012977
Dianne Hackborn7d608422011-08-07 16:24:18 -070012978 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012979 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012980 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012981 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12982 app.adjType = "heavy";
12983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012984
Dianne Hackborn7d608422011-08-07 16:24:18 -070012985 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012986 // This process is hosting what we currently consider to be the
12987 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012988 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012989 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12990 app.adjType = "home";
12991 }
12992
Joe Onorato8a9b2202010-02-26 18:56:32 -080012993 //Slog.i(TAG, "OOM " + app + ": initial adj=" + adj);
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012994
The Android Open Source Project4df24232009-03-05 14:34:35 -080012995 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012996 // there are applications dependent on our services or providers, but
12997 // this gives us a baseline and makes sure we don't get into an
12998 // infinite recursion.
12999 app.adjSeq = mAdjSeq;
13000 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013001
Christopher Tate6fa95972009-06-05 18:43:55 -070013002 if (mBackupTarget != null && app == mBackupTarget.app) {
13003 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013004 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013005 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013006 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013007 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013008 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013009 }
13010 }
13011
Dianne Hackborn7d608422011-08-07 16:24:18 -070013012 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013013 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013014 final long now = SystemClock.uptimeMillis();
13015 // This process is more important if the top activity is
13016 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013017 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013018 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013019 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013020 if (s.startRequested) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013021 if (app.hasShownUi) {
13022 // If this process has shown some UI, let it immediately
13023 // go to the LRU list because it may be pretty heavy with
13024 // UI stuff. We'll tag it with a label just to help
13025 // debug and understand what is going on.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013026 if (adj > ProcessList.SECONDARY_SERVER_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013027 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013028 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013029 } else {
13030 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13031 // This service has seen some activity within
13032 // recent memory, so we will keep its process ahead
13033 // of the background processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013034 if (adj > ProcessList.SECONDARY_SERVER_ADJ) {
13035 adj = ProcessList.SECONDARY_SERVER_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013036 app.adjType = "started-services";
13037 app.hidden = false;
13038 }
13039 }
13040 // If we have let the service slide into the background
13041 // state, still have some text describing what it is doing
13042 // even though the service no longer has an impact.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013043 if (adj > ProcessList.SECONDARY_SERVER_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013044 app.adjType = "started-bg-services";
13045 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013046 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013047 // Don't kill this process because it is doing work; it
13048 // has said it is doing work.
13049 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013050 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013051 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013052 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013053 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013054 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013055 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013056 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013057 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013058 // XXX should compute this based on the max of
13059 // all connected clients.
13060 ConnectionRecord cr = clist.get(i);
13061 if (cr.binding.client == app) {
13062 // Binding to ourself is not interesting.
13063 continue;
13064 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013065 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013066 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013067 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013068 int myHiddenAdj = hiddenAdj;
13069 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013070 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013071 myHiddenAdj = client.hiddenAdj;
13072 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013073 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013074 }
13075 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013076 clientAdj = computeOomAdjLocked(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013077 client, myHiddenAdj, TOP_APP, true);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013078 String adjType = null;
13079 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13080 // Not doing bind OOM management, so treat
13081 // this guy more like a started service.
13082 if (app.hasShownUi) {
13083 // If this process has shown some UI, let it immediately
13084 // go to the LRU list because it may be pretty heavy with
13085 // UI stuff. We'll tag it with a label just to help
13086 // debug and understand what is going on.
13087 if (adj > clientAdj) {
13088 adjType = "bound-bg-ui-services";
13089 }
13090 clientAdj = adj;
13091 } else {
13092 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13093 // This service has not seen activity within
13094 // recent memory, so allow it to drop to the
13095 // LRU list if there is no other reason to keep
13096 // it around. We'll also tag it with a label just
13097 // to help debug and undertand what is going on.
13098 if (adj > clientAdj) {
13099 adjType = "bound-bg-services";
13100 }
13101 clientAdj = adj;
13102 }
13103 }
13104 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013105 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013106 // If this process has recently shown UI, and
13107 // the process that is binding to it is less
13108 // important than being visible, then we don't
13109 // care about the binding as much as we care
13110 // about letting this process get into the LRU
13111 // list to be killed and restarted if needed for
13112 // memory.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013113 if (app.hasShownUi && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013114 adjType = "bound-bg-ui-services";
13115 } else {
13116 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13117 |Context.BIND_IMPORTANT)) != 0) {
13118 adj = clientAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013119 } else if (clientAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013120 adj = clientAdj;
13121 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013122 adj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013123 }
13124 if (!client.hidden) {
13125 app.hidden = false;
13126 }
13127 if (client.keeping) {
13128 app.keeping = true;
13129 }
13130 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013131 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013132 }
13133 if (adjType != null) {
13134 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013135 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13136 .REASON_SERVICE_IN_USE;
13137 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013138 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013139 app.adjTarget = s.name;
13140 }
13141 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13142 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13143 schedGroup = Process.THREAD_GROUP_DEFAULT;
13144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013145 }
13146 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013147 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13148 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013149 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013150 (a.visible || a.state == ActivityState.RESUMED
13151 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013152 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013153 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13154 schedGroup = Process.THREAD_GROUP_DEFAULT;
13155 }
13156 app.hidden = false;
13157 app.adjType = "service";
13158 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13159 .REASON_SERVICE_IN_USE;
13160 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013161 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013162 app.adjTarget = s.name;
13163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013165 }
13166 }
13167 }
13168 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013169
Dianne Hackborn287952c2010-09-22 22:34:31 -070013170 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013171 // would like to avoid killing it unless it would prevent the current
13172 // application from running. By default we put the process in
13173 // with the rest of the background processes; as we scan through
13174 // its services we may bump it up from there.
13175 if (adj > hiddenAdj) {
13176 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013177 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013178 app.adjType = "bg-services";
13179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013180 }
13181
Dianne Hackborn7d608422011-08-07 16:24:18 -070013182 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013183 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013184 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013185 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013186 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013187 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013188 if (cpr.clients.size() != 0) {
13189 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013190 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013191 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013192 if (client == app) {
13193 // Being our own client is not interesting.
13194 continue;
13195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013196 int myHiddenAdj = hiddenAdj;
13197 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013198 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013199 myHiddenAdj = client.hiddenAdj;
13200 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013201 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013202 }
13203 }
13204 int clientAdj = computeOomAdjLocked(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013205 client, myHiddenAdj, TOP_APP, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013206 if (adj > clientAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013207 if (app.hasShownUi && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013208 app.adjType = "bg-ui-provider";
13209 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013210 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13211 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013212 app.adjType = "provider";
13213 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013214 if (!client.hidden) {
13215 app.hidden = false;
13216 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013217 if (client.keeping) {
13218 app.keeping = true;
13219 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013220 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13221 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013222 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013223 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013224 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013225 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013226 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13227 schedGroup = Process.THREAD_GROUP_DEFAULT;
13228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013229 }
13230 }
13231 // If the provider has external (non-framework) process
13232 // dependencies, ensure that its adjustment is at least
13233 // FOREGROUND_APP_ADJ.
13234 if (cpr.externals != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013235 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13236 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013237 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013238 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013239 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013240 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013241 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013242 }
13243 }
13244 }
13245 }
13246
13247 app.curRawAdj = adj;
13248
Joe Onorato8a9b2202010-02-26 18:56:32 -080013249 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013250 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13251 if (adj > app.maxAdj) {
13252 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013253 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013254 schedGroup = Process.THREAD_GROUP_DEFAULT;
13255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013256 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013257 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013258 app.keeping = true;
13259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013260
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013261 if (app.hasAboveClient) {
13262 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13263 // then we need to drop its adjustment to be lower than the service's
13264 // in order to honor the request. We want to drop it by one adjustment
13265 // level... but there is special meaning applied to various levels so
13266 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013267 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013268 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013269 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13270 adj = ProcessList.VISIBLE_APP_ADJ;
13271 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13272 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13273 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13274 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
13275 } else if (adj < ProcessList.EMPTY_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013276 adj++;
13277 }
13278 }
13279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013280 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013281 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013282
13283 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013284 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13285 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013286 }
13287
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013288 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013289 }
13290
13291 /**
13292 * Ask a given process to GC right now.
13293 */
13294 final void performAppGcLocked(ProcessRecord app) {
13295 try {
13296 app.lastRequestedGc = SystemClock.uptimeMillis();
13297 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013298 if (app.reportLowMemory) {
13299 app.reportLowMemory = false;
13300 app.thread.scheduleLowMemory();
13301 } else {
13302 app.thread.processInBackground();
13303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013304 }
13305 } catch (Exception e) {
13306 // whatever.
13307 }
13308 }
13309
13310 /**
13311 * Returns true if things are idle enough to perform GCs.
13312 */
Josh Bartel7f208742010-02-25 11:01:44 -060013313 private final boolean canGcNowLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013314 return mParallelBroadcasts.size() == 0
13315 && mOrderedBroadcasts.size() == 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013316 && (mSleeping || (mMainStack.mResumedActivity != null &&
13317 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013318 }
13319
13320 /**
13321 * Perform GCs on all processes that are waiting for it, but only
13322 * if things are idle.
13323 */
13324 final void performAppGcsLocked() {
13325 final int N = mProcessesToGc.size();
13326 if (N <= 0) {
13327 return;
13328 }
Josh Bartel7f208742010-02-25 11:01:44 -060013329 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013330 while (mProcessesToGc.size() > 0) {
13331 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013332 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013333 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13334 <= SystemClock.uptimeMillis()) {
13335 // To avoid spamming the system, we will GC processes one
13336 // at a time, waiting a few seconds between each.
13337 performAppGcLocked(proc);
13338 scheduleAppGcsLocked();
13339 return;
13340 } else {
13341 // It hasn't been long enough since we last GCed this
13342 // process... put it in the list to wait for its time.
13343 addProcessToGcListLocked(proc);
13344 break;
13345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013346 }
13347 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013348
13349 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013350 }
13351 }
13352
13353 /**
13354 * If all looks good, perform GCs on all processes waiting for them.
13355 */
13356 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013357 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013358 performAppGcsLocked();
13359 return;
13360 }
13361 // Still not idle, wait some more.
13362 scheduleAppGcsLocked();
13363 }
13364
13365 /**
13366 * Schedule the execution of all pending app GCs.
13367 */
13368 final void scheduleAppGcsLocked() {
13369 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013370
13371 if (mProcessesToGc.size() > 0) {
13372 // Schedule a GC for the time to the next process.
13373 ProcessRecord proc = mProcessesToGc.get(0);
13374 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13375
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013376 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013377 long now = SystemClock.uptimeMillis();
13378 if (when < (now+GC_TIMEOUT)) {
13379 when = now + GC_TIMEOUT;
13380 }
13381 mHandler.sendMessageAtTime(msg, when);
13382 }
13383 }
13384
13385 /**
13386 * Add a process to the array of processes waiting to be GCed. Keeps the
13387 * list in sorted order by the last GC time. The process can't already be
13388 * on the list.
13389 */
13390 final void addProcessToGcListLocked(ProcessRecord proc) {
13391 boolean added = false;
13392 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13393 if (mProcessesToGc.get(i).lastRequestedGc <
13394 proc.lastRequestedGc) {
13395 added = true;
13396 mProcessesToGc.add(i+1, proc);
13397 break;
13398 }
13399 }
13400 if (!added) {
13401 mProcessesToGc.add(0, proc);
13402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013403 }
13404
13405 /**
13406 * Set up to ask a process to GC itself. This will either do it
13407 * immediately, or put it on the list of processes to gc the next
13408 * time things are idle.
13409 */
13410 final void scheduleAppGcLocked(ProcessRecord app) {
13411 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013412 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013413 return;
13414 }
13415 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013416 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013417 scheduleAppGcsLocked();
13418 }
13419 }
13420
Dianne Hackborn287952c2010-09-22 22:34:31 -070013421 final void checkExcessivePowerUsageLocked(boolean doKills) {
13422 updateCpuStatsNow();
13423
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013424 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013425 boolean doWakeKills = doKills;
13426 boolean doCpuKills = doKills;
13427 if (mLastPowerCheckRealtime == 0) {
13428 doWakeKills = false;
13429 }
13430 if (mLastPowerCheckUptime == 0) {
13431 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013432 }
13433 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013434 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013435 }
13436 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013437 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13438 final long curUptime = SystemClock.uptimeMillis();
13439 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13440 mLastPowerCheckRealtime = curRealtime;
13441 mLastPowerCheckUptime = curUptime;
13442 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13443 doWakeKills = false;
13444 }
13445 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13446 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013447 }
13448 int i = mLruProcesses.size();
13449 while (i > 0) {
13450 i--;
13451 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013452 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013453 long wtime;
13454 synchronized (stats) {
13455 wtime = stats.getProcessWakeTime(app.info.uid,
13456 app.pid, curRealtime);
13457 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013458 long wtimeUsed = wtime - app.lastWakeTime;
13459 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13460 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013461 StringBuilder sb = new StringBuilder(128);
13462 sb.append("Wake for ");
13463 app.toShortString(sb);
13464 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013465 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013466 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013467 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013468 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013469 sb.append((wtimeUsed*100)/realtimeSince);
13470 sb.append("%)");
13471 Slog.i(TAG, sb.toString());
13472 sb.setLength(0);
13473 sb.append("CPU for ");
13474 app.toShortString(sb);
13475 sb.append(": over ");
13476 TimeUtils.formatDuration(uptimeSince, sb);
13477 sb.append(" used ");
13478 TimeUtils.formatDuration(cputimeUsed, sb);
13479 sb.append(" (");
13480 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013481 sb.append("%)");
13482 Slog.i(TAG, sb.toString());
13483 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013484 // If a process has held a wake lock for more
13485 // than 50% of the time during this period,
13486 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013487 if (doWakeKills && realtimeSince > 0
13488 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13489 synchronized (stats) {
13490 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13491 realtimeSince, wtimeUsed);
13492 }
13493 Slog.w(TAG, "Excessive wake lock in " + app.processName
13494 + " (pid " + app.pid + "): held " + wtimeUsed
13495 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013496 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13497 app.processName, app.setAdj, "excessive wake lock");
13498 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013499 } else if (doCpuKills && uptimeSince > 0
13500 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13501 synchronized (stats) {
13502 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13503 uptimeSince, cputimeUsed);
13504 }
13505 Slog.w(TAG, "Excessive CPU in " + app.processName
13506 + " (pid " + app.pid + "): used " + cputimeUsed
13507 + " during " + uptimeSince);
13508 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13509 app.processName, app.setAdj, "excessive cpu");
13510 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013511 } else {
13512 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013513 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013514 }
13515 }
13516 }
13517 }
13518
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013519 private final boolean updateOomAdjLocked(
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013520 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013521 app.hiddenAdj = hiddenAdj;
13522
13523 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013524 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013525 }
13526
Dianne Hackborn287952c2010-09-22 22:34:31 -070013527 final boolean wasKeeping = app.keeping;
13528
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013529 boolean success = true;
13530
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013531 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013532
Jeff Brown10e89712011-07-08 18:52:57 -070013533 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013534 if (false) {
13535 // Removing for now. Forcing GCs is not so useful anymore
13536 // with Dalvik, and the new memory level hint facility is
13537 // better for what we need to do these days.
13538 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
13539 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13540 // If this app is transitioning from foreground to
13541 // non-foreground, have it do a gc.
13542 scheduleAppGcLocked(app);
13543 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13544 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13545 // Likewise do a gc when an app is moving in to the
13546 // background (such as a service stopping).
13547 scheduleAppGcLocked(app);
13548 }
Jeff Brown10e89712011-07-08 18:52:57 -070013549 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013550
Jeff Brown10e89712011-07-08 18:52:57 -070013551 if (wasKeeping && !app.keeping) {
13552 // This app is no longer something we want to keep. Note
13553 // its current wake lock time to later know to kill it if
13554 // it is not behaving well.
13555 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13556 synchronized (stats) {
13557 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13558 app.pid, SystemClock.elapsedRealtime());
13559 }
13560 app.lastCpuTime = app.curCpuTime;
13561 }
13562
13563 app.setRawAdj = app.curRawAdj;
13564 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013565 if (app.curAdj != app.setAdj) {
13566 if (Process.setOomAdj(app.pid, app.curAdj)) {
Jeff Brown10e89712011-07-08 18:52:57 -070013567 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
13568 TAG, "Set app " + app.processName +
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013569 " oom adj to " + app.curAdj + " because " + app.adjType);
13570 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013571 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013572 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013573 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013574 }
13575 }
13576 if (app.setSchedGroup != app.curSchedGroup) {
13577 app.setSchedGroup = app.curSchedGroup;
13578 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13579 "Setting process group of " + app.processName
13580 + " to " + app.curSchedGroup);
13581 if (app.waitingToKill != null &&
13582 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13583 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13584 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13585 app.processName, app.setAdj, app.waitingToKill);
13586 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013587 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013588 } else {
13589 if (true) {
13590 long oldId = Binder.clearCallingIdentity();
13591 try {
13592 Process.setProcessGroup(app.pid, app.curSchedGroup);
13593 } catch (Exception e) {
13594 Slog.w(TAG, "Failed setting process group of " + app.pid
13595 + " to " + app.curSchedGroup);
13596 e.printStackTrace();
13597 } finally {
13598 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013599 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013600 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013601 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013602 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013603 app.thread.setSchedulingGroup(app.curSchedGroup);
13604 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013605 }
13606 }
13607 }
13608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013609 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013610 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013611 }
13612
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013613 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013614 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013615 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013616 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013617 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013618 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013619 }
13620 }
13621 return resumedActivity;
13622 }
13623
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013624 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013625 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013626 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13627 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013628 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13629 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013630
13631 mAdjSeq++;
13632
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013633 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013634 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13635 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013636 if (nowHidden != wasHidden) {
13637 // Changed to/from hidden state, so apps after it in the LRU
13638 // list may also be changed.
13639 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013640 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013641 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013642 }
13643
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013644 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013645 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013646 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13647
13648 if (false) {
13649 RuntimeException e = new RuntimeException();
13650 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013651 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013652 }
13653
13654 mAdjSeq++;
13655
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013656 // Let's determine how many processes we have running vs.
13657 // how many slots we have for background processes; we may want
13658 // to put multiple processes in a slot of there are enough of
13659 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013660 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013661 int factor = (mLruProcesses.size()-4)/numSlots;
13662 if (factor < 1) factor = 1;
13663 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013664 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013665
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013666 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013667 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013668 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013669 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013670 int numBg = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013671 while (i > 0) {
13672 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013673 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013674 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013675 updateOomAdjLocked(app, curHiddenAdj, TOP_APP);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013676 if (curHiddenAdj < ProcessList.EMPTY_APP_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013677 && app.curAdj == curHiddenAdj) {
13678 step++;
13679 if (step >= factor) {
13680 step = 0;
13681 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013682 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013683 }
13684 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013685 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013686 numHidden++;
13687 if (numHidden > mProcessLimit) {
13688 Slog.i(TAG, "No longer want " + app.processName
13689 + " (pid " + app.pid + "): hidden #" + numHidden);
13690 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13691 app.processName, app.setAdj, "too many background");
13692 app.killedBackground = true;
13693 Process.killProcessQuiet(app.pid);
13694 } else {
13695 numBg++;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013696 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013697 } else if (app.curAdj >= ProcessList.HOME_APP_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013698 numBg++;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013700 }
13701 }
13702
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013703 // Now determine the memory trimming level of background processes.
13704 // Unfortunately we need to start at the back of the list to do this
13705 // properly. We only do this if the number of background apps we
13706 // are managing to keep around is less than half the maximum we desire;
13707 // if we are keeping a good number around, we'll let them use whatever
13708 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013709 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013710 final int N = mLruProcesses.size();
13711 factor = numBg/3;
13712 step = 0;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013713 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013714 for (i=0; i<N; i++) {
13715 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013716 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013717 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13718 try {
13719 app.thread.scheduleTrimMemory(curLevel);
13720 } catch (RemoteException e) {
13721 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013722 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013723 // For these apps we will also finish their activities
13724 // to help them free memory.
13725 mMainStack.destroyActivitiesLocked(app, false);
13726 }
13727 }
13728 app.trimMemoryLevel = curLevel;
13729 step++;
13730 if (step >= factor) {
13731 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013732 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13733 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013734 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013735 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13736 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013737 break;
13738 }
13739 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013740 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013741 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013742 && app.thread != null) {
13743 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013744 app.thread.scheduleTrimMemory(
13745 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013746 } catch (RemoteException e) {
13747 }
13748 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013749 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013750 } else if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013751 && app.pendingUiClean) {
13752 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13753 && app.thread != null) {
13754 try {
13755 app.thread.scheduleTrimMemory(
13756 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13757 } catch (RemoteException e) {
13758 }
13759 }
13760 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13761 app.pendingUiClean = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013762 } else {
13763 app.trimMemoryLevel = 0;
13764 }
13765 }
13766 } else {
13767 final int N = mLruProcesses.size();
13768 for (i=0; i<N; i++) {
13769 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013770 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013771 && app.pendingUiClean) {
13772 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13773 && app.thread != null) {
13774 try {
13775 app.thread.scheduleTrimMemory(
13776 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13777 } catch (RemoteException e) {
13778 }
13779 }
13780 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13781 app.pendingUiClean = false;
13782 } else {
13783 app.trimMemoryLevel = 0;
13784 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013785 }
13786 }
13787
13788 if (mAlwaysFinishActivities) {
13789 mMainStack.destroyActivitiesLocked(null, false);
13790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013791 }
13792
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013793 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013794 synchronized (this) {
13795 int i;
13796
13797 // First remove any unused application processes whose package
13798 // has been removed.
13799 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13800 final ProcessRecord app = mRemovedProcesses.get(i);
13801 if (app.activities.size() == 0
13802 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013803 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013804 TAG, "Exiting empty application process "
13805 + app.processName + " ("
13806 + (app.thread != null ? app.thread.asBinder() : null)
13807 + ")\n");
13808 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013809 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13810 app.processName, app.setAdj, "empty");
13811 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013812 } else {
13813 try {
13814 app.thread.scheduleExit();
13815 } catch (Exception e) {
13816 // Ignore exceptions.
13817 }
13818 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013819 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013820 mRemovedProcesses.remove(i);
13821
13822 if (app.persistent) {
13823 if (app.persistent) {
13824 addAppLocked(app.info);
13825 }
13826 }
13827 }
13828 }
13829
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013830 // Now update the oom adj for all processes.
13831 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013832 }
13833 }
13834
13835 /** This method sends the specified signal to each of the persistent apps */
13836 public void signalPersistentProcesses(int sig) throws RemoteException {
13837 if (sig != Process.SIGNAL_USR1) {
13838 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13839 }
13840
13841 synchronized (this) {
13842 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13843 != PackageManager.PERMISSION_GRANTED) {
13844 throw new SecurityException("Requires permission "
13845 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13846 }
13847
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013848 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13849 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013850 if (r.thread != null && r.persistent) {
13851 Process.sendSignal(r.pid, sig);
13852 }
13853 }
13854 }
13855 }
13856
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013857 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13858 if (proc == null || proc == mProfileProc) {
13859 proc = mProfileProc;
13860 path = mProfileFile;
13861 profileType = mProfileType;
13862 clearProfilerLocked();
13863 }
13864 if (proc == null) {
13865 return;
13866 }
13867 try {
13868 proc.thread.profilerControl(false, path, null, profileType);
13869 } catch (RemoteException e) {
13870 throw new IllegalStateException("Process disappeared");
13871 }
13872 }
13873
13874 private void clearProfilerLocked() {
13875 if (mProfileFd != null) {
13876 try {
13877 mProfileFd.close();
13878 } catch (IOException e) {
13879 }
13880 }
13881 mProfileApp = null;
13882 mProfileProc = null;
13883 mProfileFile = null;
13884 mProfileType = 0;
13885 mAutoStopProfiler = false;
13886 }
13887
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013888 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013889 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013890
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013891 try {
13892 synchronized (this) {
13893 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13894 // its own permission.
13895 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13896 != PackageManager.PERMISSION_GRANTED) {
13897 throw new SecurityException("Requires permission "
13898 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013899 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013900
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013901 if (start && fd == null) {
13902 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013903 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013904
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013905 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013906 if (process != null) {
13907 try {
13908 int pid = Integer.parseInt(process);
13909 synchronized (mPidsSelfLocked) {
13910 proc = mPidsSelfLocked.get(pid);
13911 }
13912 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013913 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013914
13915 if (proc == null) {
13916 HashMap<String, SparseArray<ProcessRecord>> all
13917 = mProcessNames.getMap();
13918 SparseArray<ProcessRecord> procs = all.get(process);
13919 if (procs != null && procs.size() > 0) {
13920 proc = procs.valueAt(0);
13921 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013922 }
13923 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013924
13925 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013926 throw new IllegalArgumentException("Unknown process: " + process);
13927 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013928
13929 if (start) {
13930 stopProfilerLocked(null, null, 0);
13931 setProfileApp(proc.info, proc.processName, path, fd, false);
13932 mProfileProc = proc;
13933 mProfileType = profileType;
13934 try {
13935 fd = fd.dup();
13936 } catch (IOException e) {
13937 fd = null;
13938 }
13939 proc.thread.profilerControl(start, path, fd, profileType);
13940 fd = null;
13941 mProfileFd = null;
13942 } else {
13943 stopProfilerLocked(proc, path, profileType);
13944 if (fd != null) {
13945 try {
13946 fd.close();
13947 } catch (IOException e) {
13948 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013949 }
13950 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013951
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013952 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013953 }
13954 } catch (RemoteException e) {
13955 throw new IllegalStateException("Process disappeared");
13956 } finally {
13957 if (fd != null) {
13958 try {
13959 fd.close();
13960 } catch (IOException e) {
13961 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013962 }
13963 }
13964 }
Andy McFadden824c5102010-07-09 16:26:57 -070013965
13966 public boolean dumpHeap(String process, boolean managed,
13967 String path, ParcelFileDescriptor fd) throws RemoteException {
13968
13969 try {
13970 synchronized (this) {
13971 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13972 // its own permission (same as profileControl).
13973 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13974 != PackageManager.PERMISSION_GRANTED) {
13975 throw new SecurityException("Requires permission "
13976 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13977 }
13978
13979 if (fd == null) {
13980 throw new IllegalArgumentException("null fd");
13981 }
13982
13983 ProcessRecord proc = null;
13984 try {
13985 int pid = Integer.parseInt(process);
13986 synchronized (mPidsSelfLocked) {
13987 proc = mPidsSelfLocked.get(pid);
13988 }
13989 } catch (NumberFormatException e) {
13990 }
13991
13992 if (proc == null) {
13993 HashMap<String, SparseArray<ProcessRecord>> all
13994 = mProcessNames.getMap();
13995 SparseArray<ProcessRecord> procs = all.get(process);
13996 if (procs != null && procs.size() > 0) {
13997 proc = procs.valueAt(0);
13998 }
13999 }
14000
14001 if (proc == null || proc.thread == null) {
14002 throw new IllegalArgumentException("Unknown process: " + process);
14003 }
14004
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014005 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14006 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014007 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14008 throw new SecurityException("Process not debuggable: " + proc);
14009 }
14010 }
14011
14012 proc.thread.dumpHeap(managed, path, fd);
14013 fd = null;
14014 return true;
14015 }
14016 } catch (RemoteException e) {
14017 throw new IllegalStateException("Process disappeared");
14018 } finally {
14019 if (fd != null) {
14020 try {
14021 fd.close();
14022 } catch (IOException e) {
14023 }
14024 }
14025 }
14026 }
14027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014028 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14029 public void monitor() {
14030 synchronized (this) { }
14031 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014032
14033 public void onCoreSettingsChange(Bundle settings) {
14034 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14035 ProcessRecord processRecord = mLruProcesses.get(i);
14036 try {
14037 if (processRecord.thread != null) {
14038 processRecord.thread.setCoreSettings(settings);
14039 }
14040 } catch (RemoteException re) {
14041 /* ignore */
14042 }
14043 }
14044 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014045
14046 // Multi-user methods
14047
14048 public boolean switchUser(int userid) {
14049 // TODO
14050 return true;
14051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014052}