blob: d3e12f77408406a14ece7b492856d6db87b07fe2 [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;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800109import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800110import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import android.util.PrintWriterPrinter;
112import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700113import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.view.Gravity;
115import android.view.LayoutInflater;
116import android.view.View;
117import android.view.WindowManager;
118import android.view.WindowManagerPolicy;
119
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700120import java.io.BufferedInputStream;
121import java.io.BufferedOutputStream;
122import java.io.DataInputStream;
123import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import java.io.File;
125import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700126import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700128import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200129import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800130import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.PrintWriter;
132import java.lang.IllegalStateException;
133import java.lang.ref.WeakReference;
134import java.util.ArrayList;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700135import java.util.Collections;
136import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.util.HashMap;
138import java.util.HashSet;
139import java.util.Iterator;
140import java.util.List;
141import java.util.Locale;
142import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700143import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700144import java.util.concurrent.atomic.AtomicBoolean;
145import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700147public final class ActivityManagerService extends ActivityManagerNative
148 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 static final String TAG = "ActivityManager";
150 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400151 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 static final boolean DEBUG_SWITCH = localLOGV || false;
153 static final boolean DEBUG_TASKS = localLOGV || false;
154 static final boolean DEBUG_PAUSE = localLOGV || false;
155 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
156 static final boolean DEBUG_TRANSITION = localLOGV || false;
157 static final boolean DEBUG_BROADCAST = localLOGV || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700158 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700160 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 static final boolean DEBUG_VISBILITY = localLOGV || false;
162 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700163 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800164 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700166 static final boolean DEBUG_RESULTS = localLOGV || false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700167 static final boolean DEBUG_BACKUP = localLOGV || true;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700168 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700169 static final boolean DEBUG_POWER = localLOGV || false;
170 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 static final boolean VALIDATE_TOKENS = false;
172 static final boolean SHOW_ACTIVITY_START_TIME = true;
173
174 // Control over CPU and battery monitoring.
175 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
176 static final boolean MONITOR_CPU_USAGE = true;
177 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
178 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
179 static final boolean MONITOR_THREAD_CPU_USAGE = false;
180
Dianne Hackborn1655be42009-05-08 14:29:01 -0700181 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700182 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700183
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800184 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 // Maximum number of recent tasks that we can remember.
187 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700188
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700189 // Amount of time after a call to stopAppSwitches() during which we will
190 // prevent further untrusted switches from happening.
191 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
193 // How long we wait for a launched process to attach to the activity manager
194 // before we decide it's never going to come up for real.
195 static final int PROC_START_TIMEOUT = 10*1000;
196
Jeff Brown3f9dd282011-07-08 20:02:19 -0700197 // How long we wait for a launched process to attach to the activity manager
198 // before we decide it's never going to come up for real, when the process was
199 // started with a wrapper for instrumentation (such as Valgrind) because it
200 // could take much longer than usual.
201 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 // How long to wait after going idle before forcing apps to GC.
204 static final int GC_TIMEOUT = 5*1000;
205
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700206 // The minimum amount of time between successive GC requests for a process.
207 static final int GC_MIN_INTERVAL = 60*1000;
208
Dianne Hackborn287952c2010-09-22 22:34:31 -0700209 // The rate at which we check for apps using excessive power -- 15 mins.
210 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
211
212 // The minimum sample duration we will allow before deciding we have
213 // enough data on wake locks to start killing things.
214 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
215
216 // The minimum sample duration we will allow before deciding we have
217 // enough data on CPU usage to start killing things.
218 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 // How long we allow a receiver to run before giving up on it.
221 static final int BROADCAST_TIMEOUT = 10*1000;
222
223 // How long we wait for a service to finish executing.
224 static final int SERVICE_TIMEOUT = 20*1000;
225
226 // How long a service needs to be running until restarting its process
227 // is no longer considered to be a relaunch of the service.
228 static final int SERVICE_RESTART_DURATION = 5*1000;
229
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700230 // How long a service needs to be running until it will start back at
231 // SERVICE_RESTART_DURATION after being killed.
232 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
233
234 // Multiplying factor to increase restart duration time by, for each time
235 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
236 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
237
238 // The minimum amount of time between restarting services that we allow.
239 // That is, when multiple services are restarting, we won't allow each
240 // to restart less than this amount of time from the last one.
241 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 // Maximum amount of time for there to be no activity on a service before
244 // we consider it non-essential and allow its process to go on the
245 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700246 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
248 // How long we wait until we timeout on key dispatching.
249 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // How long we wait until we timeout on key dispatching during instrumentation.
252 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
253
Dan Egnor42471dd2010-01-07 17:25:22 -0800254 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
256 static final String[] EMPTY_STRING_ARRAY = new String[0];
257
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700258 public ActivityStack mMainStack;
259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700261 * Description of a request to start a new activity, which has been held
262 * due to app switches being disabled.
263 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700264 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700265 ActivityRecord r;
266 ActivityRecord sourceRecord;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700267 Uri[] grantedUriPermissions;
268 int grantedMode;
269 boolean onlyIfNeeded;
270 }
271
272 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
273 = new ArrayList<PendingActivityLaunch>();
274
275 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 * List of all active broadcasts that are to be executed immediately
277 * (without waiting for another broadcast to finish). Currently this only
278 * contains broadcasts to registered receivers, to avoid spinning up
279 * a bunch of processes to execute IntentReceiver components.
280 */
281 final ArrayList<BroadcastRecord> mParallelBroadcasts
282 = new ArrayList<BroadcastRecord>();
283
284 /**
285 * List of all active broadcasts that are to be executed one at a time.
286 * The object at the top of the list is the currently activity broadcasts;
287 * those after it are waiting for the top to finish..
288 */
289 final ArrayList<BroadcastRecord> mOrderedBroadcasts
290 = new ArrayList<BroadcastRecord>();
291
292 /**
Dianne Hackborn12527f92009-11-11 17:39:50 -0800293 * Historical data of past broadcasts, for debugging.
294 */
295 static final int MAX_BROADCAST_HISTORY = 100;
296 final BroadcastRecord[] mBroadcastHistory
297 = new BroadcastRecord[MAX_BROADCAST_HISTORY];
298
299 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300 * Set when we current have a BROADCAST_INTENT_MSG in flight.
301 */
302 boolean mBroadcastsScheduled = false;
303
304 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 * Activity we have told the window manager to have key focus.
306 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700307 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700308 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 * List of intents that were used to start the most recent tasks.
310 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700311 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312
313 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700314 * Process management.
315 */
316 final ProcessList mProcessList = new ProcessList();
317
318 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 * All of the applications we currently have running organized by name.
320 * The keys are strings of the application package name (as
321 * returned by the package manager), and the keys are ApplicationRecord
322 * objects.
323 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700324 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325
326 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700327 * The currently running heavy-weight process, if any.
328 */
329 ProcessRecord mHeavyWeightProcess = null;
330
331 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 * The last time that various processes have crashed.
333 */
334 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
335
336 /**
337 * Set of applications that we consider to be bad, and will reject
338 * incoming broadcasts from (which the user has no control over).
339 * Processes are added to this set when they have crashed twice within
340 * a minimum amount of time; they are removed from it when they are
341 * later restarted (hopefully due to some user action). The value is the
342 * time it was added to the list.
343 */
344 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
345
346 /**
347 * All of the processes we currently have running organized by pid.
348 * The keys are the pid running the application.
349 *
350 * <p>NOTE: This object is protected by its own lock, NOT the global
351 * activity manager lock!
352 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700353 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354
355 /**
356 * All of the processes that have been forced to be foreground. The key
357 * is the pid of the caller who requested it (we hold a death
358 * link on it).
359 */
360 abstract class ForegroundToken implements IBinder.DeathRecipient {
361 int pid;
362 IBinder token;
363 }
364 final SparseArray<ForegroundToken> mForegroundProcesses
365 = new SparseArray<ForegroundToken>();
366
367 /**
368 * List of records for processes that someone had tried to start before the
369 * system was ready. We don't start them at that point, but ensure they
370 * are started by the time booting is complete.
371 */
372 final ArrayList<ProcessRecord> mProcessesOnHold
373 = new ArrayList<ProcessRecord>();
374
375 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 * List of persistent applications that are in the process
377 * of being started.
378 */
379 final ArrayList<ProcessRecord> mPersistentStartingProcesses
380 = new ArrayList<ProcessRecord>();
381
382 /**
383 * Processes that are being forcibly torn down.
384 */
385 final ArrayList<ProcessRecord> mRemovedProcesses
386 = new ArrayList<ProcessRecord>();
387
388 /**
389 * List of running applications, sorted by recent usage.
390 * The first entry in the list is the least recently used.
391 * It contains ApplicationRecord objects. This list does NOT include
392 * any persistent application records (since we never want to exit them).
393 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800394 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 = new ArrayList<ProcessRecord>();
396
397 /**
398 * List of processes that should gc as soon as things are idle.
399 */
400 final ArrayList<ProcessRecord> mProcessesToGc
401 = new ArrayList<ProcessRecord>();
402
403 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800404 * This is the process holding what we currently consider to be
405 * the "home" activity.
406 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700407 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800408
409 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400410 * Packages that the user has asked to have run in screen size
411 * compatibility mode instead of filling the screen.
412 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700413 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400414
415 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 * Set of PendingResultRecord objects that are currently active.
417 */
418 final HashSet mPendingResultRecords = new HashSet();
419
420 /**
421 * Set of IntentSenderRecord objects that are currently active.
422 */
423 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
424 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
425
426 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800427 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700428 * already logged DropBox entries for. Guarded by itself. If
429 * something (rogue user app) forces this over
430 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
431 */
432 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
433 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
434
435 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700436 * Strict Mode background batched logging state.
437 *
438 * The string buffer is guarded by itself, and its lock is also
439 * used to determine if another batched write is already
440 * in-flight.
441 */
442 private final StringBuilder mStrictModeBuffer = new StringBuilder();
443
444 /**
Jeff Brown4d94a762010-09-23 11:33:28 -0700445 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
446 */
447 private boolean mPendingBroadcastTimeoutMessage;
448
449 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 * Intent broadcast that we have tried to start, but are
451 * waiting for its application's process to be created. We only
452 * need one (instead of a list) because we always process broadcasts
453 * one at a time, so no others can be started while waiting for this
454 * one.
455 */
456 BroadcastRecord mPendingBroadcast = null;
457
458 /**
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700459 * The receiver index that is pending, to restart the broadcast if needed.
460 */
461 int mPendingBroadcastRecvIndex;
462
463 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 * Keeps track of all IIntentReceivers that have been registered for
465 * broadcasts. Hash keys are the receiver IBinder, hash value is
466 * a ReceiverList.
467 */
468 final HashMap mRegisteredReceivers = new HashMap();
469
470 /**
471 * Resolver for broadcast intents to registered receivers.
472 * Holds BroadcastFilter (subclass of IntentFilter).
473 */
474 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
475 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
476 @Override
477 protected boolean allowFilterResult(
478 BroadcastFilter filter, List<BroadcastFilter> dest) {
479 IBinder target = filter.receiverList.receiver.asBinder();
480 for (int i=dest.size()-1; i>=0; i--) {
481 if (dest.get(i).receiverList.receiver.asBinder() == target) {
482 return false;
483 }
484 }
485 return true;
486 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700487
488 @Override
489 protected String packageForFilter(BroadcastFilter filter) {
490 return filter.packageName;
491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 };
493
494 /**
495 * State of all active sticky broadcasts. Keys are the action of the
496 * sticky Intent, values are an ArrayList of all broadcasted intents with
497 * that action (which should usually be one).
498 */
499 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
500 new HashMap<String, ArrayList<Intent>>();
501
502 /**
503 * All currently running services.
504 */
505 final HashMap<ComponentName, ServiceRecord> mServices =
506 new HashMap<ComponentName, ServiceRecord>();
507
508 /**
509 * All currently running services indexed by the Intent used to start them.
510 */
511 final HashMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent =
512 new HashMap<Intent.FilterComparison, ServiceRecord>();
513
514 /**
515 * All currently bound service connections. Keys are the IBinder of
516 * the client's IServiceConnection.
517 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700518 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
519 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520
521 /**
522 * List of services that we have been asked to start,
523 * but haven't yet been able to. It is used to hold start requests
524 * while waiting for their corresponding application thread to get
525 * going.
526 */
527 final ArrayList<ServiceRecord> mPendingServices
528 = new ArrayList<ServiceRecord>();
529
530 /**
531 * List of services that are scheduled to restart following a crash.
532 */
533 final ArrayList<ServiceRecord> mRestartingServices
534 = new ArrayList<ServiceRecord>();
535
536 /**
537 * List of services that are in the process of being stopped.
538 */
539 final ArrayList<ServiceRecord> mStoppingServices
540 = new ArrayList<ServiceRecord>();
541
542 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700543 * Backup/restore process management
544 */
545 String mBackupAppName = null;
546 BackupRecord mBackupTarget = null;
547
548 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 * List of PendingThumbnailsRecord objects of clients who are still
550 * waiting to receive all of the thumbnails for a task.
551 */
552 final ArrayList mPendingThumbnails = new ArrayList();
553
554 /**
555 * List of HistoryRecord objects that have been finished and must
556 * still report back to a pending thumbnail receiver.
557 */
558 final ArrayList mCancelledThumbnails = new ArrayList();
559
560 /**
561 * All of the currently running global content providers. Keys are a
562 * string containing the provider name and values are a
563 * ContentProviderRecord object containing the data about it. Note
564 * that a single provider may be published under multiple names, so
565 * there may be multiple entries here for a single one in mProvidersByClass.
566 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700567 final HashMap<String, ContentProviderRecord> mProvidersByName
568 = new HashMap<String, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569
570 /**
571 * All of the currently running global content providers. Keys are a
572 * string containing the provider's implementation class and values are a
573 * ContentProviderRecord object containing the data about it.
574 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700575 final HashMap<String, ContentProviderRecord> mProvidersByClass
576 = new HashMap<String, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577
578 /**
579 * List of content providers who have clients waiting for them. The
580 * application is currently being launched and the provider will be
581 * removed from this list once it is published.
582 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700583 final ArrayList<ContentProviderRecord> mLaunchingProviders
584 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585
586 /**
587 * Global set of specific Uri permissions that have been granted.
588 */
589 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
590 = new SparseArray<HashMap<Uri, UriPermission>>();
591
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800592 CoreSettingsObserver mCoreSettingsObserver;
593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 /**
595 * Thread-local storage used to carry caller permissions over through
596 * indirect content-provider access.
597 * @see #ActivityManagerService.openContentUri()
598 */
599 private class Identity {
600 public int pid;
601 public int uid;
602
603 Identity(int _pid, int _uid) {
604 pid = _pid;
605 uid = _uid;
606 }
607 }
608 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
609
610 /**
611 * All information we have collected about the runtime performance of
612 * any user id that can impact battery performance.
613 */
614 final BatteryStatsService mBatteryStatsService;
615
616 /**
617 * information about component usage
618 */
619 final UsageStatsService mUsageStatsService;
620
621 /**
622 * Current configuration information. HistoryRecord objects are given
623 * a reference to this object to indicate which configuration they are
624 * currently running in, so this object must be kept immutable.
625 */
626 Configuration mConfiguration = new Configuration();
627
628 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800629 * Current sequencing integer of the configuration, for skipping old
630 * configurations.
631 */
632 int mConfigurationSeq = 0;
633
634 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700635 * Hardware-reported OpenGLES version.
636 */
637 final int GL_ES_VERSION;
638
639 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 * List of initialization arguments to pass to all processes when binding applications to them.
641 * For example, references to the commonly used services.
642 */
643 HashMap<String, IBinder> mAppBindArgs;
644
645 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700646 * Temporary to avoid allocations. Protected by main lock.
647 */
648 final StringBuilder mStringBuilder = new StringBuilder(256);
649
650 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 * Used to control how we initialize the service.
652 */
653 boolean mStartRunning = false;
654 ComponentName mTopComponent;
655 String mTopAction;
656 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700657 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 boolean mSystemReady = false;
659 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700660 boolean mWaitingUpdate = false;
661 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700662 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700663 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664
665 Context mContext;
666
667 int mFactoryTest;
668
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700669 boolean mCheckedForSetup;
670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700672 * The time at which we will allow normal application switches again,
673 * after a call to {@link #stopAppSwitches()}.
674 */
675 long mAppSwitchesAllowedTime;
676
677 /**
678 * This is set to true after the first switch after mAppSwitchesAllowedTime
679 * is set; any switches after that will clear the time.
680 */
681 boolean mDidAppSwitch;
682
683 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700684 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700685 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700686 long mLastPowerCheckRealtime;
687
688 /**
689 * Last time (in uptime) at which we checked for power usage.
690 */
691 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700692
693 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 * Set while we are wanting to sleep, to prevent any
695 * activities from being started/resumed.
696 */
697 boolean mSleeping = false;
698
699 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700700 * Set if we are shutting down the system, similar to sleeping.
701 */
702 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703
704 /**
705 * Task identifier that activities are currently being started
706 * in. Incremented each time a new task is created.
707 * todo: Replace this with a TokenSpace class that generates non-repeating
708 * integers that won't wrap.
709 */
710 int mCurTask = 1;
711
712 /**
713 * Current sequence id for oom_adj computation traversal.
714 */
715 int mAdjSeq = 0;
716
717 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700718 * Current sequence id for process LRU updating.
719 */
720 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721
722 /**
723 * System monitoring: number of processes that died since the last
724 * N procs were started.
725 */
726 int[] mProcDeaths = new int[20];
727
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700728 /**
729 * This is set if we had to do a delayed dexopt of an app before launching
730 * it, to increasing the ANR timeouts in that case.
731 */
732 boolean mDidDexOpt;
733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 String mDebugApp = null;
735 boolean mWaitForDebugger = false;
736 boolean mDebugTransient = false;
737 String mOrigDebugApp = null;
738 boolean mOrigWaitForDebugger = false;
739 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700740 IActivityController mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700742 final RemoteCallbackList<IActivityWatcher> mWatchers
743 = new RemoteCallbackList<IActivityWatcher>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700744
745 final RemoteCallbackList<IProcessObserver> mProcessObservers
746 = new RemoteCallbackList<IProcessObserver>();
747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 /**
749 * Callback of last caller to {@link #requestPss}.
750 */
751 Runnable mRequestPssCallback;
752
753 /**
754 * Remaining processes for which we are waiting results from the last
755 * call to {@link #requestPss}.
756 */
757 final ArrayList<ProcessRecord> mRequestPssList
758 = new ArrayList<ProcessRecord>();
759
760 /**
761 * Runtime statistics collection thread. This object's lock is used to
762 * protect all related state.
763 */
764 final Thread mProcessStatsThread;
765
766 /**
767 * Used to collect process stats when showing not responding dialog.
768 * Protected by mProcessStatsThread.
769 */
770 final ProcessStats mProcessStats = new ProcessStats(
771 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700772 final AtomicLong mLastCpuTime = new AtomicLong(0);
773 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 long mLastWriteTime = 0;
776
777 /**
778 * Set to true after the system has finished booting.
779 */
780 boolean mBooted = false;
781
Dianne Hackborn7d608422011-08-07 16:24:18 -0700782 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700783 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784
785 WindowManagerService mWindowManager;
786
787 static ActivityManagerService mSelf;
788 static ActivityThread mSystemThread;
789
790 private final class AppDeathRecipient implements IBinder.DeathRecipient {
791 final ProcessRecord mApp;
792 final int mPid;
793 final IApplicationThread mAppThread;
794
795 AppDeathRecipient(ProcessRecord app, int pid,
796 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800797 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 TAG, "New death recipient " + this
799 + " for thread " + thread.asBinder());
800 mApp = app;
801 mPid = pid;
802 mAppThread = thread;
803 }
804
805 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800806 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 TAG, "Death received in " + this
808 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 synchronized(ActivityManagerService.this) {
810 appDiedLocked(mApp, mPid, mAppThread);
811 }
812 }
813 }
814
815 static final int SHOW_ERROR_MSG = 1;
816 static final int SHOW_NOT_RESPONDING_MSG = 2;
817 static final int SHOW_FACTORY_ERROR_MSG = 3;
818 static final int UPDATE_CONFIGURATION_MSG = 4;
819 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
820 static final int WAIT_FOR_DEBUGGER_MSG = 6;
821 static final int BROADCAST_INTENT_MSG = 7;
822 static final int BROADCAST_TIMEOUT_MSG = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 static final int SERVICE_TIMEOUT_MSG = 12;
824 static final int UPDATE_TIME_ZONE = 13;
825 static final int SHOW_UID_ERROR_MSG = 14;
826 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700828 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700829 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800830 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700831 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
832 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700833 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700834 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700835 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700836 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700837 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700838 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
839 static final int DISPATCH_PROCESS_DIED = 32;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840
841 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700842 CompatModeDialog mCompatModeDialog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843
844 final Handler mHandler = new Handler() {
845 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800846 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 //}
848
849 public void handleMessage(Message msg) {
850 switch (msg.what) {
851 case SHOW_ERROR_MSG: {
852 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 synchronized (ActivityManagerService.this) {
854 ProcessRecord proc = (ProcessRecord)data.get("app");
855 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800856 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 return;
858 }
859 AppErrorResult res = (AppErrorResult) data.get("result");
Dianne Hackborn55280a92009-05-07 15:53:46 -0700860 if (!mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800861 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 d.show();
863 proc.crashDialog = d;
864 } else {
865 // The device is asleep, so just pretend that the user
866 // saw a crash dialog and hit "force quit".
867 res.set(0);
868 }
869 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700870
871 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 } break;
873 case SHOW_NOT_RESPONDING_MSG: {
874 synchronized (ActivityManagerService.this) {
875 HashMap data = (HashMap) msg.obj;
876 ProcessRecord proc = (ProcessRecord)data.get("app");
877 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800878 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 return;
880 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800881
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700882 Intent intent = new Intent("android.intent.action.ANR");
883 if (!mProcessesReady) {
884 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
885 }
886 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800887 null, null, 0, null, null, null,
888 false, false, MY_PID, Process.SYSTEM_UID);
889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700891 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 d.show();
893 proc.anrDialog = d;
894 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700895
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700896 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700898 case SHOW_STRICT_MODE_VIOLATION_MSG: {
899 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
900 synchronized (ActivityManagerService.this) {
901 ProcessRecord proc = (ProcessRecord) data.get("app");
902 if (proc == null) {
903 Slog.e(TAG, "App not found when showing strict mode dialog.");
904 break;
905 }
906 if (proc.crashDialog != null) {
907 Slog.e(TAG, "App already has strict mode dialog: " + proc);
908 return;
909 }
910 AppErrorResult res = (AppErrorResult) data.get("result");
911 if (!mSleeping && !mShuttingDown) {
912 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
913 d.show();
914 proc.crashDialog = d;
915 } else {
916 // The device is asleep, so just pretend that the user
917 // saw a crash dialog and hit "force quit".
918 res.set(0);
919 }
920 }
921 ensureBootCompleted();
922 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 case SHOW_FACTORY_ERROR_MSG: {
924 Dialog d = new FactoryErrorDialog(
925 mContext, msg.getData().getCharSequence("msg"));
926 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700927 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 } break;
929 case UPDATE_CONFIGURATION_MSG: {
930 final ContentResolver resolver = mContext.getContentResolver();
931 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
932 } break;
933 case GC_BACKGROUND_PROCESSES_MSG: {
934 synchronized (ActivityManagerService.this) {
935 performAppGcsIfAppropriateLocked();
936 }
937 } break;
938 case WAIT_FOR_DEBUGGER_MSG: {
939 synchronized (ActivityManagerService.this) {
940 ProcessRecord app = (ProcessRecord)msg.obj;
941 if (msg.arg1 != 0) {
942 if (!app.waitedForDebugger) {
943 Dialog d = new AppWaitingForDebuggerDialog(
944 ActivityManagerService.this,
945 mContext, app);
946 app.waitDialog = d;
947 app.waitedForDebugger = true;
948 d.show();
949 }
950 } else {
951 if (app.waitDialog != null) {
952 app.waitDialog.dismiss();
953 app.waitDialog = null;
954 }
955 }
956 }
957 } break;
958 case BROADCAST_INTENT_MSG: {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800959 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 TAG, "Received BROADCAST_INTENT_MSG");
961 processNextBroadcast(true);
962 } break;
963 case BROADCAST_TIMEOUT_MSG: {
Jeff Brown4d94a762010-09-23 11:33:28 -0700964 synchronized (ActivityManagerService.this) {
965 broadcastTimeoutLocked(true);
Jeff Hamiltonacf84742010-05-25 22:10:18 -0500966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700969 if (mDidDexOpt) {
970 mDidDexOpt = false;
971 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
972 nmsg.obj = msg.obj;
973 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
974 return;
975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 serviceTimeout((ProcessRecord)msg.obj);
977 } break;
978 case UPDATE_TIME_ZONE: {
979 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800980 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
981 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 if (r.thread != null) {
983 try {
984 r.thread.updateTimeZone();
985 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800986 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 }
988 }
989 }
990 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700991 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700992 case CLEAR_DNS_CACHE: {
993 synchronized (ActivityManagerService.this) {
994 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
995 ProcessRecord r = mLruProcesses.get(i);
996 if (r.thread != null) {
997 try {
998 r.thread.clearDnsCache();
999 } catch (RemoteException ex) {
1000 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1001 }
1002 }
1003 }
1004 }
1005 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001006 case UPDATE_HTTP_PROXY: {
1007 ProxyProperties proxy = (ProxyProperties)msg.obj;
1008 String host = "";
1009 String port = "";
1010 String exclList = "";
1011 if (proxy != null) {
1012 host = proxy.getHost();
1013 port = Integer.toString(proxy.getPort());
1014 exclList = proxy.getExclusionList();
1015 }
1016 synchronized (ActivityManagerService.this) {
1017 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1018 ProcessRecord r = mLruProcesses.get(i);
1019 if (r.thread != null) {
1020 try {
1021 r.thread.setHttpProxy(host, port, exclList);
1022 } catch (RemoteException ex) {
1023 Slog.w(TAG, "Failed to update http proxy for: " +
1024 r.info.processName);
1025 }
1026 }
1027 }
1028 }
1029 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 case SHOW_UID_ERROR_MSG: {
1031 // XXX This is a temporary dialog, no need to localize.
1032 AlertDialog d = new BaseErrorDialog(mContext);
1033 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1034 d.setCancelable(false);
1035 d.setTitle("System UIDs Inconsistent");
1036 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 +02001037 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1039 mUidAlert = d;
1040 d.show();
1041 } break;
1042 case IM_FEELING_LUCKY_MSG: {
1043 if (mUidAlert != null) {
1044 mUidAlert.dismiss();
1045 mUidAlert = null;
1046 }
1047 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001049 if (mDidDexOpt) {
1050 mDidDexOpt = false;
1051 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1052 nmsg.obj = msg.obj;
1053 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1054 return;
1055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 ProcessRecord app = (ProcessRecord)msg.obj;
1057 synchronized (ActivityManagerService.this) {
1058 processStartTimedOutLocked(app);
1059 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001060 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001061 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1062 synchronized (ActivityManagerService.this) {
1063 doPendingActivityLaunchesLocked(true);
1064 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001065 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001066 case KILL_APPLICATION_MSG: {
1067 synchronized (ActivityManagerService.this) {
1068 int uid = msg.arg1;
1069 boolean restart = (msg.arg2 == 1);
1070 String pkg = (String) msg.obj;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001071 forceStopPackageLocked(pkg, uid, restart, false, true);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001072 }
1073 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001074 case FINALIZE_PENDING_INTENT_MSG: {
1075 ((PendingIntentRecord)msg.obj).completeFinalize();
1076 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001077 case POST_HEAVY_NOTIFICATION_MSG: {
1078 INotificationManager inm = NotificationManager.getService();
1079 if (inm == null) {
1080 return;
1081 }
1082
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001083 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001084 ProcessRecord process = root.app;
1085 if (process == null) {
1086 return;
1087 }
1088
1089 try {
1090 Context context = mContext.createPackageContext(process.info.packageName, 0);
1091 String text = mContext.getString(R.string.heavy_weight_notification,
1092 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1093 Notification notification = new Notification();
1094 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1095 notification.when = 0;
1096 notification.flags = Notification.FLAG_ONGOING_EVENT;
1097 notification.tickerText = text;
1098 notification.defaults = 0; // please be quiet
1099 notification.sound = null;
1100 notification.vibrate = null;
1101 notification.setLatestEventInfo(context, text,
1102 mContext.getText(R.string.heavy_weight_notification_detail),
1103 PendingIntent.getActivity(mContext, 0, root.intent,
1104 PendingIntent.FLAG_CANCEL_CURRENT));
1105
1106 try {
1107 int[] outId = new int[1];
1108 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1109 notification, outId);
1110 } catch (RuntimeException e) {
1111 Slog.w(ActivityManagerService.TAG,
1112 "Error showing notification for heavy-weight app", e);
1113 } catch (RemoteException e) {
1114 }
1115 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001116 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001117 }
1118 } break;
1119 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1120 INotificationManager inm = NotificationManager.getService();
1121 if (inm == null) {
1122 return;
1123 }
1124 try {
1125 inm.cancelNotification("android",
1126 R.string.heavy_weight_notification);
1127 } catch (RuntimeException e) {
1128 Slog.w(ActivityManagerService.TAG,
1129 "Error canceling notification for service", e);
1130 } catch (RemoteException e) {
1131 }
1132 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001133 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1134 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001135 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001136 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001137 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1138 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001139 }
1140 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001141 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1142 synchronized (ActivityManagerService.this) {
1143 ActivityRecord ar = (ActivityRecord)msg.obj;
1144 if (mCompatModeDialog != null) {
1145 if (mCompatModeDialog.mAppInfo.packageName.equals(
1146 ar.info.applicationInfo.packageName)) {
1147 return;
1148 }
1149 mCompatModeDialog.dismiss();
1150 mCompatModeDialog = null;
1151 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001152 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001153 if (mCompatModePackages.getPackageAskCompatModeLocked(
1154 ar.packageName)) {
1155 int mode = mCompatModePackages.computeCompatModeLocked(
1156 ar.info.applicationInfo);
1157 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1158 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1159 mCompatModeDialog = new CompatModeDialog(
1160 ActivityManagerService.this, mContext,
1161 ar.info.applicationInfo);
1162 mCompatModeDialog.show();
1163 }
1164 }
1165 }
1166 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001167 break;
1168 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001169 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001170 final int pid = msg.arg1;
1171 final int uid = msg.arg2;
1172 final boolean foregroundActivities = (Boolean) msg.obj;
1173 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001174 break;
1175 }
1176 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001177 final int pid = msg.arg1;
1178 final int uid = msg.arg2;
1179 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001180 break;
1181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 }
1183 }
1184 };
1185
1186 public static void setSystemProcess() {
1187 try {
1188 ActivityManagerService m = mSelf;
1189
1190 ServiceManager.addService("activity", m);
1191 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001192 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 if (MONITOR_CPU_USAGE) {
1194 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 ServiceManager.addService("permission", new PermissionController(m));
1197
1198 ApplicationInfo info =
1199 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001200 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001201 mSystemThread.installSystemApplicationInfo(info);
1202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 synchronized (mSelf) {
1204 ProcessRecord app = mSelf.newProcessRecordLocked(
1205 mSystemThread.getApplicationThread(), info,
1206 info.processName);
1207 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001208 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001209 app.maxAdj = ProcessList.SYSTEM_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 mSelf.mProcessNames.put(app.processName, app.info.uid, app);
1211 synchronized (mSelf.mPidsSelfLocked) {
1212 mSelf.mPidsSelfLocked.put(app.pid, app);
1213 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001214 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 }
1216 } catch (PackageManager.NameNotFoundException e) {
1217 throw new RuntimeException(
1218 "Unable to find android system package", e);
1219 }
1220 }
1221
1222 public void setWindowManager(WindowManagerService wm) {
1223 mWindowManager = wm;
1224 }
1225
1226 public static final Context main(int factoryTest) {
1227 AThread thr = new AThread();
1228 thr.start();
1229
1230 synchronized (thr) {
1231 while (thr.mService == null) {
1232 try {
1233 thr.wait();
1234 } catch (InterruptedException e) {
1235 }
1236 }
1237 }
1238
1239 ActivityManagerService m = thr.mService;
1240 mSelf = m;
1241 ActivityThread at = ActivityThread.systemMain();
1242 mSystemThread = at;
1243 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001244 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 m.mContext = context;
1246 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001247 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248
1249 m.mBatteryStatsService.publish(context);
1250 m.mUsageStatsService.publish(context);
1251
1252 synchronized (thr) {
1253 thr.mReady = true;
1254 thr.notifyAll();
1255 }
1256
1257 m.startRunning(null, null, null, null);
1258
1259 return context;
1260 }
1261
1262 public static ActivityManagerService self() {
1263 return mSelf;
1264 }
1265
1266 static class AThread extends Thread {
1267 ActivityManagerService mService;
1268 boolean mReady = false;
1269
1270 public AThread() {
1271 super("ActivityManager");
1272 }
1273
1274 public void run() {
1275 Looper.prepare();
1276
1277 android.os.Process.setThreadPriority(
1278 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001279 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280
1281 ActivityManagerService m = new ActivityManagerService();
1282
1283 synchronized (this) {
1284 mService = m;
1285 notifyAll();
1286 }
1287
1288 synchronized (this) {
1289 while (!mReady) {
1290 try {
1291 wait();
1292 } catch (InterruptedException e) {
1293 }
1294 }
1295 }
1296
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001297 // For debug builds, log event loop stalls to dropbox for analysis.
1298 if (StrictMode.conditionallyEnableDebugLogging()) {
1299 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1300 }
1301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 Looper.loop();
1303 }
1304 }
1305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 static class MemBinder extends Binder {
1307 ActivityManagerService mActivityManagerService;
1308 MemBinder(ActivityManagerService activityManagerService) {
1309 mActivityManagerService = activityManagerService;
1310 }
1311
1312 @Override
1313 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001314 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
1316 }
1317
Chet Haase9c1e23b2011-03-24 10:51:31 -07001318 static class GraphicsBinder extends Binder {
1319 ActivityManagerService mActivityManagerService;
1320 GraphicsBinder(ActivityManagerService activityManagerService) {
1321 mActivityManagerService = activityManagerService;
1322 }
1323
1324 @Override
1325 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001326 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001327 }
1328 }
1329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 static class CpuBinder extends Binder {
1331 ActivityManagerService mActivityManagerService;
1332 CpuBinder(ActivityManagerService activityManagerService) {
1333 mActivityManagerService = activityManagerService;
1334 }
1335
1336 @Override
1337 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1338 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001339 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1340 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1341 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 }
1343 }
1344 }
1345
1346 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001347 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 File dataDir = Environment.getDataDirectory();
1350 File systemDir = new File(dataDir, "system");
1351 systemDir.mkdirs();
1352 mBatteryStatsService = new BatteryStatsService(new File(
1353 systemDir, "batterystats.bin").toString());
1354 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001355 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001356 mOnBattery = DEBUG_POWER ? true
1357 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001358 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001360 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001361 systemDir, "usagestats").toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362
Jack Palevichb90d28c2009-07-22 15:35:24 -07001363 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1364 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1365
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001366 mConfiguration.setToDefaults();
1367 mConfiguration.locale = Locale.getDefault();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 mProcessStats.init();
1369
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001370 mCompatModePackages = new CompatModePackages(this, systemDir);
1371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 // Add ourself to the Watchdog monitors.
1373 Watchdog.getInstance().addMonitor(this);
1374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 mProcessStatsThread = new Thread("ProcessStats") {
1376 public void run() {
1377 while (true) {
1378 try {
1379 try {
1380 synchronized(this) {
1381 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001382 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001384 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 // + ", write delay=" + nextWriteDelay);
1386 if (nextWriteDelay < nextCpuDelay) {
1387 nextCpuDelay = nextWriteDelay;
1388 }
1389 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001390 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 this.wait(nextCpuDelay);
1392 }
1393 }
1394 } catch (InterruptedException e) {
1395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 updateCpuStatsNow();
1397 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001398 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
1400 }
1401 }
1402 };
1403 mProcessStatsThread.start();
1404 }
1405
1406 @Override
1407 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1408 throws RemoteException {
1409 try {
1410 return super.onTransact(code, data, reply, flags);
1411 } catch (RuntimeException e) {
1412 // The activity manager only throws security exceptions, so let's
1413 // log all others.
1414 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001415 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417 throw e;
1418 }
1419 }
1420
1421 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001422 final long now = SystemClock.uptimeMillis();
1423 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1424 return;
1425 }
1426 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1427 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 mProcessStatsThread.notify();
1429 }
1430 }
1431 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 void updateCpuStatsNow() {
1434 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001435 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 final long now = SystemClock.uptimeMillis();
1437 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001440 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1441 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 haveNewCpuStats = true;
1443 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001444 //Slog.i(TAG, mProcessStats.printCurrentState());
1445 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 // + mProcessStats.getTotalCpuPercent() + "%");
1447
Joe Onorato8a9b2202010-02-26 18:56:32 -08001448 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 if ("true".equals(SystemProperties.get("events.cpu"))) {
1450 int user = mProcessStats.getLastUserTime();
1451 int system = mProcessStats.getLastSystemTime();
1452 int iowait = mProcessStats.getLastIoWaitTime();
1453 int irq = mProcessStats.getLastIrqTime();
1454 int softIrq = mProcessStats.getLastSoftIrqTime();
1455 int idle = mProcessStats.getLastIdleTime();
1456
1457 int total = user + system + iowait + irq + softIrq + idle;
1458 if (total == 0) total = 1;
1459
Doug Zongker2bec3d42009-12-04 12:52:44 -08001460 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 ((user+system+iowait+irq+softIrq) * 100) / total,
1462 (user * 100) / total,
1463 (system * 100) / total,
1464 (iowait * 100) / total,
1465 (irq * 100) / total,
1466 (softIrq * 100) / total);
1467 }
1468 }
1469
Amith Yamasanie43530a2009-08-21 13:11:37 -07001470 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001471 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001472 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 synchronized(mPidsSelfLocked) {
1474 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001475 if (mOnBattery) {
1476 int perc = bstats.startAddingCpuLocked();
1477 int totalUTime = 0;
1478 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001479 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001481 ProcessStats.Stats st = mProcessStats.getStats(i);
1482 if (!st.working) {
1483 continue;
1484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001486 int otherUTime = (st.rel_utime*perc)/100;
1487 int otherSTime = (st.rel_stime*perc)/100;
1488 totalUTime += otherUTime;
1489 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 if (pr != null) {
1491 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001492 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1493 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001494 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001495 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001496 } else {
1497 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001498 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001499 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001500 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1501 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001502 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 }
1505 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001506 bstats.finishAddingCpuLocked(perc, totalUTime,
1507 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 }
1509 }
1510 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1513 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001514 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516 }
1517 }
1518 }
1519
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001520 @Override
1521 public void batteryNeedsCpuUpdate() {
1522 updateCpuStatsNow();
1523 }
1524
1525 @Override
1526 public void batteryPowerChanged(boolean onBattery) {
1527 // When plugging in, update the CPU stats first before changing
1528 // the plug state.
1529 updateCpuStatsNow();
1530 synchronized (this) {
1531 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001532 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001533 }
1534 }
1535 }
1536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 /**
1538 * Initialize the application bind args. These are passed to each
1539 * process when the bindApplication() IPC is sent to the process. They're
1540 * lazily setup to make sure the services are running when they're asked for.
1541 */
1542 private HashMap<String, IBinder> getCommonServicesLocked() {
1543 if (mAppBindArgs == null) {
1544 mAppBindArgs = new HashMap<String, IBinder>();
1545
1546 // Setup the application init args
1547 mAppBindArgs.put("package", ServiceManager.getService("package"));
1548 mAppBindArgs.put("window", ServiceManager.getService("window"));
1549 mAppBindArgs.put(Context.ALARM_SERVICE,
1550 ServiceManager.getService(Context.ALARM_SERVICE));
1551 }
1552 return mAppBindArgs;
1553 }
1554
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001555 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 if (mFocusedActivity != r) {
1557 mFocusedActivity = r;
1558 mWindowManager.setFocusedApp(r, true);
1559 }
1560 }
1561
Dianne Hackborn906497c2010-05-10 15:57:38 -07001562 private final void updateLruProcessInternalLocked(ProcessRecord app,
1563 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001565 int lrui = mLruProcesses.indexOf(app);
1566 if (lrui >= 0) mLruProcesses.remove(lrui);
1567
1568 int i = mLruProcesses.size()-1;
1569 int skipTop = 0;
1570
Dianne Hackborn906497c2010-05-10 15:57:38 -07001571 app.lruSeq = mLruSeq;
1572
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001573 // compute the new weight for this process.
1574 if (updateActivityTime) {
1575 app.lastActivityTime = SystemClock.uptimeMillis();
1576 }
1577 if (app.activities.size() > 0) {
1578 // If this process has activities, we more strongly want to keep
1579 // it around.
1580 app.lruWeight = app.lastActivityTime;
1581 } else if (app.pubProviders.size() > 0) {
1582 // If this process contains content providers, we want to keep
1583 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001584 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001585 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001586 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001587 } else {
1588 // If this process doesn't have activities, we less strongly
1589 // want to keep it around, and generally want to avoid getting
1590 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001591 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_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 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001595
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001596 while (i >= 0) {
1597 ProcessRecord p = mLruProcesses.get(i);
1598 // If this app shouldn't be in front of the first N background
1599 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001600 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001601 skipTop--;
1602 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001603 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001604 mLruProcesses.add(i+1, app);
1605 break;
1606 }
1607 i--;
1608 }
1609 if (i < 0) {
1610 mLruProcesses.add(0, app);
1611 }
1612
Dianne Hackborn906497c2010-05-10 15:57:38 -07001613 // If the app is currently using a content provider or service,
1614 // bump those processes as well.
1615 if (app.connections.size() > 0) {
1616 for (ConnectionRecord cr : app.connections) {
1617 if (cr.binding != null && cr.binding.service != null
1618 && cr.binding.service.app != null
1619 && cr.binding.service.app.lruSeq != mLruSeq) {
1620 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1621 updateActivityTime, i+1);
1622 }
1623 }
1624 }
1625 if (app.conProviders.size() > 0) {
1626 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
1627 if (cpr.app != null && cpr.app.lruSeq != mLruSeq) {
1628 updateLruProcessInternalLocked(cpr.app, oomAdj,
1629 updateActivityTime, i+1);
1630 }
1631 }
1632 }
1633
Joe Onorato8a9b2202010-02-26 18:56:32 -08001634 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 if (oomAdj) {
1636 updateOomAdjLocked();
1637 }
1638 }
1639
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001640 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001641 boolean oomAdj, boolean updateActivityTime) {
1642 mLruSeq++;
1643 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1644 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001645
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001646 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 String processName, int uid) {
1648 if (uid == Process.SYSTEM_UID) {
1649 // The system gets to run in any process. If there are multiple
1650 // processes with the same uid, just pick the first (this
1651 // should never happen).
1652 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1653 processName);
1654 return procs != null ? procs.valueAt(0) : null;
1655 }
1656 ProcessRecord proc = mProcessNames.get(processName, uid);
1657 return proc;
1658 }
1659
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001660 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001661 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001662 try {
1663 if (pm.performDexOpt(packageName)) {
1664 mDidDexOpt = true;
1665 }
1666 } catch (RemoteException e) {
1667 }
1668 }
1669
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001670 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 int transit = mWindowManager.getPendingAppTransition();
1672 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1673 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1674 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1675 }
1676
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001677 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001679 String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 ProcessRecord app = getProcessRecordLocked(processName, info.uid);
1681 // We don't have to do anything more if:
1682 // (1) There is an existing application record; and
1683 // (2) The caller doesn't think it is dead, OR there is no thread
1684 // object attached to it so we know it couldn't have crashed; and
1685 // (3) There is a pid assigned to it, so it is either starting or
1686 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001687 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 + " app=" + app + " knownToBeDead=" + knownToBeDead
1689 + " thread=" + (app != null ? app.thread : null)
1690 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001691 if (app != null && app.pid > 0) {
1692 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001693 // We already have the app running, or are waiting for it to
1694 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001695 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001696 // If this is a new package in the process, add the package to the list
1697 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001698 return app;
1699 } else {
1700 // An application record is attached to a previous process,
1701 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001702 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001703 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 String hostingNameStr = hostingName != null
1708 ? hostingName.flattenToShortString() : null;
1709
1710 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1711 // If we are in the background, then check to see if this process
1712 // is bad. If so, we will just silently fail.
1713 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001714 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1715 + "/" + info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 return null;
1717 }
1718 } else {
1719 // When the user is explicitly starting a process, then clear its
1720 // crash count so that we won't make it bad until they see at
1721 // least one crash dialog again, and make the process good again
1722 // if it had been bad.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001723 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
1724 + "/" + info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 mProcessCrashTimes.remove(info.processName, info.uid);
1726 if (mBadProcesses.get(info.processName, info.uid) != null) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08001727 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 info.processName);
1729 mBadProcesses.remove(info.processName, info.uid);
1730 if (app != null) {
1731 app.bad = false;
1732 }
1733 }
1734 }
1735
1736 if (app == null) {
1737 app = newProcessRecordLocked(null, info, processName);
1738 mProcessNames.put(processName, info.uid, app);
1739 } else {
1740 // If this is a new package in the process, add the package to the list
1741 app.addPackage(info.packageName);
1742 }
1743
1744 // If the system is not ready yet, then hold off on starting this
1745 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001746 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001747 && !isAllowedWhileBooting(info)
1748 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 if (!mProcessesOnHold.contains(app)) {
1750 mProcessesOnHold.add(app);
1751 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001752 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 return app;
1754 }
1755
1756 startProcessLocked(app, hostingType, hostingNameStr);
1757 return (app.pid != 0) ? app : null;
1758 }
1759
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001760 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1761 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1762 }
1763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 private final void startProcessLocked(ProcessRecord app,
1765 String hostingType, String hostingNameStr) {
1766 if (app.pid > 0 && app.pid != MY_PID) {
1767 synchronized (mPidsSelfLocked) {
1768 mPidsSelfLocked.remove(app.pid);
1769 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1770 }
1771 app.pid = 0;
1772 }
1773
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001774 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1775 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 mProcessesOnHold.remove(app);
1777
1778 updateCpuStats();
1779
1780 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1781 mProcDeaths[0] = 0;
1782
1783 try {
1784 int uid = app.info.uid;
1785 int[] gids = null;
1786 try {
1787 gids = mContext.getPackageManager().getPackageGids(
1788 app.info.packageName);
1789 } catch (PackageManager.NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001790 Slog.w(TAG, "Unable to retrieve gids", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 }
1792 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1793 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1794 && mTopComponent != null
1795 && app.processName.equals(mTopComponent.getPackageName())) {
1796 uid = 0;
1797 }
1798 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1799 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1800 uid = 0;
1801 }
1802 }
1803 int debugFlags = 0;
1804 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1805 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001806 // Also turn on CheckJNI for debuggable apps. It's quite
1807 // awkward to turn on otherwise.
1808 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001810 // Run the app in safe mode if its manifest requests so or the
1811 // system is booted in safe mode.
1812 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1813 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001814 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1817 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1818 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001819 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1820 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 if ("1".equals(SystemProperties.get("debug.assert"))) {
1823 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1824 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001825
1826 // Start the process. It will either succeed and return a result containing
1827 // the PID of the new process, or else throw a RuntimeException.
1828 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001829 app.processName, uid, uid, gids, debugFlags,
1830 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07001831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1833 synchronized (bs) {
1834 if (bs.isOnBattery()) {
1835 app.batteryStats.incStartsLocked();
1836 }
1837 }
1838
Jeff Brown3f9dd282011-07-08 20:02:19 -07001839 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 app.processName, hostingType,
1841 hostingNameStr != null ? hostingNameStr : "");
1842
1843 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07001844 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07001847 StringBuilder buf = mStringBuilder;
1848 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 buf.append("Start proc ");
1850 buf.append(app.processName);
1851 buf.append(" for ");
1852 buf.append(hostingType);
1853 if (hostingNameStr != null) {
1854 buf.append(" ");
1855 buf.append(hostingNameStr);
1856 }
1857 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07001858 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 buf.append(" uid=");
1860 buf.append(uid);
1861 buf.append(" gids={");
1862 if (gids != null) {
1863 for (int gi=0; gi<gids.length; gi++) {
1864 if (gi != 0) buf.append(", ");
1865 buf.append(gids[gi]);
1866
1867 }
1868 }
1869 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001870 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07001871 app.pid = startResult.pid;
1872 app.usingWrapper = startResult.usingWrapper;
1873 app.removed = false;
1874 synchronized (mPidsSelfLocked) {
1875 this.mPidsSelfLocked.put(startResult.pid, app);
1876 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1877 msg.obj = app;
1878 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
1879 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 }
1881 } catch (RuntimeException e) {
1882 // XXX do better error recovery.
1883 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001884 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 }
1886 }
1887
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001888 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 if (resumed) {
1890 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
1891 } else {
1892 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
1893 }
1894 }
1895
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001896 boolean startHomeActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001897 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1898 && mTopAction == null) {
1899 // We are running in factory test mode, but unable to find
1900 // the factory test app, so just sit around displaying the
1901 // error message and don't try to start anything.
1902 return false;
1903 }
1904 Intent intent = new Intent(
1905 mTopAction,
1906 mTopData != null ? Uri.parse(mTopData) : null);
1907 intent.setComponent(mTopComponent);
1908 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
1909 intent.addCategory(Intent.CATEGORY_HOME);
1910 }
1911 ActivityInfo aInfo =
1912 intent.resolveActivityInfo(mContext.getPackageManager(),
1913 STOCK_PM_FLAGS);
1914 if (aInfo != null) {
1915 intent.setComponent(new ComponentName(
1916 aInfo.applicationInfo.packageName, aInfo.name));
1917 // Don't do this if the home app is currently being
1918 // instrumented.
1919 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
1920 aInfo.applicationInfo.uid);
1921 if (app == null || app.instrumentationClass == null) {
1922 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001923 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001924 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001925 }
1926 }
1927
1928
1929 return true;
1930 }
1931
1932 /**
1933 * Starts the "new version setup screen" if appropriate.
1934 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001935 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001936 // Only do this once per boot.
1937 if (mCheckedForSetup) {
1938 return;
1939 }
1940
1941 // We will show this screen if the current one is a different
1942 // version than the last one shown, and we are not running in
1943 // low-level factory test mode.
1944 final ContentResolver resolver = mContext.getContentResolver();
1945 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
1946 Settings.Secure.getInt(resolver,
1947 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
1948 mCheckedForSetup = true;
1949
1950 // See if we should be showing the platform update setup UI.
1951 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
1952 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
1953 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
1954
1955 // We don't allow third party apps to replace this.
1956 ResolveInfo ri = null;
1957 for (int i=0; ris != null && i<ris.size(); i++) {
1958 if ((ris.get(i).activityInfo.applicationInfo.flags
1959 & ApplicationInfo.FLAG_SYSTEM) != 0) {
1960 ri = ris.get(i);
1961 break;
1962 }
1963 }
1964
1965 if (ri != null) {
1966 String vers = ri.activityInfo.metaData != null
1967 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
1968 : null;
1969 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
1970 vers = ri.activityInfo.applicationInfo.metaData.getString(
1971 Intent.METADATA_SETUP_VERSION);
1972 }
1973 String lastVers = Settings.Secure.getString(
1974 resolver, Settings.Secure.LAST_SETUP_SHOWN);
1975 if (vers != null && !vers.equals(lastVers)) {
1976 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1977 intent.setComponent(new ComponentName(
1978 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001979 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001980 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001981 }
1982 }
1983 }
1984 }
1985
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001986 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001987 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001988 }
1989
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001990 public int getFrontActivityScreenCompatMode() {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001991 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001992 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
1993 }
1994 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001995
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001996 public void setFrontActivityScreenCompatMode(int mode) {
1997 synchronized (this) {
1998 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
1999 }
2000 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002001
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002002 public int getPackageScreenCompatMode(String packageName) {
2003 synchronized (this) {
2004 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2005 }
2006 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002007
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002008 public void setPackageScreenCompatMode(String packageName, int mode) {
2009 synchronized (this) {
2010 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002011 }
2012 }
2013
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002014 public boolean getPackageAskScreenCompat(String packageName) {
2015 synchronized (this) {
2016 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2017 }
2018 }
2019
2020 public void setPackageAskScreenCompat(String packageName, boolean ask) {
2021 synchronized (this) {
2022 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2023 }
2024 }
2025
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002026 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002027 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002028
2029 final int identHash = System.identityHashCode(r);
2030 updateUsageStats(r, true);
2031
2032 int i = mWatchers.beginBroadcast();
2033 while (i > 0) {
2034 i--;
2035 IActivityWatcher w = mWatchers.getBroadcastItem(i);
2036 if (w != null) {
2037 try {
2038 w.activityResuming(identHash);
2039 } catch (RemoteException e) {
2040 }
2041 }
2042 }
2043 mWatchers.finishBroadcast();
2044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045
Jeff Sharkeya4620792011-05-20 15:29:23 -07002046 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2047 int i = mProcessObservers.beginBroadcast();
2048 while (i > 0) {
2049 i--;
2050 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2051 if (observer != null) {
2052 try {
2053 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2054 } catch (RemoteException e) {
2055 }
2056 }
2057 }
2058 mProcessObservers.finishBroadcast();
2059 }
2060
2061 private void dispatchProcessDied(int pid, int uid) {
2062 int i = mProcessObservers.beginBroadcast();
2063 while (i > 0) {
2064 i--;
2065 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2066 if (observer != null) {
2067 try {
2068 observer.onProcessDied(pid, uid);
2069 } catch (RemoteException e) {
2070 }
2071 }
2072 }
2073 mProcessObservers.finishBroadcast();
2074 }
2075
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002076 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002077 final int N = mPendingActivityLaunches.size();
2078 if (N <= 0) {
2079 return;
2080 }
2081 for (int i=0; i<N; i++) {
2082 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002083 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002084 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
2085 doResume && i == (N-1));
2086 }
2087 mPendingActivityLaunches.clear();
2088 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002089
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002090 public final int startActivity(IApplicationThread caller,
2091 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2092 int grantedMode, IBinder resultTo,
2093 String resultWho, int requestCode, boolean onlyIfNeeded,
2094 boolean debug) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002095 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002096 grantedUriPermissions, grantedMode, resultTo, resultWho,
2097 requestCode, onlyIfNeeded, debug, null, null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002098 }
2099
2100 public final WaitResult startActivityAndWait(IApplicationThread caller,
2101 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2102 int grantedMode, IBinder resultTo,
2103 String resultWho, int requestCode, boolean onlyIfNeeded,
2104 boolean debug) {
2105 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002106 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002107 grantedUriPermissions, grantedMode, resultTo, resultWho,
2108 requestCode, onlyIfNeeded, debug, res, null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002109 return res;
2110 }
2111
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002112 public final int startActivityWithConfig(IApplicationThread caller,
2113 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2114 int grantedMode, IBinder resultTo,
2115 String resultWho, int requestCode, boolean onlyIfNeeded,
2116 boolean debug, Configuration config) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002117 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002118 grantedUriPermissions, grantedMode, resultTo, resultWho,
2119 requestCode, onlyIfNeeded, debug, null, config);
2120 }
2121
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002122 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002123 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002124 IBinder resultTo, String resultWho, int requestCode,
2125 int flagsMask, int flagsValues) {
2126 // Refuse possible leaked file descriptors
2127 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2128 throw new IllegalArgumentException("File descriptors passed in Intent");
2129 }
2130
2131 IIntentSender sender = intent.getTarget();
2132 if (!(sender instanceof PendingIntentRecord)) {
2133 throw new IllegalArgumentException("Bad PendingIntent object");
2134 }
2135
2136 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002137
2138 synchronized (this) {
2139 // If this is coming from the currently resumed activity, it is
2140 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002141 if (mMainStack.mResumedActivity != null
2142 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002143 Binder.getCallingUid()) {
2144 mAppSwitchesAllowedTime = 0;
2145 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002146 }
2147
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002148 return pir.sendInner(0, fillInIntent, resolvedType, null,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002149 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
2150 }
2151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 public boolean startNextMatchingActivity(IBinder callingActivity,
2153 Intent intent) {
2154 // Refuse possible leaked file descriptors
2155 if (intent != null && intent.hasFileDescriptors() == true) {
2156 throw new IllegalArgumentException("File descriptors passed in Intent");
2157 }
2158
2159 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002160 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2161 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 return false;
2163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 if (r.app == null || r.app.thread == null) {
2165 // The caller is not running... d'oh!
2166 return false;
2167 }
2168 intent = new Intent(intent);
2169 // The caller is not allowed to change the data.
2170 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2171 // And we are resetting to find the next component...
2172 intent.setComponent(null);
2173
2174 ActivityInfo aInfo = null;
2175 try {
2176 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002177 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002179 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180
2181 // Look for the original activity in the list...
2182 final int N = resolves != null ? resolves.size() : 0;
2183 for (int i=0; i<N; i++) {
2184 ResolveInfo rInfo = resolves.get(i);
2185 if (rInfo.activityInfo.packageName.equals(r.packageName)
2186 && rInfo.activityInfo.name.equals(r.info.name)) {
2187 // We found the current one... the next matching is
2188 // after it.
2189 i++;
2190 if (i<N) {
2191 aInfo = resolves.get(i).activityInfo;
2192 }
2193 break;
2194 }
2195 }
2196 } catch (RemoteException e) {
2197 }
2198
2199 if (aInfo == null) {
2200 // Nobody who is next!
2201 return false;
2202 }
2203
2204 intent.setComponent(new ComponentName(
2205 aInfo.applicationInfo.packageName, aInfo.name));
2206 intent.setFlags(intent.getFlags()&~(
2207 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2208 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2209 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2210 Intent.FLAG_ACTIVITY_NEW_TASK));
2211
2212 // Okay now we need to start the new activity, replacing the
2213 // currently running activity. This is a little tricky because
2214 // we want to start the new one as if the current one is finished,
2215 // but not finish the current one first so that there is no flicker.
2216 // And thus...
2217 final boolean wasFinishing = r.finishing;
2218 r.finishing = true;
2219
2220 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002221 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002222 final String resultWho = r.resultWho;
2223 final int requestCode = r.requestCode;
2224 r.resultTo = null;
2225 if (resultTo != null) {
2226 resultTo.removeResultsLocked(r, resultWho, requestCode);
2227 }
2228
2229 final long origId = Binder.clearCallingIdentity();
2230 // XXX we are not dealing with propagating grantedUriPermissions...
2231 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002232 int res = mMainStack.startActivityLocked(r.app.thread, intent,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 r.resolvedType, null, 0, aInfo, resultTo, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002234 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 Binder.restoreCallingIdentity(origId);
2236
2237 r.finishing = wasFinishing;
2238 if (res != START_SUCCESS) {
2239 return false;
2240 }
2241 return true;
2242 }
2243 }
2244
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002245 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 Intent intent, String resolvedType, IBinder resultTo,
2247 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002248
2249 // This is so super not safe, that only the system (or okay root)
2250 // can do it.
2251 final int callingUid = Binder.getCallingUid();
2252 if (callingUid != 0 && callingUid != Process.myUid()) {
2253 throw new SecurityException(
2254 "startActivityInPackage only available to the system");
2255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002257 return mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
2258 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false, null, null);
2259 }
2260
2261 public final int startActivities(IApplicationThread caller,
2262 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2263 return mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo);
2264 }
2265
2266 public final int startActivitiesInPackage(int uid,
2267 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2268
2269 // This is so super not safe, that only the system (or okay root)
2270 // can do it.
2271 final int callingUid = Binder.getCallingUid();
2272 if (callingUid != 0 && callingUid != Process.myUid()) {
2273 throw new SecurityException(
2274 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 }
2276
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002277 return mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278 }
2279
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002280 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002282 // Quick case: check if the top-most recent task is the same.
2283 if (N > 0 && mRecentTasks.get(0) == task) {
2284 return;
2285 }
2286 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 for (int i=0; i<N; i++) {
2288 TaskRecord tr = mRecentTasks.get(i);
2289 if ((task.affinity != null && task.affinity.equals(tr.affinity))
2290 || (task.intent != null && task.intent.filterEquals(tr.intent))) {
2291 mRecentTasks.remove(i);
2292 i--;
2293 N--;
2294 if (task.intent == null) {
2295 // If the new recent task we are adding is not fully
2296 // specified, then replace it with the existing recent task.
2297 task = tr;
2298 }
2299 }
2300 }
2301 if (N >= MAX_RECENT_TASKS) {
2302 mRecentTasks.remove(N-1);
2303 }
2304 mRecentTasks.add(0, task);
2305 }
2306
2307 public void setRequestedOrientation(IBinder token,
2308 int requestedOrientation) {
2309 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002310 ActivityRecord r = mMainStack.isInStackLocked(token);
2311 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 return;
2313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 final long origId = Binder.clearCallingIdentity();
2315 mWindowManager.setAppOrientation(r, requestedOrientation);
2316 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002317 mConfiguration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 r.mayFreezeScreenLocked(r.app) ? r : null);
2319 if (config != null) {
2320 r.frozenBeforeDestroy = true;
Dianne Hackborn31ca8542011-07-19 14:58:28 -07002321 if (!updateConfigurationLocked(config, r, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002322 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 }
2324 }
2325 Binder.restoreCallingIdentity(origId);
2326 }
2327 }
2328
2329 public int getRequestedOrientation(IBinder token) {
2330 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002331 ActivityRecord r = mMainStack.isInStackLocked(token);
2332 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 return mWindowManager.getAppOrientation(r);
2336 }
2337 }
2338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 /**
2340 * This is the internal entry point for handling Activity.finish().
2341 *
2342 * @param token The Binder token referencing the Activity we want to finish.
2343 * @param resultCode Result code, if any, from this Activity.
2344 * @param resultData Result data (Intent), if any, from this Activity.
2345 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002346 * @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 -08002347 */
2348 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2349 // Refuse possible leaked file descriptors
2350 if (resultData != null && resultData.hasFileDescriptors() == true) {
2351 throw new IllegalArgumentException("File descriptors passed in Intent");
2352 }
2353
2354 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002355 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002357 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 if (next != null) {
2359 // ask watcher if this is allowed
2360 boolean resumeOK = true;
2361 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002362 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002364 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 }
2366
2367 if (!resumeOK) {
2368 return false;
2369 }
2370 }
2371 }
2372 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002373 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 resultData, "app-request");
2375 Binder.restoreCallingIdentity(origId);
2376 return res;
2377 }
2378 }
2379
Dianne Hackborn860755f2010-06-03 18:47:52 -07002380 public final void finishHeavyWeightApp() {
2381 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2382 != PackageManager.PERMISSION_GRANTED) {
2383 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2384 + Binder.getCallingPid()
2385 + ", uid=" + Binder.getCallingUid()
2386 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2387 Slog.w(TAG, msg);
2388 throw new SecurityException(msg);
2389 }
2390
2391 synchronized(this) {
2392 if (mHeavyWeightProcess == null) {
2393 return;
2394 }
2395
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002396 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002397 mHeavyWeightProcess.activities);
2398 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002399 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002400 if (!r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002401 int index = mMainStack.indexOfTokenLocked(r);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002402 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002403 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002404 null, "finish-heavy");
2405 }
2406 }
2407 }
2408
2409 mHeavyWeightProcess = null;
2410 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2411 }
2412 }
2413
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002414 public void crashApplication(int uid, int initialPid, String packageName,
2415 String message) {
2416 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2417 != PackageManager.PERMISSION_GRANTED) {
2418 String msg = "Permission Denial: crashApplication() from pid="
2419 + Binder.getCallingPid()
2420 + ", uid=" + Binder.getCallingUid()
2421 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2422 Slog.w(TAG, msg);
2423 throw new SecurityException(msg);
2424 }
2425
2426 synchronized(this) {
2427 ProcessRecord proc = null;
2428
2429 // Figure out which process to kill. We don't trust that initialPid
2430 // still has any relation to current pids, so must scan through the
2431 // list.
2432 synchronized (mPidsSelfLocked) {
2433 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2434 ProcessRecord p = mPidsSelfLocked.valueAt(i);
2435 if (p.info.uid != uid) {
2436 continue;
2437 }
2438 if (p.pid == initialPid) {
2439 proc = p;
2440 break;
2441 }
2442 for (String str : p.pkgList) {
2443 if (str.equals(packageName)) {
2444 proc = p;
2445 }
2446 }
2447 }
2448 }
2449
2450 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002451 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002452 + " initialPid=" + initialPid
2453 + " packageName=" + packageName);
2454 return;
2455 }
2456
2457 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002458 if (proc.pid == Process.myPid()) {
2459 Log.w(TAG, "crashApplication: trying to crash self!");
2460 return;
2461 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002462 long ident = Binder.clearCallingIdentity();
2463 try {
2464 proc.thread.scheduleCrash(message);
2465 } catch (RemoteException e) {
2466 }
2467 Binder.restoreCallingIdentity(ident);
2468 }
2469 }
2470 }
2471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 public final void finishSubActivity(IBinder token, String resultWho,
2473 int requestCode) {
2474 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002475 ActivityRecord self = mMainStack.isInStackLocked(token);
2476 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 return;
2478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479
2480 final long origId = Binder.clearCallingIdentity();
2481
2482 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002483 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2484 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 if (r.resultTo == self && r.requestCode == requestCode) {
2486 if ((r.resultWho == null && resultWho == null) ||
2487 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002488 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 Activity.RESULT_CANCELED, null, "request-sub");
2490 }
2491 }
2492 }
2493
2494 Binder.restoreCallingIdentity(origId);
2495 }
2496 }
2497
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002498 public boolean willActivityBeVisible(IBinder token) {
2499 synchronized(this) {
2500 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002501 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2502 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002503 if (r == token) {
2504 return true;
2505 }
2506 if (r.fullscreen && !r.finishing) {
2507 return false;
2508 }
2509 }
2510 return true;
2511 }
2512 }
2513
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002514 public void overridePendingTransition(IBinder token, String packageName,
2515 int enterAnim, int exitAnim) {
2516 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002517 ActivityRecord self = mMainStack.isInStackLocked(token);
2518 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002519 return;
2520 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002521
2522 final long origId = Binder.clearCallingIdentity();
2523
2524 if (self.state == ActivityState.RESUMED
2525 || self.state == ActivityState.PAUSING) {
2526 mWindowManager.overridePendingAppTransition(packageName,
2527 enterAnim, exitAnim);
2528 }
2529
2530 Binder.restoreCallingIdentity(origId);
2531 }
2532 }
2533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 * Main function for removing an existing process from the activity manager
2536 * as a result of that process going away. Clears out all connections
2537 * to the process.
2538 */
2539 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002540 boolean restarting, boolean allowRestart) {
2541 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002543 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 }
2545
2546 // Just in case...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002547 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2548 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2549 mMainStack.mPausingActivity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002551 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2552 mMainStack.mLastPausedActivity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 }
2554
2555 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002556 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557
2558 boolean atTop = true;
2559 boolean hasVisibleActivities = false;
2560
2561 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002562 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002563 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 TAG, "Removing app " + app + " from history with " + i + " entries");
2565 while (i > 0) {
2566 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002567 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002568 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2570 if (r.app == app) {
2571 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002572 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 TAG, "Removing this entry! frozen=" + r.haveState
2574 + " finishing=" + r.finishing);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08002575 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002576 mMainStack.mHistory.remove(i);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002577 r.takeFromHistory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 mWindowManager.removeAppToken(r);
2579 if (VALIDATE_TOKENS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002580 mWindowManager.validateAppTokens(mMainStack.mHistory);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002582 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583
2584 } else {
2585 // We have the current state for this activity, so
2586 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002587 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 TAG, "Keeping entry, setting app to null");
2589 if (r.visible) {
2590 hasVisibleActivities = true;
2591 }
2592 r.app = null;
2593 r.nowVisible = false;
2594 if (!r.haveState) {
2595 r.icicle = null;
2596 }
2597 }
2598
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002599 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 }
2601 atTop = false;
2602 }
2603
2604 app.activities.clear();
2605
2606 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002607 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 + " running instrumentation " + app.instrumentationClass);
2609 Bundle info = new Bundle();
2610 info.putString("shortMsg", "Process crashed.");
2611 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2612 }
2613
2614 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002615 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 // If there was nothing to resume, and we are not already
2617 // restarting this process, but there is a visible activity that
2618 // is hosted by the process... then make sure all visible
2619 // activities are running, taking care of restarting this
2620 // process.
2621 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002622 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 }
2624 }
2625 }
2626 }
2627
2628 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2629 IBinder threadBinder = thread.asBinder();
2630
2631 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002632 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2633 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2635 return i;
2636 }
2637 }
2638 return -1;
2639 }
2640
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002641 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 IApplicationThread thread) {
2643 if (thread == null) {
2644 return null;
2645 }
2646
2647 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002648 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 }
2650
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002651 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 IApplicationThread thread) {
2653
2654 mProcDeaths[0]++;
2655
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002656 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2657 synchronized (stats) {
2658 stats.noteProcessDiedLocked(app.info.uid, pid);
2659 }
2660
Magnus Edlund7bb25812010-02-24 15:45:06 +01002661 // Clean up already done if the process has been re-started.
2662 if (app.pid == pid && app.thread != null &&
2663 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002664 if (!app.killedBackground) {
2665 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2666 + ") has died.");
2667 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002668 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002669 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 TAG, "Dying app: " + app + ", pid: " + pid
2671 + ", thread: " + thread.asBinder());
2672 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002673 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674
2675 if (doLowMem) {
2676 // If there are no longer any background processes running,
2677 // and the app that died was not running instrumentation,
2678 // then tell everyone we are now low on memory.
2679 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002680 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2681 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002682 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 haveBg = true;
2684 break;
2685 }
2686 }
2687
2688 if (!haveBg) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002689 Slog.i(TAG, "Low Memory: No more background processes.");
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002690 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002691 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002692 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2693 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002694 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002695 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2696 // The low memory report is overriding any current
2697 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002698 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002699 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002700 rec.lastRequestedGc = 0;
2701 } else {
2702 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002704 rec.reportLowMemory = true;
2705 rec.lastLowMemory = now;
2706 mProcessesToGc.remove(rec);
2707 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 }
2709 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002710 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 }
2712 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002713 } else if (app.pid != pid) {
2714 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002715 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002716 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002717 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002718 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002719 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 + thread.asBinder());
2721 }
2722 }
2723
Dan Egnor42471dd2010-01-07 17:25:22 -08002724 /**
2725 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002726 * @param clearTraces causes the dump file to be erased prior to the new
2727 * traces being written, if true; when false, the new traces will be
2728 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002729 * @param firstPids of dalvik VM processes to dump stack traces for first
2730 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002731 * @return file containing stack traces, or null if no dump file is configured
2732 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002733 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2734 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002735 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2736 if (tracesPath == null || tracesPath.length() == 0) {
2737 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002739
2740 File tracesFile = new File(tracesPath);
2741 try {
2742 File tracesDir = tracesFile.getParentFile();
2743 if (!tracesDir.exists()) tracesFile.mkdirs();
2744 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2745
Christopher Tate6ee412d2010-05-28 12:01:56 -07002746 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002747 tracesFile.createNewFile();
2748 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2749 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002750 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002751 return null;
2752 }
2753
2754 // Use a FileObserver to detect when traces finish writing.
2755 // The order of traces is considered important to maintain for legibility.
2756 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2757 public synchronized void onEvent(int event, String path) { notify(); }
2758 };
2759
2760 try {
2761 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002762
2763 // First collect all of the stacks of the most important pids.
2764 try {
2765 int num = firstPids.size();
2766 for (int i = 0; i < num; i++) {
2767 synchronized (observer) {
2768 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2769 observer.wait(200); // Wait for write-close, give up after 200msec
2770 }
2771 }
2772 } catch (InterruptedException e) {
2773 Log.wtf(TAG, e);
2774 }
2775
2776 // Next measure CPU usage.
2777 if (processStats != null) {
2778 processStats.init();
2779 System.gc();
2780 processStats.update();
2781 try {
2782 synchronized (processStats) {
2783 processStats.wait(500); // measure over 1/2 second.
2784 }
2785 } catch (InterruptedException e) {
2786 }
2787 processStats.update();
2788
2789 // We'll take the stack crawls of just the top apps using CPU.
2790 final int N = processStats.countWorkingStats();
2791 int numProcs = 0;
2792 for (int i=0; i<N && numProcs<5; i++) {
2793 ProcessStats.Stats stats = processStats.getWorkingStats(i);
2794 if (lastPids.indexOfKey(stats.pid) >= 0) {
2795 numProcs++;
2796 try {
2797 synchronized (observer) {
2798 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
2799 observer.wait(200); // Wait for write-close, give up after 200msec
2800 }
2801 } catch (InterruptedException e) {
2802 Log.wtf(TAG, e);
2803 }
2804
2805 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002806 }
2807 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002808
2809 return tracesFile;
2810
Dan Egnor42471dd2010-01-07 17:25:22 -08002811 } finally {
2812 observer.stopWatching();
2813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 }
2815
Jeff Brown4d94a762010-09-23 11:33:28 -07002816 private final class AppNotResponding implements Runnable {
2817 private final ProcessRecord mApp;
2818 private final String mAnnotation;
2819
2820 public AppNotResponding(ProcessRecord app, String annotation) {
2821 mApp = app;
2822 mAnnotation = annotation;
2823 }
2824
2825 @Override
2826 public void run() {
2827 appNotResponding(mApp, null, null, mAnnotation);
2828 }
2829 }
2830
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002831 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
2832 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002833 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
2834 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
2835
Dianne Hackborn287952c2010-09-22 22:34:31 -07002836 if (mController != null) {
2837 try {
2838 // 0 == continue, -1 = kill process immediately
2839 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
2840 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
2841 } catch (RemoteException e) {
2842 mController = null;
2843 }
2844 }
2845
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002846 long anrTime = SystemClock.uptimeMillis();
2847 if (MONITOR_CPU_USAGE) {
2848 updateCpuStatsNow();
2849 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002850
2851 synchronized (this) {
2852 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
2853 if (mShuttingDown) {
2854 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
2855 return;
2856 } else if (app.notResponding) {
2857 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
2858 return;
2859 } else if (app.crashing) {
2860 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
2861 return;
2862 }
2863
2864 // In case we come through here for the same app before completing
2865 // this one, mark as anring now so we will bail out.
2866 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08002867
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002868 // Log the ANR to the event log.
2869 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
2870 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08002871
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002872 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002873 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002874
2875 int parentPid = app.pid;
2876 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002877 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002878
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002879 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08002880
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002881 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
2882 ProcessRecord r = mLruProcesses.get(i);
2883 if (r != null && r.thread != null) {
2884 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002885 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
2886 if (r.persistent) {
2887 firstPids.add(pid);
2888 } else {
2889 lastPids.put(pid, Boolean.TRUE);
2890 }
2891 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 }
2894 }
2895
Dan Egnor42471dd2010-01-07 17:25:22 -08002896 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002897 StringBuilder info = mStringBuilder;
2898 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08002899 info.append("ANR in ").append(app.processName);
2900 if (activity != null && activity.shortComponentName != null) {
2901 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07002902 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08002903 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08002905 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002907 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08002908 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910
Dianne Hackborn287952c2010-09-22 22:34:31 -07002911 final ProcessStats processStats = new ProcessStats(true);
2912
2913 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
2914
Dan Egnor42471dd2010-01-07 17:25:22 -08002915 String cpuInfo = null;
2916 if (MONITOR_CPU_USAGE) {
2917 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002918 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002919 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002920 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002921 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08002922 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 }
2924
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002925 info.append(processStats.printCurrentState(anrTime));
2926
Joe Onorato8a9b2202010-02-26 18:56:32 -08002927 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08002928 if (tracesFile == null) {
2929 // There is no trace file, so dump (only) the alleged culprit's threads to the log
2930 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
2931 }
2932
2933 addErrorToDropBox("anr", app, activity, parent, annotation, cpuInfo, tracesFile, null);
2934
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002935 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08002937 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
2938 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002940 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
2941 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 }
2943 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002944 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 }
2946 }
2947
Dan Egnor42471dd2010-01-07 17:25:22 -08002948 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
2949 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
2950 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002951
2952 synchronized (this) {
2953 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002954 Slog.w(TAG, "Killing " + app + ": background ANR");
2955 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
2956 app.processName, app.setAdj, "background ANR");
2957 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002958 return;
2959 }
2960
2961 // Set the app's notResponding state, and look up the errorReportReceiver
2962 makeAppNotRespondingLocked(app,
2963 activity != null ? activity.shortComponentName : null,
2964 annotation != null ? "ANR " + annotation : "ANR",
2965 info.toString());
2966
2967 // Bring up the infamous App Not Responding dialog
2968 Message msg = Message.obtain();
2969 HashMap map = new HashMap();
2970 msg.what = SHOW_NOT_RESPONDING_MSG;
2971 msg.obj = map;
2972 map.put("app", app);
2973 if (activity != null) {
2974 map.put("activity", activity);
2975 }
2976
2977 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08002978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 }
2980
Dianne Hackborn0dad3642010-09-09 21:25:35 -07002981 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
2982 if (!mLaunchWarningShown) {
2983 mLaunchWarningShown = true;
2984 mHandler.post(new Runnable() {
2985 @Override
2986 public void run() {
2987 synchronized (ActivityManagerService.this) {
2988 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
2989 d.show();
2990 mHandler.postDelayed(new Runnable() {
2991 @Override
2992 public void run() {
2993 synchronized (ActivityManagerService.this) {
2994 d.dismiss();
2995 mLaunchWarningShown = false;
2996 }
2997 }
2998 }, 4000);
2999 }
3000 }
3001 });
3002 }
3003 }
3004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 public boolean clearApplicationUserData(final String packageName,
3006 final IPackageDataObserver observer) {
3007 int uid = Binder.getCallingUid();
3008 int pid = Binder.getCallingPid();
3009 long callingId = Binder.clearCallingIdentity();
3010 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003011 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 int pkgUid = -1;
3013 synchronized(this) {
3014 try {
3015 pkgUid = pm.getPackageUid(packageName);
3016 } catch (RemoteException e) {
3017 }
3018 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003019 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 return false;
3021 }
3022 if (uid == pkgUid || checkComponentPermission(
3023 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003024 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003026 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 } else {
3028 throw new SecurityException(pid+" does not have permission:"+
3029 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3030 "for process:"+packageName);
3031 }
3032 }
3033
3034 try {
3035 //clear application user data
3036 pm.clearApplicationUserData(packageName, observer);
3037 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3038 Uri.fromParts("package", packageName, null));
3039 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003040 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
3041 null, null, 0, null, null, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042 } catch (RemoteException e) {
3043 }
3044 } finally {
3045 Binder.restoreCallingIdentity(callingId);
3046 }
3047 return true;
3048 }
3049
Dianne Hackborn03abb812010-01-04 18:43:19 -08003050 public void killBackgroundProcesses(final String packageName) {
3051 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3052 != PackageManager.PERMISSION_GRANTED &&
3053 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3054 != PackageManager.PERMISSION_GRANTED) {
3055 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 + Binder.getCallingPid()
3057 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003058 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003059 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 throw new SecurityException(msg);
3061 }
3062
3063 long callingId = Binder.clearCallingIdentity();
3064 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003065 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 int pkgUid = -1;
3067 synchronized(this) {
3068 try {
3069 pkgUid = pm.getPackageUid(packageName);
3070 } catch (RemoteException e) {
3071 }
3072 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003073 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003074 return;
3075 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003076 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborn7d608422011-08-07 16:24:18 -07003077 ProcessList.SECONDARY_SERVER_ADJ, false, true, true);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003078 }
3079 } finally {
3080 Binder.restoreCallingIdentity(callingId);
3081 }
3082 }
3083
3084 public void forceStopPackage(final String packageName) {
3085 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3086 != PackageManager.PERMISSION_GRANTED) {
3087 String msg = "Permission Denial: forceStopPackage() from pid="
3088 + Binder.getCallingPid()
3089 + ", uid=" + Binder.getCallingUid()
3090 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003091 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003092 throw new SecurityException(msg);
3093 }
3094
3095 long callingId = Binder.clearCallingIdentity();
3096 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003097 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003098 int pkgUid = -1;
3099 synchronized(this) {
3100 try {
3101 pkgUid = pm.getPackageUid(packageName);
3102 } catch (RemoteException e) {
3103 }
3104 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003105 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003106 return;
3107 }
3108 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003109 try {
3110 pm.setPackageStoppedState(packageName, true);
3111 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003112 } catch (IllegalArgumentException e) {
3113 Slog.w(TAG, "Failed trying to unstop package "
3114 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 }
3117 } finally {
3118 Binder.restoreCallingIdentity(callingId);
3119 }
3120 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003121
3122 /*
3123 * The pkg name and uid have to be specified.
3124 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3125 */
3126 public void killApplicationWithUid(String pkg, int uid) {
3127 if (pkg == null) {
3128 return;
3129 }
3130 // Make sure the uid is valid.
3131 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003132 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003133 return;
3134 }
3135 int callerUid = Binder.getCallingUid();
3136 // Only the system server can kill an application
3137 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003138 // Post an aysnc message to kill the application
3139 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3140 msg.arg1 = uid;
3141 msg.arg2 = 0;
3142 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003143 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003144 } else {
3145 throw new SecurityException(callerUid + " cannot kill pkg: " +
3146 pkg);
3147 }
3148 }
3149
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003150 public void closeSystemDialogs(String reason) {
3151 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003152 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003153 if (reason != null) {
3154 intent.putExtra("reason", reason);
3155 }
3156
3157 final int uid = Binder.getCallingUid();
3158 final long origId = Binder.clearCallingIdentity();
3159 synchronized (this) {
3160 int i = mWatchers.beginBroadcast();
3161 while (i > 0) {
3162 i--;
3163 IActivityWatcher w = mWatchers.getBroadcastItem(i);
3164 if (w != null) {
3165 try {
3166 w.closingSystemDialogs(reason);
3167 } catch (RemoteException e) {
3168 }
3169 }
3170 }
3171 mWatchers.finishBroadcast();
3172
Dianne Hackbornffa42482009-09-23 22:20:11 -07003173 mWindowManager.closeSystemDialogs(reason);
3174
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003175 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3176 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003177 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003178 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003179 Activity.RESULT_CANCELED, null, "close-sys");
3180 }
3181 }
3182
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003183 broadcastIntentLocked(null, null, intent, null,
3184 null, 0, null, null, null, false, false, -1, uid);
3185 }
3186 Binder.restoreCallingIdentity(origId);
3187 }
3188
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003189 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003190 throws RemoteException {
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003191 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3192 for (int i=pids.length-1; i>=0; i--) {
3193 infos[i] = new Debug.MemoryInfo();
3194 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003195 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003196 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003197 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003198
Dianne Hackbornb437e092011-08-05 17:50:29 -07003199 public long[] getProcessPss(int[] pids) throws RemoteException {
3200 long[] pss = new long[pids.length];
3201 for (int i=pids.length-1; i>=0; i--) {
3202 pss[i] = Debug.getPss(pids[i]);
3203 }
3204 return pss;
3205 }
3206
Christopher Tate5e1ab332009-09-01 20:32:49 -07003207 public void killApplicationProcess(String processName, int uid) {
3208 if (processName == null) {
3209 return;
3210 }
3211
3212 int callerUid = Binder.getCallingUid();
3213 // Only the system server can kill an application
3214 if (callerUid == Process.SYSTEM_UID) {
3215 synchronized (this) {
3216 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003217 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003218 try {
3219 app.thread.scheduleSuicide();
3220 } catch (RemoteException e) {
3221 // If the other end already died, then our work here is done.
3222 }
3223 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003224 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003225 + processName + " / " + uid);
3226 }
3227 }
3228 } else {
3229 throw new SecurityException(callerUid + " cannot kill app process: " +
3230 processName);
3231 }
3232 }
3233
Dianne Hackborn03abb812010-01-04 18:43:19 -08003234 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003235 forceStopPackageLocked(packageName, uid, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3237 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003238 if (!mProcessesReady) {
3239 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241 intent.putExtra(Intent.EXTRA_UID, uid);
3242 broadcastIntentLocked(null, null, intent,
3243 null, null, 0, null, null, null,
3244 false, false, MY_PID, Process.SYSTEM_UID);
3245 }
3246
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003247 private final boolean killPackageProcessesLocked(String packageName, int uid,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003248 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003249 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250
Dianne Hackborn03abb812010-01-04 18:43:19 -08003251 // Remove all processes this package may have touched: all with the
3252 // same UID (except for the system or root user), and all whose name
3253 // matches the package name.
3254 final String procNamePrefix = packageName + ":";
3255 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3256 final int NA = apps.size();
3257 for (int ia=0; ia<NA; ia++) {
3258 ProcessRecord app = apps.valueAt(ia);
Christopher Tate064d8422011-07-26 15:38:07 -07003259 if (app.persistent) {
3260 // we don't kill persistent processes
3261 continue;
3262 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003263 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003264 if (doit) {
3265 procs.add(app);
3266 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003267 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3268 || app.processName.equals(packageName)
3269 || app.processName.startsWith(procNamePrefix)) {
3270 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003271 if (!doit) {
3272 return true;
3273 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003274 app.removed = true;
3275 procs.add(app);
3276 }
3277 }
3278 }
3279 }
3280
3281 int N = procs.size();
3282 for (int i=0; i<N; i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003283 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003284 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003285 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003286 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003287
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003288 private final boolean forceStopPackageLocked(String name, int uid,
3289 boolean callerWillRestart, boolean purgeCache, boolean doit) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003290 int i;
3291 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 if (uid < 0) {
3294 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003295 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 } catch (RemoteException e) {
3297 }
3298 }
3299
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003300 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003301 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003302
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003303 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3304 while (badApps.hasNext()) {
3305 SparseArray<Long> ba = badApps.next();
3306 if (ba.get(uid) != null) {
3307 badApps.remove();
3308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 }
3310 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003311
3312 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003313 callerWillRestart, false, doit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003315 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3316 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Christopher Tate064d8422011-07-26 15:38:07 -07003317 if (r.packageName.equals(name)
3318 && (r.app == null || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003319 if (!doit) {
3320 return true;
3321 }
3322 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003323 Slog.i(TAG, " Force finishing activity " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 if (r.app != null) {
3325 r.app.removed = true;
3326 }
3327 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003328 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "uninstall");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 }
3330 }
3331
3332 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3333 for (ServiceRecord service : mServices.values()) {
Christopher Tate064d8422011-07-26 15:38:07 -07003334 if (service.packageName.equals(name)
3335 && (service.app == null || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003336 if (!doit) {
3337 return true;
3338 }
3339 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003340 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 if (service.app != null) {
3342 service.app.removed = true;
3343 }
3344 service.app = null;
3345 services.add(service);
3346 }
3347 }
3348
3349 N = services.size();
3350 for (i=0; i<N; i++) {
3351 bringDownServiceLocked(services.get(i), true);
3352 }
3353
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003354 if (doit) {
3355 if (purgeCache) {
3356 AttributeCache ac = AttributeCache.instance();
3357 if (ac != null) {
3358 ac.removePackage(name);
3359 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003360 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003361 mMainStack.resumeTopActivityLocked(null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003362 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003363
3364 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 }
3366
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003367 private final boolean removeProcessLocked(ProcessRecord app,
3368 boolean callerWillRestart, boolean allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 final String name = app.processName;
3370 final int uid = app.info.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003371 if (DEBUG_PROCESSES) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 TAG, "Force removing process " + app + " (" + name
3373 + "/" + uid + ")");
3374
3375 mProcessNames.remove(name, uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003376 if (mHeavyWeightProcess == app) {
3377 mHeavyWeightProcess = null;
3378 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 boolean needRestart = false;
3381 if (app.pid > 0 && app.pid != MY_PID) {
3382 int pid = app.pid;
3383 synchronized (mPidsSelfLocked) {
3384 mPidsSelfLocked.remove(pid);
3385 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3386 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003387 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003388 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 Process.killProcess(pid);
3390
3391 if (app.persistent) {
3392 if (!callerWillRestart) {
3393 addAppLocked(app.info);
3394 } else {
3395 needRestart = true;
3396 }
3397 }
3398 } else {
3399 mRemovedProcesses.add(app);
3400 }
3401
3402 return needRestart;
3403 }
3404
3405 private final void processStartTimedOutLocked(ProcessRecord app) {
3406 final int pid = app.pid;
3407 boolean gone = false;
3408 synchronized (mPidsSelfLocked) {
3409 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3410 if (knownApp != null && knownApp.thread == null) {
3411 mPidsSelfLocked.remove(pid);
3412 gone = true;
3413 }
3414 }
3415
3416 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003417 Slog.w(TAG, "Process " + app + " failed to attach");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003418 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.info.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003419 app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003421 if (mHeavyWeightProcess == app) {
3422 mHeavyWeightProcess = null;
3423 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3424 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003425 // Take care of any launching providers waiting for this process.
3426 checkAppInLaunchingProvidersLocked(app, true);
3427 // Take care of any services that are waiting for the process.
3428 for (int i=0; i<mPendingServices.size(); i++) {
3429 ServiceRecord sr = mPendingServices.get(i);
3430 if (app.info.uid == sr.appInfo.uid
3431 && app.processName.equals(sr.processName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003432 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003433 mPendingServices.remove(i);
3434 i--;
3435 bringDownServiceLocked(sr, true);
3436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003438 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3439 app.processName, app.setAdj, "start timeout");
3440 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003441 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003442 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003443 try {
3444 IBackupManager bm = IBackupManager.Stub.asInterface(
3445 ServiceManager.getService(Context.BACKUP_SERVICE));
3446 bm.agentDisconnected(app.info.packageName);
3447 } catch (RemoteException e) {
3448 // Can't happen; the backup manager is local
3449 }
3450 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003451 if (mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003452 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003453 mPendingBroadcast.state = BroadcastRecord.IDLE;
3454 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003455 mPendingBroadcast = null;
3456 scheduleBroadcastsLocked();
3457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003459 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 }
3461 }
3462
3463 private final boolean attachApplicationLocked(IApplicationThread thread,
3464 int pid) {
3465
3466 // Find the application record that is being attached... either via
3467 // the pid if we are running in multiple processes, or just pull the
3468 // next app record if we are emulating process with anonymous threads.
3469 ProcessRecord app;
3470 if (pid != MY_PID && pid >= 0) {
3471 synchronized (mPidsSelfLocked) {
3472 app = mPidsSelfLocked.get(pid);
3473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 } else {
3475 app = null;
3476 }
3477
3478 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003479 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003481 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003483 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 } else {
3485 try {
3486 thread.scheduleExit();
3487 } catch (Exception e) {
3488 // Ignore exceptions.
3489 }
3490 }
3491 return false;
3492 }
3493
3494 // If this application record is still attached to a previous
3495 // process, clean it up now.
3496 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003497 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 }
3499
3500 // Tell the process all about itself.
3501
Joe Onorato8a9b2202010-02-26 18:56:32 -08003502 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 TAG, "Binding process pid " + pid + " to record " + app);
3504
3505 String processName = app.processName;
3506 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003507 AppDeathRecipient adr = new AppDeathRecipient(
3508 app, pid, thread);
3509 thread.asBinder().linkToDeath(adr, 0);
3510 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 } catch (RemoteException e) {
3512 app.resetPackageList();
3513 startProcessLocked(app, "link fail", processName);
3514 return false;
3515 }
3516
Doug Zongker2bec3d42009-12-04 12:52:44 -08003517 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518
3519 app.thread = thread;
3520 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003521 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3522 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003523 app.forcingToForeground = null;
3524 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003525 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 app.debugging = false;
3527
3528 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3529
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003530 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003531 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003533 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003534 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003535 }
3536
Joe Onorato8a9b2202010-02-26 18:56:32 -08003537 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 TAG, "New app record " + app
3539 + " thread=" + thread.asBinder() + " pid=" + pid);
3540 try {
3541 int testMode = IApplicationThread.DEBUG_OFF;
3542 if (mDebugApp != null && mDebugApp.equals(processName)) {
3543 testMode = mWaitForDebugger
3544 ? IApplicationThread.DEBUG_WAIT
3545 : IApplicationThread.DEBUG_ON;
3546 app.debugging = true;
3547 if (mDebugTransient) {
3548 mDebugApp = mOrigDebugApp;
3549 mWaitForDebugger = mOrigWaitForDebugger;
3550 }
3551 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003552
Christopher Tate181fafa2009-05-14 11:12:14 -07003553 // If the app is being launched for restore or full backup, set it up specially
3554 boolean isRestrictedBackupMode = false;
3555 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3556 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003557 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003558 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3559 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003560
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003561 ensurePackageDexOpt(app.instrumentationInfo != null
3562 ? app.instrumentationInfo.packageName
3563 : app.info.packageName);
3564 if (app.instrumentationClass != null) {
3565 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003566 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003567 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003568 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003569 ApplicationInfo appInfo = app.instrumentationInfo != null
3570 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003571 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003572 thread.bindApplication(processName, appInfo, providers,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 app.instrumentationClass, app.instrumentationProfileFile,
3574 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003575 isRestrictedBackupMode || !normalMode,
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003576 mConfiguration, app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003577 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003578 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003579 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 } catch (Exception e) {
3581 // todo: Yikes! What should we do? For now we will try to
3582 // start another process, but that could easily get us in
3583 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003584 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585
3586 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003587 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 startProcessLocked(app, "bind fail", processName);
3589 return false;
3590 }
3591
3592 // Remove this record from the list of starting applications.
3593 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003594 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3595 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 mProcessesOnHold.remove(app);
3597
3598 boolean badApp = false;
3599 boolean didSomething = false;
3600
3601 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003602 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003603 if (hr != null && normalMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
3605 && processName.equals(hr.processName)) {
3606 try {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003607 if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003608 didSomething = true;
3609 }
3610 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003611 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 + hr.intent.getComponent().flattenToShortString(), e);
3613 badApp = true;
3614 }
3615 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003616 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617 }
3618 }
3619
3620 // Find any services that should be running in this process...
3621 if (!badApp && mPendingServices.size() > 0) {
3622 ServiceRecord sr = null;
3623 try {
3624 for (int i=0; i<mPendingServices.size(); i++) {
3625 sr = mPendingServices.get(i);
3626 if (app.info.uid != sr.appInfo.uid
3627 || !processName.equals(sr.processName)) {
3628 continue;
3629 }
3630
3631 mPendingServices.remove(i);
3632 i--;
3633 realStartServiceLocked(sr, app);
3634 didSomething = true;
3635 }
3636 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003637 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003638 + sr.shortName, e);
3639 badApp = true;
3640 }
3641 }
3642
3643 // Check if the next broadcast receiver is in this process...
3644 BroadcastRecord br = mPendingBroadcast;
3645 if (!badApp && br != null && br.curApp == app) {
3646 try {
3647 mPendingBroadcast = null;
3648 processCurBroadcastLocked(br, app);
3649 didSomething = true;
3650 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003651 Slog.w(TAG, "Exception in new application when starting receiver "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 + br.curComponent.flattenToShortString(), e);
3653 badApp = true;
Jeff Brown4d94a762010-09-23 11:33:28 -07003654 logBroadcastReceiverDiscardLocked(br);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 finishReceiverLocked(br.receiver, br.resultCode, br.resultData,
3656 br.resultExtras, br.resultAbort, true);
3657 scheduleBroadcastsLocked();
Magnus Edlund7bb25812010-02-24 15:45:06 +01003658 // We need to reset the state if we fails to start the receiver.
3659 br.state = BroadcastRecord.IDLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 }
3661 }
3662
Christopher Tate181fafa2009-05-14 11:12:14 -07003663 // Check whether the next backup agent is in this process...
3664 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.info.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003665 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003666 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003667 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003668 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
3669 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
3670 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07003671 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003672 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003673 e.printStackTrace();
3674 }
3675 }
3676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 if (badApp) {
3678 // todo: Also need to kill application to deal with all
3679 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003680 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 return false;
3682 }
3683
3684 if (!didSomething) {
3685 updateOomAdjLocked();
3686 }
3687
3688 return true;
3689 }
3690
3691 public final void attachApplication(IApplicationThread thread) {
3692 synchronized (this) {
3693 int callingPid = Binder.getCallingPid();
3694 final long origId = Binder.clearCallingIdentity();
3695 attachApplicationLocked(thread, callingPid);
3696 Binder.restoreCallingIdentity(origId);
3697 }
3698 }
3699
Dianne Hackborne88846e2009-09-30 21:34:25 -07003700 public final void activityIdle(IBinder token, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003702 mMainStack.activityIdleInternal(token, false, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 Binder.restoreCallingIdentity(origId);
3704 }
3705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003706 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003707 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003708 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 mWindowManager.enableScreenAfterBoot();
3710 }
3711
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003712 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003713 IntentFilter pkgFilter = new IntentFilter();
3714 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
3715 pkgFilter.addDataScheme("package");
3716 mContext.registerReceiver(new BroadcastReceiver() {
3717 @Override
3718 public void onReceive(Context context, Intent intent) {
3719 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3720 if (pkgs != null) {
3721 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07003722 synchronized (ActivityManagerService.this) {
3723 if (forceStopPackageLocked(pkg, -1, false, false, false)) {
3724 setResultCode(Activity.RESULT_OK);
3725 return;
3726 }
3727 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003728 }
3729 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003730 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003731 }, pkgFilter);
3732
3733 synchronized (this) {
3734 // Ensure that any processes we had put on hold are now started
3735 // up.
3736 final int NP = mProcessesOnHold.size();
3737 if (NP > 0) {
3738 ArrayList<ProcessRecord> procs =
3739 new ArrayList<ProcessRecord>(mProcessesOnHold);
3740 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003741 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
3742 + procs.get(ip));
3743 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003744 }
3745 }
3746
3747 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003748 // Start looking for apps that are abusing wake locks.
3749 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003750 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003751 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07003752 SystemProperties.set("sys.boot_completed", "1");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003753 broadcastIntentLocked(null, null,
3754 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
3755 null, null, 0, null, null,
3756 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
3757 false, false, MY_PID, Process.SYSTEM_UID);
3758 }
3759 }
3760 }
3761
3762 final void ensureBootCompleted() {
3763 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003764 boolean enableScreen;
3765 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003766 booting = mBooting;
3767 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003768 enableScreen = !mBooted;
3769 mBooted = true;
3770 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003771
3772 if (booting) {
3773 finishBooting();
3774 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003775
3776 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003777 enableScreenAfterBoot();
3778 }
3779 }
3780
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003781 public final void activityPaused(IBinder token) {
3782 final long origId = Binder.clearCallingIdentity();
3783 mMainStack.activityPaused(token, false);
3784 Binder.restoreCallingIdentity(origId);
3785 }
3786
3787 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
3788 CharSequence description) {
3789 if (localLOGV) Slog.v(
3790 TAG, "Activity stopped: token=" + token);
3791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 // Refuse possible leaked file descriptors
3793 if (icicle != null && icicle.hasFileDescriptors()) {
3794 throw new IllegalArgumentException("File descriptors passed in Bundle");
3795 }
3796
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003797 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798
3799 final long origId = Binder.clearCallingIdentity();
3800
3801 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003802 r = mMainStack.isInStackLocked(token);
3803 if (r != null) {
3804 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 }
3806 }
3807
3808 if (r != null) {
3809 sendPendingThumbnail(r, null, null, null, false);
3810 }
3811
3812 trimApplications();
3813
3814 Binder.restoreCallingIdentity(origId);
3815 }
3816
3817 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003818 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003819 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 }
3821
3822 public String getCallingPackage(IBinder token) {
3823 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003824 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07003825 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826 }
3827 }
3828
3829 public ComponentName getCallingActivity(IBinder token) {
3830 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003831 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 return r != null ? r.intent.getComponent() : null;
3833 }
3834 }
3835
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003836 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003837 ActivityRecord r = mMainStack.isInStackLocked(token);
3838 if (r == null) {
3839 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003841 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 }
3843
3844 public ComponentName getActivityClassForToken(IBinder token) {
3845 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003846 ActivityRecord r = mMainStack.isInStackLocked(token);
3847 if (r == null) {
3848 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003850 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 }
3852 }
3853
3854 public String getPackageForToken(IBinder token) {
3855 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003856 ActivityRecord r = mMainStack.isInStackLocked(token);
3857 if (r == null) {
3858 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003860 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 }
3862 }
3863
3864 public IIntentSender getIntentSender(int type,
3865 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003866 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003868 if (intents != null) {
3869 if (intents.length < 1) {
3870 throw new IllegalArgumentException("Intents array length must be >= 1");
3871 }
3872 for (int i=0; i<intents.length; i++) {
3873 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07003874 if (intent != null) {
3875 if (intent.hasFileDescriptors()) {
3876 throw new IllegalArgumentException("File descriptors passed in Intent");
3877 }
3878 if (type == INTENT_SENDER_BROADCAST &&
3879 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
3880 throw new IllegalArgumentException(
3881 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
3882 }
3883 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003884 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003885 }
3886 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003887 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003888 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003889 }
3890 }
3891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 synchronized(this) {
3893 int callingUid = Binder.getCallingUid();
3894 try {
Jeff Brown10e89712011-07-08 18:52:57 -07003895 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003896 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 .getPackageUid(packageName);
3898 if (uid != Binder.getCallingUid()) {
3899 String msg = "Permission Denial: getIntentSender() from pid="
3900 + Binder.getCallingPid()
3901 + ", uid=" + Binder.getCallingUid()
3902 + ", (need uid=" + uid + ")"
3903 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003904 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 throw new SecurityException(msg);
3906 }
3907 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003908
3909 return getIntentSenderLocked(type, packageName, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003910 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 } catch (RemoteException e) {
3913 throw new SecurityException(e);
3914 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003915 }
3916 }
3917
3918 IIntentSender getIntentSenderLocked(int type,
3919 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003920 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003921 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003922 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003923 activity = mMainStack.isInStackLocked(token);
3924 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07003925 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003927 if (activity.finishing) {
3928 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003930 }
3931
3932 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
3933 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
3934 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
3935 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
3936 |PendingIntent.FLAG_UPDATE_CURRENT);
3937
3938 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
3939 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003940 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003941 WeakReference<PendingIntentRecord> ref;
3942 ref = mIntentSenderRecords.get(key);
3943 PendingIntentRecord rec = ref != null ? ref.get() : null;
3944 if (rec != null) {
3945 if (!cancelCurrent) {
3946 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003947 if (rec.key.requestIntent != null) {
3948 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
3949 }
3950 if (intents != null) {
3951 intents[intents.length-1] = rec.key.requestIntent;
3952 rec.key.allIntents = intents;
3953 rec.key.allResolvedTypes = resolvedTypes;
3954 } else {
3955 rec.key.allIntents = null;
3956 rec.key.allResolvedTypes = null;
3957 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 return rec;
3960 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003961 rec.canceled = true;
3962 mIntentSenderRecords.remove(key);
3963 }
3964 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965 return rec;
3966 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003967 rec = new PendingIntentRecord(this, key, callingUid);
3968 mIntentSenderRecords.put(key, rec.ref);
3969 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
3970 if (activity.pendingResults == null) {
3971 activity.pendingResults
3972 = new HashSet<WeakReference<PendingIntentRecord>>();
3973 }
3974 activity.pendingResults.add(rec.ref);
3975 }
3976 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 }
3978
3979 public void cancelIntentSender(IIntentSender sender) {
3980 if (!(sender instanceof PendingIntentRecord)) {
3981 return;
3982 }
3983 synchronized(this) {
3984 PendingIntentRecord rec = (PendingIntentRecord)sender;
3985 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003986 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 .getPackageUid(rec.key.packageName);
3988 if (uid != Binder.getCallingUid()) {
3989 String msg = "Permission Denial: cancelIntentSender() from pid="
3990 + Binder.getCallingPid()
3991 + ", uid=" + Binder.getCallingUid()
3992 + " is not allowed to cancel packges "
3993 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003994 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 throw new SecurityException(msg);
3996 }
3997 } catch (RemoteException e) {
3998 throw new SecurityException(e);
3999 }
4000 cancelIntentSenderLocked(rec, true);
4001 }
4002 }
4003
4004 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4005 rec.canceled = true;
4006 mIntentSenderRecords.remove(rec.key);
4007 if (cleanActivity && rec.key.activity != null) {
4008 rec.key.activity.pendingResults.remove(rec.ref);
4009 }
4010 }
4011
4012 public String getPackageForIntentSender(IIntentSender pendingResult) {
4013 if (!(pendingResult instanceof PendingIntentRecord)) {
4014 return null;
4015 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004016 try {
4017 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4018 return res.key.packageName;
4019 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 }
4021 return null;
4022 }
4023
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004024 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4025 if (!(pendingResult instanceof PendingIntentRecord)) {
4026 return false;
4027 }
4028 try {
4029 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4030 if (res.key.allIntents == null) {
4031 return false;
4032 }
4033 for (int i=0; i<res.key.allIntents.length; i++) {
4034 Intent intent = res.key.allIntents[i];
4035 if (intent.getPackage() != null && intent.getComponent() != null) {
4036 return false;
4037 }
4038 }
4039 return true;
4040 } catch (ClassCastException e) {
4041 }
4042 return false;
4043 }
4044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 public void setProcessLimit(int max) {
4046 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4047 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004048 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004049 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004050 mProcessLimitOverride = max;
4051 }
4052 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 }
4054
4055 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004056 synchronized (this) {
4057 return mProcessLimitOverride;
4058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 }
4060
4061 void foregroundTokenDied(ForegroundToken token) {
4062 synchronized (ActivityManagerService.this) {
4063 synchronized (mPidsSelfLocked) {
4064 ForegroundToken cur
4065 = mForegroundProcesses.get(token.pid);
4066 if (cur != token) {
4067 return;
4068 }
4069 mForegroundProcesses.remove(token.pid);
4070 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4071 if (pr == null) {
4072 return;
4073 }
4074 pr.forcingToForeground = null;
4075 pr.foregroundServices = false;
4076 }
4077 updateOomAdjLocked();
4078 }
4079 }
4080
4081 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4082 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4083 "setProcessForeground()");
4084 synchronized(this) {
4085 boolean changed = false;
4086
4087 synchronized (mPidsSelfLocked) {
4088 ProcessRecord pr = mPidsSelfLocked.get(pid);
4089 if (pr == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004090 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 return;
4092 }
4093 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4094 if (oldToken != null) {
4095 oldToken.token.unlinkToDeath(oldToken, 0);
4096 mForegroundProcesses.remove(pid);
4097 pr.forcingToForeground = null;
4098 changed = true;
4099 }
4100 if (isForeground && token != null) {
4101 ForegroundToken newToken = new ForegroundToken() {
4102 public void binderDied() {
4103 foregroundTokenDied(this);
4104 }
4105 };
4106 newToken.pid = pid;
4107 newToken.token = token;
4108 try {
4109 token.linkToDeath(newToken, 0);
4110 mForegroundProcesses.put(pid, newToken);
4111 pr.forcingToForeground = token;
4112 changed = true;
4113 } catch (RemoteException e) {
4114 // If the process died while doing this, we will later
4115 // do the cleanup with the process death link.
4116 }
4117 }
4118 }
4119
4120 if (changed) {
4121 updateOomAdjLocked();
4122 }
4123 }
4124 }
4125
4126 // =========================================================
4127 // PERMISSIONS
4128 // =========================================================
4129
4130 static class PermissionController extends IPermissionController.Stub {
4131 ActivityManagerService mActivityManagerService;
4132 PermissionController(ActivityManagerService activityManagerService) {
4133 mActivityManagerService = activityManagerService;
4134 }
4135
4136 public boolean checkPermission(String permission, int pid, int uid) {
4137 return mActivityManagerService.checkPermission(permission, pid,
4138 uid) == PackageManager.PERMISSION_GRANTED;
4139 }
4140 }
4141
4142 /**
4143 * This can be called with or without the global lock held.
4144 */
4145 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004146 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147 // We might be performing an operation on behalf of an indirect binder
4148 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4149 // client identity accordingly before proceeding.
4150 Identity tlsIdentity = sCallerIdentity.get();
4151 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004152 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4154 uid = tlsIdentity.uid;
4155 pid = tlsIdentity.pid;
4156 }
4157
4158 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004159 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 return PackageManager.PERMISSION_GRANTED;
4161 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004162 // If there is a uid that owns whatever is being accessed, it has
4163 // blanket access to it regardless of the permissions it requires.
4164 if (owningUid >= 0 && uid == owningUid) {
4165 return PackageManager.PERMISSION_GRANTED;
4166 }
4167 // If the target is not exported, then nobody else can get to it.
4168 if (!exported) {
4169 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 return PackageManager.PERMISSION_DENIED;
4171 }
4172 if (permission == null) {
4173 return PackageManager.PERMISSION_GRANTED;
4174 }
4175 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004176 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 .checkUidPermission(permission, uid);
4178 } catch (RemoteException e) {
4179 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004180 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181 }
4182 return PackageManager.PERMISSION_DENIED;
4183 }
4184
4185 /**
4186 * As the only public entry point for permissions checking, this method
4187 * can enforce the semantic that requesting a check on a null global
4188 * permission is automatically denied. (Internally a null permission
4189 * string is used when calling {@link #checkComponentPermission} in cases
4190 * when only uid-based security is needed.)
4191 *
4192 * This can be called with or without the global lock held.
4193 */
4194 public int checkPermission(String permission, int pid, int uid) {
4195 if (permission == null) {
4196 return PackageManager.PERMISSION_DENIED;
4197 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004198 return checkComponentPermission(permission, pid, uid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 }
4200
4201 /**
4202 * Binder IPC calls go through the public entry point.
4203 * This can be called with or without the global lock held.
4204 */
4205 int checkCallingPermission(String permission) {
4206 return checkPermission(permission,
4207 Binder.getCallingPid(),
4208 Binder.getCallingUid());
4209 }
4210
4211 /**
4212 * This can be called with or without the global lock held.
4213 */
4214 void enforceCallingPermission(String permission, String func) {
4215 if (checkCallingPermission(permission)
4216 == PackageManager.PERMISSION_GRANTED) {
4217 return;
4218 }
4219
4220 String msg = "Permission Denial: " + func + " from pid="
4221 + Binder.getCallingPid()
4222 + ", uid=" + Binder.getCallingUid()
4223 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004224 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 throw new SecurityException(msg);
4226 }
4227
4228 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07004229 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
4230 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4231 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
4232 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4233 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004235 // Is the component private from the target uid?
4236 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
4237
4238 // Acceptable if the there is no read permission needed from the
4239 // target or the target is holding the read permission.
4240 if (!readPerm) {
4241 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004243 == PackageManager.PERMISSION_GRANTED)) {
4244 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 }
4246 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004247
4248 // Acceptable if the there is no write permission needed from the
4249 // target or the target is holding the read permission.
4250 if (!writePerm) {
4251 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004252 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004253 == PackageManager.PERMISSION_GRANTED)) {
4254 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004255 }
4256 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004257
4258 // Acceptable if there is a path permission matching the URI that
4259 // the target holds the permission on.
4260 PathPermission[] pps = pi.pathPermissions;
4261 if (pps != null && (!readPerm || !writePerm)) {
4262 final String path = uri.getPath();
4263 int i = pps.length;
4264 while (i > 0 && (!readPerm || !writePerm)) {
4265 i--;
4266 PathPermission pp = pps[i];
4267 if (!readPerm) {
4268 final String pprperm = pp.getReadPermission();
4269 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4270 + pprperm + " for " + pp.getPath()
4271 + ": match=" + pp.match(path)
4272 + " check=" + pm.checkUidPermission(pprperm, uid));
4273 if (pprperm != null && pp.match(path) &&
4274 (pm.checkUidPermission(pprperm, uid)
4275 == PackageManager.PERMISSION_GRANTED)) {
4276 readPerm = true;
4277 }
4278 }
4279 if (!writePerm) {
4280 final String ppwperm = pp.getWritePermission();
4281 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4282 + ppwperm + " for " + pp.getPath()
4283 + ": match=" + pp.match(path)
4284 + " check=" + pm.checkUidPermission(ppwperm, uid));
4285 if (ppwperm != null && pp.match(path) &&
4286 (pm.checkUidPermission(ppwperm, uid)
4287 == PackageManager.PERMISSION_GRANTED)) {
4288 writePerm = true;
4289 }
4290 }
4291 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 } catch (RemoteException e) {
4294 return false;
4295 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004296
4297 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004298 }
4299
4300 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4301 int modeFlags) {
4302 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004303 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 return true;
4305 }
4306 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4307 if (perms == null) return false;
4308 UriPermission perm = perms.get(uri);
4309 if (perm == null) return false;
4310 return (modeFlags&perm.modeFlags) == modeFlags;
4311 }
4312
4313 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
4314 // Another redirected-binder-call permissions check as in
4315 // {@link checkComponentPermission}.
4316 Identity tlsIdentity = sCallerIdentity.get();
4317 if (tlsIdentity != null) {
4318 uid = tlsIdentity.uid;
4319 pid = tlsIdentity.pid;
4320 }
4321
4322 // Our own process gets to do everything.
4323 if (pid == MY_PID) {
4324 return PackageManager.PERMISSION_GRANTED;
4325 }
4326 synchronized(this) {
4327 return checkUriPermissionLocked(uri, uid, modeFlags)
4328 ? PackageManager.PERMISSION_GRANTED
4329 : PackageManager.PERMISSION_DENIED;
4330 }
4331 }
4332
Dianne Hackborn39792d22010-08-19 18:01:52 -07004333 /**
4334 * Check if the targetPkg can be granted permission to access uri by
4335 * the callingUid using the given modeFlags. Throws a security exception
4336 * if callingUid is not allowed to do this. Returns the uid of the target
4337 * if the URI permission grant should be performed; returns -1 if it is not
4338 * needed (for example targetPkg already has permission to access the URI).
4339 */
4340 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
4341 Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4343 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4344 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004345 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004346 }
4347
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004348 if (targetPkg != null) {
4349 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4350 "Checking grant " + targetPkg + " permission to " + uri);
4351 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004352
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004353 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004354
4355 // If this is not a content: uri, we can't do anything with it.
4356 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004357 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004358 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004359 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 }
4361
4362 String name = uri.getAuthority();
4363 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004364 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 if (cpr != null) {
4366 pi = cpr.info;
4367 } else {
4368 try {
4369 pi = pm.resolveContentProvider(name,
4370 PackageManager.GET_URI_PERMISSION_PATTERNS);
4371 } catch (RemoteException ex) {
4372 }
4373 }
4374 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004375 Slog.w(TAG, "No content provider found for: " + name);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004376 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004377 }
4378
4379 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004380 if (targetPkg != null) {
4381 try {
4382 targetUid = pm.getPackageUid(targetPkg);
4383 if (targetUid < 0) {
4384 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4385 "Can't grant URI permission no uid for: " + targetPkg);
4386 return -1;
4387 }
4388 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004389 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004391 } else {
4392 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 }
4394
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004395 if (targetUid >= 0) {
4396 // First... does the target actually need this permission?
4397 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4398 // No need to grant the target this permission.
4399 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4400 "Target " + targetPkg + " already has full permission to " + uri);
4401 return -1;
4402 }
4403 } else {
4404 // First... there is no target package, so can anyone access it?
4405 boolean allowed = pi.exported;
4406 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4407 if (pi.readPermission != null) {
4408 allowed = false;
4409 }
4410 }
4411 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4412 if (pi.writePermission != null) {
4413 allowed = false;
4414 }
4415 }
4416 if (allowed) {
4417 return -1;
4418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419 }
4420
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004421 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 if (!pi.grantUriPermissions) {
4423 throw new SecurityException("Provider " + pi.packageName
4424 + "/" + pi.name
4425 + " does not allow granting of Uri permissions (uri "
4426 + uri + ")");
4427 }
4428 if (pi.uriPermissionPatterns != null) {
4429 final int N = pi.uriPermissionPatterns.length;
4430 boolean allowed = false;
4431 for (int i=0; i<N; i++) {
4432 if (pi.uriPermissionPatterns[i] != null
4433 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4434 allowed = true;
4435 break;
4436 }
4437 }
4438 if (!allowed) {
4439 throw new SecurityException("Provider " + pi.packageName
4440 + "/" + pi.name
4441 + " does not allow granting of permission to path of Uri "
4442 + uri);
4443 }
4444 }
4445
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004446 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004448 if (callingUid != Process.myUid()) {
4449 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4450 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4451 throw new SecurityException("Uid " + callingUid
4452 + " does not have permission to uri " + uri);
4453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004454 }
4455 }
4456
Dianne Hackborn39792d22010-08-19 18:01:52 -07004457 return targetUid;
4458 }
4459
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004460 public int checkGrantUriPermission(int callingUid, String targetPkg,
4461 Uri uri, int modeFlags) {
4462 synchronized(this) {
4463 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4464 }
4465 }
4466
Dianne Hackborn39792d22010-08-19 18:01:52 -07004467 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4468 Uri uri, int modeFlags, UriPermissionOwner owner) {
4469 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4470 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4471 if (modeFlags == 0) {
4472 return;
4473 }
4474
4475 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 // to the uri, and the target doesn't. Let's now give this to
4477 // the target.
4478
Joe Onorato8a9b2202010-02-26 18:56:32 -08004479 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004480 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 HashMap<Uri, UriPermission> targetUris
4483 = mGrantedUriPermissions.get(targetUid);
4484 if (targetUris == null) {
4485 targetUris = new HashMap<Uri, UriPermission>();
4486 mGrantedUriPermissions.put(targetUid, targetUris);
4487 }
4488
4489 UriPermission perm = targetUris.get(uri);
4490 if (perm == null) {
4491 perm = new UriPermission(targetUid, uri);
4492 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004496 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004498 } else {
4499 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4500 perm.readOwners.add(owner);
4501 owner.addReadPermission(perm);
4502 }
4503 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4504 perm.writeOwners.add(owner);
4505 owner.addWritePermission(perm);
4506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 }
4508 }
4509
Dianne Hackborn39792d22010-08-19 18:01:52 -07004510 void grantUriPermissionLocked(int callingUid,
4511 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004512 if (targetPkg == null) {
4513 throw new NullPointerException("targetPkg");
4514 }
4515
Dianne Hackborn39792d22010-08-19 18:01:52 -07004516 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4517 if (targetUid < 0) {
4518 return;
4519 }
4520
4521 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4522 }
4523
4524 /**
4525 * Like checkGrantUriPermissionLocked, but takes an Intent.
4526 */
4527 int checkGrantUriPermissionFromIntentLocked(int callingUid,
4528 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004529 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004530 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004531 + " from " + intent + "; flags=0x"
4532 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4533
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004534 if (targetPkg == null) {
4535 throw new NullPointerException("targetPkg");
4536 }
4537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004538 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004539 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004540 }
4541 Uri data = intent.getData();
4542 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004543 return -1;
4544 }
4545 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4546 intent.getFlags());
4547 }
4548
4549 /**
4550 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4551 */
4552 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
4553 String targetPkg, Intent intent, UriPermissionOwner owner) {
4554 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
4555 intent.getFlags(), owner);
4556 }
4557
4558 void grantUriPermissionFromIntentLocked(int callingUid,
4559 String targetPkg, Intent intent, UriPermissionOwner owner) {
4560 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
4561 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004562 return;
4563 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004564
4565 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 }
4567
4568 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4569 Uri uri, int modeFlags) {
4570 synchronized(this) {
4571 final ProcessRecord r = getRecordForAppLocked(caller);
4572 if (r == null) {
4573 throw new SecurityException("Unable to find app for caller "
4574 + caller
4575 + " when granting permission to uri " + uri);
4576 }
4577 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004578 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004579 }
4580 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004581 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 }
4583
4584 grantUriPermissionLocked(r.info.uid, targetPkg, uri, modeFlags,
4585 null);
4586 }
4587 }
4588
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004589 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4591 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4592 HashMap<Uri, UriPermission> perms
4593 = mGrantedUriPermissions.get(perm.uid);
4594 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004595 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004596 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004597 perms.remove(perm.uri);
4598 if (perms.size() == 0) {
4599 mGrantedUriPermissions.remove(perm.uid);
4600 }
4601 }
4602 }
4603 }
4604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 private void revokeUriPermissionLocked(int callingUid, Uri uri,
4606 int modeFlags) {
4607 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4608 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4609 if (modeFlags == 0) {
4610 return;
4611 }
4612
Joe Onorato8a9b2202010-02-26 18:56:32 -08004613 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004614 "Revoking all granted permissions to " + uri);
4615
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004616 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617
4618 final String authority = uri.getAuthority();
4619 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004620 ContentProviderRecord cpr = mProvidersByName.get(authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 if (cpr != null) {
4622 pi = cpr.info;
4623 } else {
4624 try {
4625 pi = pm.resolveContentProvider(authority,
4626 PackageManager.GET_URI_PERMISSION_PATTERNS);
4627 } catch (RemoteException ex) {
4628 }
4629 }
4630 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004631 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 return;
4633 }
4634
4635 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07004636 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 // Right now, if you are not the original owner of the permission,
4638 // you are not allowed to revoke it.
4639 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4640 throw new SecurityException("Uid " + callingUid
4641 + " does not have permission to uri " + uri);
4642 //}
4643 }
4644
4645 // Go through all of the permissions and remove any that match.
4646 final List<String> SEGMENTS = uri.getPathSegments();
4647 if (SEGMENTS != null) {
4648 final int NS = SEGMENTS.size();
4649 int N = mGrantedUriPermissions.size();
4650 for (int i=0; i<N; i++) {
4651 HashMap<Uri, UriPermission> perms
4652 = mGrantedUriPermissions.valueAt(i);
4653 Iterator<UriPermission> it = perms.values().iterator();
4654 toploop:
4655 while (it.hasNext()) {
4656 UriPermission perm = it.next();
4657 Uri targetUri = perm.uri;
4658 if (!authority.equals(targetUri.getAuthority())) {
4659 continue;
4660 }
4661 List<String> targetSegments = targetUri.getPathSegments();
4662 if (targetSegments == null) {
4663 continue;
4664 }
4665 if (targetSegments.size() < NS) {
4666 continue;
4667 }
4668 for (int j=0; j<NS; j++) {
4669 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
4670 continue toploop;
4671 }
4672 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004673 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004674 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 perm.clearModes(modeFlags);
4676 if (perm.modeFlags == 0) {
4677 it.remove();
4678 }
4679 }
4680 if (perms.size() == 0) {
4681 mGrantedUriPermissions.remove(
4682 mGrantedUriPermissions.keyAt(i));
4683 N--;
4684 i--;
4685 }
4686 }
4687 }
4688 }
4689
4690 public void revokeUriPermission(IApplicationThread caller, Uri uri,
4691 int modeFlags) {
4692 synchronized(this) {
4693 final ProcessRecord r = getRecordForAppLocked(caller);
4694 if (r == null) {
4695 throw new SecurityException("Unable to find app for caller "
4696 + caller
4697 + " when revoking permission to uri " + uri);
4698 }
4699 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004700 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004701 return;
4702 }
4703
4704 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4705 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4706 if (modeFlags == 0) {
4707 return;
4708 }
4709
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004710 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004711
4712 final String authority = uri.getAuthority();
4713 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004714 ContentProviderRecord cpr = mProvidersByName.get(authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 if (cpr != null) {
4716 pi = cpr.info;
4717 } else {
4718 try {
4719 pi = pm.resolveContentProvider(authority,
4720 PackageManager.GET_URI_PERMISSION_PATTERNS);
4721 } catch (RemoteException ex) {
4722 }
4723 }
4724 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004725 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004726 return;
4727 }
4728
4729 revokeUriPermissionLocked(r.info.uid, uri, modeFlags);
4730 }
4731 }
4732
Dianne Hackborn7e269642010-08-25 19:50:20 -07004733 @Override
4734 public IBinder newUriPermissionOwner(String name) {
4735 synchronized(this) {
4736 UriPermissionOwner owner = new UriPermissionOwner(this, name);
4737 return owner.getExternalTokenLocked();
4738 }
4739 }
4740
4741 @Override
4742 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
4743 Uri uri, int modeFlags) {
4744 synchronized(this) {
4745 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
4746 if (owner == null) {
4747 throw new IllegalArgumentException("Unknown owner: " + token);
4748 }
4749 if (fromUid != Binder.getCallingUid()) {
4750 if (Binder.getCallingUid() != Process.myUid()) {
4751 // Only system code can grant URI permissions on behalf
4752 // of other users.
4753 throw new SecurityException("nice try");
4754 }
4755 }
4756 if (targetPkg == null) {
4757 throw new IllegalArgumentException("null target");
4758 }
4759 if (uri == null) {
4760 throw new IllegalArgumentException("null uri");
4761 }
4762
4763 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
4764 }
4765 }
4766
4767 @Override
4768 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
4769 synchronized(this) {
4770 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
4771 if (owner == null) {
4772 throw new IllegalArgumentException("Unknown owner: " + token);
4773 }
4774
4775 if (uri == null) {
4776 owner.removeUriPermissionsLocked(mode);
4777 } else {
4778 owner.removeUriPermissionLocked(uri, mode);
4779 }
4780 }
4781 }
4782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004783 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
4784 synchronized (this) {
4785 ProcessRecord app =
4786 who != null ? getRecordForAppLocked(who) : null;
4787 if (app == null) return;
4788
4789 Message msg = Message.obtain();
4790 msg.what = WAIT_FOR_DEBUGGER_MSG;
4791 msg.obj = app;
4792 msg.arg1 = waiting ? 1 : 0;
4793 mHandler.sendMessage(msg);
4794 }
4795 }
4796
4797 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004798 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
4799 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004800 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07004801 outInfo.threshold = homeAppMem;
4802 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
4803 outInfo.hiddenAppThreshold = hiddenAppMem;
4804 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
4805 ProcessList.SECONDARY_SERVER_ADJ);
4806 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
4807 ProcessList.VISIBLE_APP_ADJ);
4808 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
4809 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004810 }
4811
4812 // =========================================================
4813 // TASK MANAGEMENT
4814 // =========================================================
4815
4816 public List getTasks(int maxNum, int flags,
4817 IThumbnailReceiver receiver) {
4818 ArrayList list = new ArrayList();
4819
4820 PendingThumbnailsRecord pending = null;
4821 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004822 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004823
4824 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004825 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
4827 + ", receiver=" + receiver);
4828
4829 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
4830 != PackageManager.PERMISSION_GRANTED) {
4831 if (receiver != null) {
4832 // If the caller wants to wait for pending thumbnails,
4833 // it ain't gonna get them.
4834 try {
4835 receiver.finished();
4836 } catch (RemoteException ex) {
4837 }
4838 }
4839 String msg = "Permission Denial: getTasks() from pid="
4840 + Binder.getCallingPid()
4841 + ", uid=" + Binder.getCallingUid()
4842 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004843 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004844 throw new SecurityException(msg);
4845 }
4846
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004847 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004848 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004849 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004850 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004851 TaskRecord curTask = null;
4852 int numActivities = 0;
4853 int numRunning = 0;
4854 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004855 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004856 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004857 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004858
4859 // Initialize state for next task if needed.
4860 if (top == null ||
4861 (top.state == ActivityState.INITIALIZING
4862 && top.task == r.task)) {
4863 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004864 curTask = r.task;
4865 numActivities = numRunning = 0;
4866 }
4867
4868 // Add 'r' into the current task.
4869 numActivities++;
4870 if (r.app != null && r.app.thread != null) {
4871 numRunning++;
4872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004873
Joe Onorato8a9b2202010-02-26 18:56:32 -08004874 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004875 TAG, r.intent.getComponent().flattenToShortString()
4876 + ": task=" + r.task);
4877
4878 // If the next one is a different task, generate a new
4879 // TaskInfo entry for what we have.
4880 if (next == null || next.task != curTask) {
4881 ActivityManager.RunningTaskInfo ci
4882 = new ActivityManager.RunningTaskInfo();
4883 ci.id = curTask.taskId;
4884 ci.baseActivity = r.intent.getComponent();
4885 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07004886 if (top.thumbHolder != null) {
4887 ci.description = top.thumbHolder.lastDescription;
4888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004889 ci.numActivities = numActivities;
4890 ci.numRunning = numRunning;
4891 //System.out.println(
4892 // "#" + maxNum + ": " + " descr=" + ci.description);
4893 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004894 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 TAG, "State=" + top.state + "Idle=" + top.idle
4896 + " app=" + top.app
4897 + " thr=" + (top.app != null ? top.app.thread : null));
4898 if (top.state == ActivityState.RESUMED
4899 || top.state == ActivityState.PAUSING) {
4900 if (top.idle && top.app != null
4901 && top.app.thread != null) {
4902 topRecord = top;
4903 topThumbnail = top.app.thread;
4904 } else {
4905 top.thumbnailNeeded = true;
4906 }
4907 }
4908 if (pending == null) {
4909 pending = new PendingThumbnailsRecord(receiver);
4910 }
4911 pending.pendingRecords.add(top);
4912 }
4913 list.add(ci);
4914 maxNum--;
4915 top = null;
4916 }
4917 }
4918
4919 if (pending != null) {
4920 mPendingThumbnails.add(pending);
4921 }
4922 }
4923
Joe Onorato8a9b2202010-02-26 18:56:32 -08004924 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925
4926 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004927 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004928 try {
4929 topThumbnail.requestThumbnail(topRecord);
4930 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004931 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004932 sendPendingThumbnail(null, topRecord, null, null, true);
4933 }
4934 }
4935
4936 if (pending == null && receiver != null) {
4937 // In this case all thumbnails were available and the client
4938 // is being asked to be told when the remaining ones come in...
4939 // which is unusually, since the top-most currently running
4940 // activity should never have a canned thumbnail! Oh well.
4941 try {
4942 receiver.finished();
4943 } catch (RemoteException ex) {
4944 }
4945 }
4946
4947 return list;
4948 }
4949
4950 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
4951 int flags) {
4952 synchronized (this) {
4953 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
4954 "getRecentTasks()");
4955
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004956 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07004957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004958 final int N = mRecentTasks.size();
4959 ArrayList<ActivityManager.RecentTaskInfo> res
4960 = new ArrayList<ActivityManager.RecentTaskInfo>(
4961 maxNum < N ? maxNum : N);
4962 for (int i=0; i<N && maxNum > 0; i++) {
4963 TaskRecord tr = mRecentTasks.get(i);
4964 if (((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
4965 || (tr.intent == null)
4966 || ((tr.intent.getFlags()
4967 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
4968 ActivityManager.RecentTaskInfo rti
4969 = new ActivityManager.RecentTaskInfo();
4970 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08004971 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004972 rti.baseIntent = new Intent(
4973 tr.intent != null ? tr.intent : tr.affinityIntent);
4974 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08004975 rti.description = tr.lastDescription;
4976
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07004977 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
4978 // Check whether this activity is currently available.
4979 try {
4980 if (rti.origActivity != null) {
4981 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
4982 continue;
4983 }
4984 } else if (rti.baseIntent != null) {
4985 if (pm.queryIntentActivities(rti.baseIntent,
4986 null, 0) == null) {
4987 continue;
4988 }
4989 }
4990 } catch (RemoteException e) {
4991 // Will never happen.
4992 }
4993 }
4994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004995 res.add(rti);
4996 maxNum--;
4997 }
4998 }
4999 return res;
5000 }
5001 }
5002
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005003 private TaskRecord taskForIdLocked(int id) {
5004 final int N = mRecentTasks.size();
5005 for (int i=0; i<N; i++) {
5006 TaskRecord tr = mRecentTasks.get(i);
5007 if (tr.taskId == id) {
5008 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005009 }
5010 }
5011 return null;
5012 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005013
5014 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5015 synchronized (this) {
5016 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5017 "getTaskThumbnails()");
5018 TaskRecord tr = taskForIdLocked(id);
5019 if (tr != null) {
5020 return mMainStack.getTaskThumbnailsLocked(tr);
5021 }
5022 }
5023 return null;
5024 }
5025
5026 public boolean removeSubTask(int taskId, int subTaskIndex) {
5027 synchronized (this) {
5028 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5029 "removeSubTask()");
5030 long ident = Binder.clearCallingIdentity();
5031 try {
5032 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
5033 } finally {
5034 Binder.restoreCallingIdentity(ident);
5035 }
5036 }
5037 }
5038
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005039 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005040 TaskRecord tr = root.task;
5041 Intent baseIntent = new Intent(
5042 tr.intent != null ? tr.intent : tr.affinityIntent);
5043 ComponentName component = baseIntent.getComponent();
5044 if (component == null) {
5045 Slog.w(TAG, "Now component for base intent of task: " + tr);
5046 return;
5047 }
5048
5049 // Find any running services associated with this app.
5050 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
5051 for (ServiceRecord sr : mServices.values()) {
5052 if (sr.packageName.equals(component.getPackageName())) {
5053 services.add(sr);
5054 }
5055 }
5056
5057 // Take care of any running services associated with the app.
5058 for (int i=0; i<services.size(); i++) {
5059 ServiceRecord sr = services.get(i);
5060 if (sr.startRequested) {
5061 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005062 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005063 stopServiceLocked(sr);
5064 } else {
5065 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
5066 sr.makeNextStartId(), baseIntent, -1));
5067 if (sr.app != null && sr.app.thread != null) {
5068 sendServiceArgsLocked(sr, false);
5069 }
5070 }
5071 }
5072 }
5073
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005074 if (killProcesses) {
5075 // Find any running processes associated with this app.
5076 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5077 SparseArray<ProcessRecord> appProcs
5078 = mProcessNames.getMap().get(component.getPackageName());
5079 if (appProcs != null) {
5080 for (int i=0; i<appProcs.size(); i++) {
5081 procs.add(appProcs.valueAt(i));
5082 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005083 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005084
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005085 // Kill the running processes.
5086 for (int i=0; i<procs.size(); i++) {
5087 ProcessRecord pr = procs.get(i);
5088 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5089 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5090 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5091 pr.processName, pr.setAdj, "remove task");
5092 Process.killProcessQuiet(pr.pid);
5093 } else {
5094 pr.waitingToKill = "remove task";
5095 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005096 }
5097 }
5098 }
5099
5100 public boolean removeTask(int taskId, int flags) {
5101 synchronized (this) {
5102 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5103 "removeTask()");
5104 long ident = Binder.clearCallingIdentity();
5105 try {
5106 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
5107 if (r != null) {
5108 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005109 cleanUpRemovedTaskLocked(r,
5110 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005111 return true;
5112 }
5113 } finally {
5114 Binder.restoreCallingIdentity(ident);
5115 }
5116 }
5117 return false;
5118 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005120 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5121 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005122 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 TaskRecord jt = startTask;
5124
5125 // First look backwards
5126 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005127 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 if (r.task != jt) {
5129 jt = r.task;
5130 if (affinity.equals(jt.affinity)) {
5131 return j;
5132 }
5133 }
5134 }
5135
5136 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005137 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005138 jt = startTask;
5139 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005140 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005141 if (r.task != jt) {
5142 if (affinity.equals(jt.affinity)) {
5143 return j;
5144 }
5145 jt = r.task;
5146 }
5147 }
5148
5149 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005150 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005151 return N-1;
5152 }
5153
5154 return -1;
5155 }
5156
5157 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005158 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005159 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005160 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005161 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5162 "moveTaskToFront()");
5163
5164 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005165 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5166 Binder.getCallingUid(), "Task to front")) {
5167 return;
5168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005169 final long origId = Binder.clearCallingIdentity();
5170 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005171 TaskRecord tr = taskForIdLocked(task);
5172 if (tr != null) {
5173 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5174 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005175 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005176 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5177 // Caller wants the home activity moved with it. To accomplish this,
5178 // we'll just move the home task to the top first.
5179 mMainStack.moveHomeToFrontLocked();
5180 }
5181 mMainStack.moveTaskToFrontLocked(tr, null);
5182 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005183 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005184 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5185 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005187 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5188 mMainStack.mUserLeaving = true;
5189 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005190 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5191 // Caller wants the home activity moved with it. To accomplish this,
5192 // we'll just move the home task to the top first.
5193 mMainStack.moveHomeToFrontLocked();
5194 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005195 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 return;
5197 }
5198 }
5199 } finally {
5200 Binder.restoreCallingIdentity(origId);
5201 }
5202 }
5203 }
5204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 public void moveTaskToBack(int task) {
5206 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5207 "moveTaskToBack()");
5208
5209 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005210 if (mMainStack.mResumedActivity != null
5211 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005212 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5213 Binder.getCallingUid(), "Task to back")) {
5214 return;
5215 }
5216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005218 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 Binder.restoreCallingIdentity(origId);
5220 }
5221 }
5222
5223 /**
5224 * Moves an activity, and all of the other activities within the same task, to the bottom
5225 * of the history stack. The activity's order within the task is unchanged.
5226 *
5227 * @param token A reference to the activity we wish to move
5228 * @param nonRoot If false then this only works if the activity is the root
5229 * of a task; if true it will work for any activity in a task.
5230 * @return Returns true if the move completed, false if not.
5231 */
5232 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
5233 synchronized(this) {
5234 final long origId = Binder.clearCallingIdentity();
5235 int taskId = getTaskForActivityLocked(token, !nonRoot);
5236 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005237 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238 }
5239 Binder.restoreCallingIdentity(origId);
5240 }
5241 return false;
5242 }
5243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 public void moveTaskBackwards(int task) {
5245 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5246 "moveTaskBackwards()");
5247
5248 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005249 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5250 Binder.getCallingUid(), "Task backwards")) {
5251 return;
5252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005253 final long origId = Binder.clearCallingIdentity();
5254 moveTaskBackwardsLocked(task);
5255 Binder.restoreCallingIdentity(origId);
5256 }
5257 }
5258
5259 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005260 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005261 }
5262
5263 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5264 synchronized(this) {
5265 return getTaskForActivityLocked(token, onlyRoot);
5266 }
5267 }
5268
5269 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005270 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005271 TaskRecord lastTask = null;
5272 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005273 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005274 if (r == token) {
5275 if (!onlyRoot || lastTask != r.task) {
5276 return r.task.taskId;
5277 }
5278 return -1;
5279 }
5280 lastTask = r.task;
5281 }
5282
5283 return -1;
5284 }
5285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005286 public void finishOtherInstances(IBinder token, ComponentName className) {
5287 synchronized(this) {
5288 final long origId = Binder.clearCallingIdentity();
5289
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005290 int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 TaskRecord lastTask = null;
5292 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005293 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 if (r.realActivity.equals(className)
5295 && r != token && lastTask != r.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005296 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005297 null, "others")) {
5298 i--;
5299 N--;
5300 }
5301 }
5302 lastTask = r.task;
5303 }
5304
5305 Binder.restoreCallingIdentity(origId);
5306 }
5307 }
5308
5309 // =========================================================
5310 // THUMBNAILS
5311 // =========================================================
5312
5313 public void reportThumbnail(IBinder token,
5314 Bitmap thumbnail, CharSequence description) {
5315 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5316 final long origId = Binder.clearCallingIdentity();
5317 sendPendingThumbnail(null, token, thumbnail, description, true);
5318 Binder.restoreCallingIdentity(origId);
5319 }
5320
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005321 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005322 Bitmap thumbnail, CharSequence description, boolean always) {
5323 TaskRecord task = null;
5324 ArrayList receivers = null;
5325
5326 //System.out.println("Send pending thumbnail: " + r);
5327
5328 synchronized(this) {
5329 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005330 r = mMainStack.isInStackLocked(token);
5331 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 return;
5333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005334 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005335 if (thumbnail == null && r.thumbHolder != null) {
5336 thumbnail = r.thumbHolder.lastThumbnail;
5337 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005338 }
5339 if (thumbnail == null && !always) {
5340 // If there is no thumbnail, and this entry is not actually
5341 // going away, then abort for now and pick up the next
5342 // thumbnail we get.
5343 return;
5344 }
5345 task = r.task;
5346
5347 int N = mPendingThumbnails.size();
5348 int i=0;
5349 while (i<N) {
5350 PendingThumbnailsRecord pr =
5351 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5352 //System.out.println("Looking in " + pr.pendingRecords);
5353 if (pr.pendingRecords.remove(r)) {
5354 if (receivers == null) {
5355 receivers = new ArrayList();
5356 }
5357 receivers.add(pr);
5358 if (pr.pendingRecords.size() == 0) {
5359 pr.finished = true;
5360 mPendingThumbnails.remove(i);
5361 N--;
5362 continue;
5363 }
5364 }
5365 i++;
5366 }
5367 }
5368
5369 if (receivers != null) {
5370 final int N = receivers.size();
5371 for (int i=0; i<N; i++) {
5372 try {
5373 PendingThumbnailsRecord pr =
5374 (PendingThumbnailsRecord)receivers.get(i);
5375 pr.receiver.newThumbnail(
5376 task != null ? task.taskId : -1, thumbnail, description);
5377 if (pr.finished) {
5378 pr.receiver.finished();
5379 }
5380 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005381 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005382 }
5383 }
5384 }
5385 }
5386
5387 // =========================================================
5388 // CONTENT PROVIDERS
5389 // =========================================================
5390
Jeff Brown10e89712011-07-08 18:52:57 -07005391 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5392 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005393 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005394 providers = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 queryContentProviders(app.processName, app.info.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005396 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 } catch (RemoteException ex) {
5398 }
5399 if (providers != null) {
5400 final int N = providers.size();
5401 for (int i=0; i<N; i++) {
5402 ProviderInfo cpi =
5403 (ProviderInfo)providers.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07005404 ContentProviderRecord cpr = mProvidersByClass.get(cpi.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005405 if (cpr == null) {
5406 cpr = new ContentProviderRecord(cpi, app.info);
5407 mProvidersByClass.put(cpi.name, cpr);
5408 }
5409 app.pubProviders.put(cpi.name, cpr);
5410 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005411 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005412 }
5413 }
5414 return providers;
5415 }
5416
5417 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005418 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
5420 final int callingUid = (r != null) ? r.info.uid : Binder.getCallingUid();
5421 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005422 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005423 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424 return null;
5425 }
5426 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005427 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005428 == PackageManager.PERMISSION_GRANTED) {
5429 return null;
5430 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005431
5432 PathPermission[] pps = cpi.pathPermissions;
5433 if (pps != null) {
5434 int i = pps.length;
5435 while (i > 0) {
5436 i--;
5437 PathPermission pp = pps[i];
5438 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005439 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005440 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005441 return null;
5442 }
5443 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005444 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005445 == PackageManager.PERMISSION_GRANTED) {
5446 return null;
5447 }
5448 }
5449 }
5450
Dianne Hackbornb424b632010-08-18 15:59:05 -07005451 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5452 if (perms != null) {
5453 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5454 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5455 return null;
5456 }
5457 }
5458 }
5459
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005460 String msg;
5461 if (!cpi.exported) {
5462 msg = "Permission Denial: opening provider " + cpi.name
5463 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5464 + ", uid=" + callingUid + ") that is not exported from uid "
5465 + cpi.applicationInfo.uid;
5466 } else {
5467 msg = "Permission Denial: opening provider " + cpi.name
5468 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5469 + ", uid=" + callingUid + ") requires "
5470 + cpi.readPermission + " or " + cpi.writePermission;
5471 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005472 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005473 return msg;
5474 }
5475
5476 private final ContentProviderHolder getContentProviderImpl(
5477 IApplicationThread caller, String name) {
5478 ContentProviderRecord cpr;
5479 ProviderInfo cpi = null;
5480
5481 synchronized(this) {
5482 ProcessRecord r = null;
5483 if (caller != null) {
5484 r = getRecordForAppLocked(caller);
5485 if (r == null) {
5486 throw new SecurityException(
5487 "Unable to find app for caller " + caller
5488 + " (pid=" + Binder.getCallingPid()
5489 + ") when getting content provider " + name);
5490 }
5491 }
5492
5493 // First check if this content provider has been published...
Dianne Hackborn860755f2010-06-03 18:47:52 -07005494 cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 if (cpr != null) {
5496 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005497 String msg;
5498 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5499 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005500 }
5501
5502 if (r != null && cpr.canRunHere(r)) {
5503 // This provider has been published or is in the process
5504 // of being published... but it is also allowed to run
5505 // in the caller's process, so don't make a connection
5506 // and just let the caller instantiate its own instance.
5507 if (cpr.provider != null) {
5508 // don't give caller the provider object, it needs
5509 // to make its own.
5510 cpr = new ContentProviderRecord(cpr);
5511 }
5512 return cpr;
5513 }
5514
5515 final long origId = Binder.clearCallingIdentity();
5516
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005517 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 // return it right away.
5519 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005520 if (DEBUG_PROVIDER) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005521 "Adding provider requested by "
5522 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005523 + cpr.info.processName);
5524 Integer cnt = r.conProviders.get(cpr);
5525 if (cnt == null) {
5526 r.conProviders.put(cpr, new Integer(1));
5527 } else {
5528 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 cpr.clients.add(r);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005531 if (cpr.app != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005532 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005533 // make sure to count it as being accessed and thus
5534 // back up on the LRU list. This is good because
5535 // content providers are often expensive to start.
5536 updateLruProcessLocked(cpr.app, false, true);
5537 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07005538 } else {
5539 cpr.externals++;
5540 }
5541
5542 if (cpr.app != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 updateOomAdjLocked(cpr.app);
5544 }
5545
5546 Binder.restoreCallingIdentity(origId);
5547
5548 } else {
5549 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005550 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07005551 resolveContentProvider(name,
5552 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 } catch (RemoteException ex) {
5554 }
5555 if (cpi == null) {
5556 return null;
5557 }
5558
Dianne Hackbornb424b632010-08-18 15:59:05 -07005559 String msg;
5560 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5561 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005562 }
5563
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07005564 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005565 && !cpi.processName.equals("system")) {
5566 // If this content provider does not run in the system
5567 // process, and the system is not yet ready to run other
5568 // processes, then fail fast instead of hanging.
5569 throw new IllegalArgumentException(
5570 "Attempt to launch content provider before system ready");
5571 }
5572
Dianne Hackborn860755f2010-06-03 18:47:52 -07005573 cpr = mProvidersByClass.get(cpi.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 final boolean firstClass = cpr == null;
5575 if (firstClass) {
5576 try {
5577 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005578 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 getApplicationInfo(
5580 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005581 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005583 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005584 + cpi.name);
5585 return null;
5586 }
5587 cpr = new ContentProviderRecord(cpi, ai);
5588 } catch (RemoteException ex) {
5589 // pm is in same process, this will never happen.
5590 }
5591 }
5592
5593 if (r != null && cpr.canRunHere(r)) {
5594 // If this is a multiprocess provider, then just return its
5595 // info and allow the caller to instantiate it. Only do
5596 // this if the provider is the same user as the caller's
5597 // process, or can run as root (so can be in any process).
5598 return cpr;
5599 }
5600
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005601 if (DEBUG_PROVIDER) {
5602 RuntimeException e = new RuntimeException("here");
Joe Onorato8a9b2202010-02-26 18:56:32 -08005603 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.info.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005604 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005605 }
5606
5607 // This is single process, and our app is now connecting to it.
5608 // See if we are already in the process of launching this
5609 // provider.
5610 final int N = mLaunchingProviders.size();
5611 int i;
5612 for (i=0; i<N; i++) {
5613 if (mLaunchingProviders.get(i) == cpr) {
5614 break;
5615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 }
5617
5618 // If the provider is not already being launched, then get it
5619 // started.
5620 if (i >= N) {
5621 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08005622
5623 try {
5624 // Content provider is now in use, its package can't be stopped.
5625 try {
5626 AppGlobals.getPackageManager().setPackageStoppedState(
5627 cpr.appInfo.packageName, false);
5628 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08005629 } catch (IllegalArgumentException e) {
5630 Slog.w(TAG, "Failed trying to unstop package "
5631 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08005632 }
5633
5634 ProcessRecord proc = startProcessLocked(cpi.processName,
5635 cpr.appInfo, false, 0, "content provider",
5636 new ComponentName(cpi.applicationInfo.packageName,
5637 cpi.name), false);
5638 if (proc == null) {
5639 Slog.w(TAG, "Unable to launch app "
5640 + cpi.applicationInfo.packageName + "/"
5641 + cpi.applicationInfo.uid + " for provider "
5642 + name + ": process is bad");
5643 return null;
5644 }
5645 cpr.launchingApp = proc;
5646 mLaunchingProviders.add(cpr);
5647 } finally {
5648 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 }
5651
5652 // Make sure the provider is published (the same provider class
5653 // may be published under multiple names).
5654 if (firstClass) {
5655 mProvidersByClass.put(cpi.name, cpr);
5656 }
5657 mProvidersByName.put(name, cpr);
5658
5659 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005660 if (DEBUG_PROVIDER) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005661 "Adding provider requested by "
5662 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005663 + cpr.info.processName);
5664 Integer cnt = r.conProviders.get(cpr);
5665 if (cnt == null) {
5666 r.conProviders.put(cpr, new Integer(1));
5667 } else {
5668 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 cpr.clients.add(r);
5671 } else {
5672 cpr.externals++;
5673 }
5674 }
5675 }
5676
5677 // Wait for the provider to be published...
5678 synchronized (cpr) {
5679 while (cpr.provider == null) {
5680 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005681 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 + cpi.applicationInfo.packageName + "/"
5683 + cpi.applicationInfo.uid + " for provider "
5684 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08005685 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005686 cpi.applicationInfo.packageName,
5687 cpi.applicationInfo.uid, name);
5688 return null;
5689 }
5690 try {
5691 cpr.wait();
5692 } catch (InterruptedException ex) {
5693 }
5694 }
5695 }
5696 return cpr;
5697 }
5698
5699 public final ContentProviderHolder getContentProvider(
5700 IApplicationThread caller, String name) {
5701 if (caller == null) {
5702 String msg = "null IApplicationThread when getting content provider "
5703 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005704 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 throw new SecurityException(msg);
5706 }
5707
5708 return getContentProviderImpl(caller, name);
5709 }
5710
5711 private ContentProviderHolder getContentProviderExternal(String name) {
5712 return getContentProviderImpl(null, name);
5713 }
5714
5715 /**
5716 * Drop a content provider from a ProcessRecord's bookkeeping
5717 * @param cpr
5718 */
5719 public void removeContentProvider(IApplicationThread caller, String name) {
5720 synchronized (this) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005721 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005723 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08005724 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005725 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 return;
5727 }
5728 final ProcessRecord r = getRecordForAppLocked(caller);
5729 if (r == null) {
5730 throw new SecurityException(
5731 "Unable to find app for caller " + caller +
5732 " when removing content provider " + name);
5733 }
5734 //update content provider record entry info
Dianne Hackborn860755f2010-06-03 18:47:52 -07005735 ContentProviderRecord localCpr = mProvidersByClass.get(cpr.info.name);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005736 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005737 + r.info.processName + " from process "
5738 + localCpr.appInfo.processName);
5739 if (localCpr.app == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08005741 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005742 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 return;
5744 } else {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005745 Integer cnt = r.conProviders.get(localCpr);
5746 if (cnt == null || cnt.intValue() <= 1) {
5747 localCpr.clients.remove(r);
5748 r.conProviders.remove(localCpr);
5749 } else {
5750 r.conProviders.put(localCpr, new Integer(cnt.intValue()-1));
5751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 }
5753 updateOomAdjLocked();
5754 }
5755 }
5756
5757 private void removeContentProviderExternal(String name) {
5758 synchronized (this) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005759 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 if(cpr == null) {
5761 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08005762 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 return;
5764 }
5765
5766 //update content provider record entry info
Dianne Hackborn860755f2010-06-03 18:47:52 -07005767 ContentProviderRecord localCpr = mProvidersByClass.get(cpr.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 localCpr.externals--;
5769 if (localCpr.externals < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005770 Slog.e(TAG, "Externals < 0 for content provider " + localCpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005771 }
5772 updateOomAdjLocked();
5773 }
5774 }
5775
5776 public final void publishContentProviders(IApplicationThread caller,
5777 List<ContentProviderHolder> providers) {
5778 if (providers == null) {
5779 return;
5780 }
5781
5782 synchronized(this) {
5783 final ProcessRecord r = getRecordForAppLocked(caller);
5784 if (r == null) {
5785 throw new SecurityException(
5786 "Unable to find app for caller " + caller
5787 + " (pid=" + Binder.getCallingPid()
5788 + ") when publishing content providers");
5789 }
5790
5791 final long origId = Binder.clearCallingIdentity();
5792
5793 final int N = providers.size();
5794 for (int i=0; i<N; i++) {
5795 ContentProviderHolder src = providers.get(i);
5796 if (src == null || src.info == null || src.provider == null) {
5797 continue;
5798 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005799 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 if (dst != null) {
5801 mProvidersByClass.put(dst.info.name, dst);
5802 String names[] = dst.info.authority.split(";");
5803 for (int j = 0; j < names.length; j++) {
5804 mProvidersByName.put(names[j], dst);
5805 }
5806
5807 int NL = mLaunchingProviders.size();
5808 int j;
5809 for (j=0; j<NL; j++) {
5810 if (mLaunchingProviders.get(j) == dst) {
5811 mLaunchingProviders.remove(j);
5812 j--;
5813 NL--;
5814 }
5815 }
5816 synchronized (dst) {
5817 dst.provider = src.provider;
5818 dst.app = r;
5819 dst.notifyAll();
5820 }
5821 updateOomAdjLocked(r);
5822 }
5823 }
5824
5825 Binder.restoreCallingIdentity(origId);
5826 }
5827 }
5828
5829 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07005830 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06005831 synchronized (mSelf) {
5832 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
5833 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08005834 if (providers != null) {
5835 for (int i=providers.size()-1; i>=0; i--) {
5836 ProviderInfo pi = (ProviderInfo)providers.get(i);
5837 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5838 Slog.w(TAG, "Not installing system proc provider " + pi.name
5839 + ": not system .apk");
5840 providers.remove(i);
5841 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005842 }
5843 }
5844 }
Josh Bartel2ecce342010-02-25 10:55:48 -06005845 if (providers != null) {
5846 mSystemThread.installSystemProviders(providers);
5847 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08005848
5849 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005850 }
5851
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07005852 /**
5853 * Allows app to retrieve the MIME type of a URI without having permission
5854 * to access its content provider.
5855 *
5856 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
5857 *
5858 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
5859 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
5860 */
5861 public String getProviderMimeType(Uri uri) {
5862 final String name = uri.getAuthority();
5863 final long ident = Binder.clearCallingIdentity();
5864 ContentProviderHolder holder = null;
5865
5866 try {
5867 holder = getContentProviderExternal(name);
5868 if (holder != null) {
5869 return holder.provider.getType(uri);
5870 }
5871 } catch (RemoteException e) {
5872 Log.w(TAG, "Content provider dead retrieving " + uri, e);
5873 return null;
5874 } finally {
5875 if (holder != null) {
5876 removeContentProviderExternal(name);
5877 }
5878 Binder.restoreCallingIdentity(ident);
5879 }
5880
5881 return null;
5882 }
5883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005884 // =========================================================
5885 // GLOBAL MANAGEMENT
5886 // =========================================================
5887
5888 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
5889 ApplicationInfo info, String customProcess) {
5890 String proc = customProcess != null ? customProcess : info.processName;
5891 BatteryStatsImpl.Uid.Proc ps = null;
5892 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
5893 synchronized (stats) {
5894 ps = stats.getProcessStatsLocked(info.uid, proc);
5895 }
5896 return new ProcessRecord(ps, thread, info, proc);
5897 }
5898
5899 final ProcessRecord addAppLocked(ApplicationInfo info) {
5900 ProcessRecord app = getProcessRecordLocked(info.processName, info.uid);
5901
5902 if (app == null) {
5903 app = newProcessRecordLocked(null, info, null);
5904 mProcessNames.put(info.processName, info.uid, app);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08005905 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906 }
5907
Dianne Hackborne7f97212011-02-24 14:40:20 -08005908 // This package really, really can not be stopped.
5909 try {
5910 AppGlobals.getPackageManager().setPackageStoppedState(
5911 info.packageName, false);
5912 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08005913 } catch (IllegalArgumentException e) {
5914 Slog.w(TAG, "Failed trying to unstop package "
5915 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08005916 }
5917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005918 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
5919 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
5920 app.persistent = true;
Dianne Hackborn7d608422011-08-07 16:24:18 -07005921 app.maxAdj = ProcessList.CORE_SERVER_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005922 }
5923 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
5924 mPersistentStartingProcesses.add(app);
5925 startProcessLocked(app, "added application", app.processName);
5926 }
5927
5928 return app;
5929 }
5930
5931 public void unhandledBack() {
5932 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
5933 "unhandledBack()");
5934
5935 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005936 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08005937 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005938 TAG, "Performing unhandledBack(): stack size = " + count);
5939 if (count > 1) {
5940 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005941 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
5943 Binder.restoreCallingIdentity(origId);
5944 }
5945 }
5946 }
5947
5948 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
5949 String name = uri.getAuthority();
5950 ContentProviderHolder cph = getContentProviderExternal(name);
5951 ParcelFileDescriptor pfd = null;
5952 if (cph != null) {
5953 // We record the binder invoker's uid in thread-local storage before
5954 // going to the content provider to open the file. Later, in the code
5955 // that handles all permissions checks, we look for this uid and use
5956 // that rather than the Activity Manager's own uid. The effect is that
5957 // we do the check against the caller's permissions even though it looks
5958 // to the content provider like the Activity Manager itself is making
5959 // the request.
5960 sCallerIdentity.set(new Identity(
5961 Binder.getCallingPid(), Binder.getCallingUid()));
5962 try {
5963 pfd = cph.provider.openFile(uri, "r");
5964 } catch (FileNotFoundException e) {
5965 // do nothing; pfd will be returned null
5966 } finally {
5967 // Ensure that whatever happens, we clean up the identity state
5968 sCallerIdentity.remove();
5969 }
5970
5971 // We've got the fd now, so we're done with the provider.
5972 removeContentProviderExternal(name);
5973 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005974 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 }
5976 return pfd;
5977 }
5978
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08005979 // Actually is sleeping or shutting down or whatever else in the future
5980 // is an inactive state.
5981 public boolean isSleeping() {
5982 return mSleeping || mShuttingDown;
5983 }
5984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 public void goingToSleep() {
5986 synchronized(this) {
5987 mSleeping = true;
5988 mWindowManager.setEventDispatching(false);
5989
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08005990 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005991
5992 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07005993 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005994 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
5995 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07005996 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 }
5998 }
5999
Dianne Hackborn55280a92009-05-07 15:53:46 -07006000 public boolean shutdown(int timeout) {
6001 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6002 != PackageManager.PERMISSION_GRANTED) {
6003 throw new SecurityException("Requires permission "
6004 + android.Manifest.permission.SHUTDOWN);
6005 }
6006
6007 boolean timedout = false;
6008
6009 synchronized(this) {
6010 mShuttingDown = true;
6011 mWindowManager.setEventDispatching(false);
6012
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006013 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006014 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006015 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006016 while (mMainStack.mResumedActivity != null
6017 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006018 long delay = endTime - System.currentTimeMillis();
6019 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006020 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006021 timedout = true;
6022 break;
6023 }
6024 try {
6025 this.wait();
6026 } catch (InterruptedException e) {
6027 }
6028 }
6029 }
6030 }
6031
6032 mUsageStatsService.shutdown();
6033 mBatteryStatsService.shutdown();
6034
6035 return timedout;
6036 }
6037
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006038 public final void activitySlept(IBinder token) {
6039 if (localLOGV) Slog.v(
6040 TAG, "Activity slept: token=" + token);
6041
6042 ActivityRecord r = null;
6043
6044 final long origId = Binder.clearCallingIdentity();
6045
6046 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006047 r = mMainStack.isInStackLocked(token);
6048 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006049 mMainStack.activitySleptLocked(r);
6050 }
6051 }
6052
6053 Binder.restoreCallingIdentity(origId);
6054 }
6055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 public void wakingUp() {
6057 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058 mWindowManager.setEventDispatching(true);
6059 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006060 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006061 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006062 }
6063 }
6064
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006065 public void stopAppSwitches() {
6066 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6067 != PackageManager.PERMISSION_GRANTED) {
6068 throw new SecurityException("Requires permission "
6069 + android.Manifest.permission.STOP_APP_SWITCHES);
6070 }
6071
6072 synchronized(this) {
6073 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6074 + APP_SWITCH_DELAY_TIME;
6075 mDidAppSwitch = false;
6076 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6077 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6078 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6079 }
6080 }
6081
6082 public void resumeAppSwitches() {
6083 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6084 != PackageManager.PERMISSION_GRANTED) {
6085 throw new SecurityException("Requires permission "
6086 + android.Manifest.permission.STOP_APP_SWITCHES);
6087 }
6088
6089 synchronized(this) {
6090 // Note that we don't execute any pending app switches... we will
6091 // let those wait until either the timeout, or the next start
6092 // activity request.
6093 mAppSwitchesAllowedTime = 0;
6094 }
6095 }
6096
6097 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6098 String name) {
6099 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6100 return true;
6101 }
6102
6103 final int perm = checkComponentPermission(
6104 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006105 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006106 if (perm == PackageManager.PERMISSION_GRANTED) {
6107 return true;
6108 }
6109
Joe Onorato8a9b2202010-02-26 18:56:32 -08006110 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006111 return false;
6112 }
6113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 public void setDebugApp(String packageName, boolean waitForDebugger,
6115 boolean persistent) {
6116 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6117 "setDebugApp()");
6118
6119 // Note that this is not really thread safe if there are multiple
6120 // callers into it at the same time, but that's not a situation we
6121 // care about.
6122 if (persistent) {
6123 final ContentResolver resolver = mContext.getContentResolver();
6124 Settings.System.putString(
6125 resolver, Settings.System.DEBUG_APP,
6126 packageName);
6127 Settings.System.putInt(
6128 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6129 waitForDebugger ? 1 : 0);
6130 }
6131
6132 synchronized (this) {
6133 if (!persistent) {
6134 mOrigDebugApp = mDebugApp;
6135 mOrigWaitForDebugger = mWaitForDebugger;
6136 }
6137 mDebugApp = packageName;
6138 mWaitForDebugger = waitForDebugger;
6139 mDebugTransient = !persistent;
6140 if (packageName != null) {
6141 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006142 forceStopPackageLocked(packageName, -1, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 Binder.restoreCallingIdentity(origId);
6144 }
6145 }
6146 }
6147
6148 public void setAlwaysFinish(boolean enabled) {
6149 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6150 "setAlwaysFinish()");
6151
6152 Settings.System.putInt(
6153 mContext.getContentResolver(),
6154 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6155
6156 synchronized (this) {
6157 mAlwaysFinishActivities = enabled;
6158 }
6159 }
6160
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006161 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006163 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006165 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 }
6167 }
6168
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006169 public boolean isUserAMonkey() {
6170 // For now the fact that there is a controller implies
6171 // we have a monkey.
6172 synchronized (this) {
6173 return mController != null;
6174 }
6175 }
6176
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006177 public void registerActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06006178 synchronized (this) {
6179 mWatchers.register(watcher);
6180 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006181 }
6182
6183 public void unregisterActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06006184 synchronized (this) {
6185 mWatchers.unregister(watcher);
6186 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006187 }
6188
Jeff Sharkeya4620792011-05-20 15:29:23 -07006189 public void registerProcessObserver(IProcessObserver observer) {
6190 mProcessObservers.register(observer);
6191 }
6192
6193 public void unregisterProcessObserver(IProcessObserver observer) {
6194 mProcessObservers.unregister(observer);
6195 }
6196
Daniel Sandler69a48172010-06-23 16:29:36 -04006197 public void setImmersive(IBinder token, boolean immersive) {
6198 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006199 ActivityRecord r = mMainStack.isInStackLocked(token);
6200 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006201 throw new IllegalArgumentException();
6202 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006203 r.immersive = immersive;
6204 }
6205 }
6206
6207 public boolean isImmersive(IBinder token) {
6208 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006209 ActivityRecord r = mMainStack.isInStackLocked(token);
6210 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006211 throw new IllegalArgumentException();
6212 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006213 return r.immersive;
6214 }
6215 }
6216
6217 public boolean isTopActivityImmersive() {
6218 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006219 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006220 return (r != null) ? r.immersive : false;
6221 }
6222 }
6223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 public final void enterSafeMode() {
6225 synchronized(this) {
6226 // It only makes sense to do this before the system is ready
6227 // and started launching other packages.
6228 if (!mSystemReady) {
6229 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006230 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 } catch (RemoteException e) {
6232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 }
6234 }
6235 }
6236
Jeff Brownb09abc12011-01-13 21:08:27 -08006237 public final void showSafeModeOverlay() {
6238 View v = LayoutInflater.from(mContext).inflate(
6239 com.android.internal.R.layout.safe_mode, null);
6240 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6241 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6242 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6243 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6244 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6245 lp.format = v.getBackground().getOpacity();
6246 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6247 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6248 ((WindowManager)mContext.getSystemService(
6249 Context.WINDOW_SERVICE)).addView(v, lp);
6250 }
6251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 public void noteWakeupAlarm(IIntentSender sender) {
6253 if (!(sender instanceof PendingIntentRecord)) {
6254 return;
6255 }
6256 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6257 synchronized (stats) {
6258 if (mBatteryStatsService.isOnBattery()) {
6259 mBatteryStatsService.enforceCallingPermission();
6260 PendingIntentRecord rec = (PendingIntentRecord)sender;
6261 int MY_UID = Binder.getCallingUid();
6262 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6263 BatteryStatsImpl.Uid.Pkg pkg =
6264 stats.getPackageStatsLocked(uid, rec.key.packageName);
6265 pkg.incWakeupsLocked();
6266 }
6267 }
6268 }
6269
Dianne Hackborn64825172011-03-02 21:32:58 -08006270 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006272 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006274 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 // XXX Note: don't acquire main activity lock here, because the window
6276 // manager calls in with its locks held.
6277
6278 boolean killed = false;
6279 synchronized (mPidsSelfLocked) {
6280 int[] types = new int[pids.length];
6281 int worstType = 0;
6282 for (int i=0; i<pids.length; i++) {
6283 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6284 if (proc != null) {
6285 int type = proc.setAdj;
6286 types[i] = type;
6287 if (type > worstType) {
6288 worstType = type;
6289 }
6290 }
6291 }
6292
Dianne Hackborn64825172011-03-02 21:32:58 -08006293 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 // then constrain it so we will kill all hidden procs.
Dianne Hackborn7d608422011-08-07 16:24:18 -07006295 if (worstType < ProcessList.EMPTY_APP_ADJ && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
6296 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006298
6299 // If this is not a secure call, don't let it kill processes that
6300 // are important.
Dianne Hackborn7d608422011-08-07 16:24:18 -07006301 if (!secure && worstType < ProcessList.SECONDARY_SERVER_ADJ) {
6302 worstType = ProcessList.SECONDARY_SERVER_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006303 }
6304
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006305 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 for (int i=0; i<pids.length; i++) {
6307 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6308 if (proc == null) {
6309 continue;
6310 }
6311 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006312 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006313 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006314 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6315 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006317 proc.killedBackground = true;
6318 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 }
6320 }
6321 }
6322 return killed;
6323 }
6324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 public final void startRunning(String pkg, String cls, String action,
6326 String data) {
6327 synchronized(this) {
6328 if (mStartRunning) {
6329 return;
6330 }
6331 mStartRunning = true;
6332 mTopComponent = pkg != null && cls != null
6333 ? new ComponentName(pkg, cls) : null;
6334 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6335 mTopData = data;
6336 if (!mSystemReady) {
6337 return;
6338 }
6339 }
6340
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006341 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 }
6343
6344 private void retrieveSettings() {
6345 final ContentResolver resolver = mContext.getContentResolver();
6346 String debugApp = Settings.System.getString(
6347 resolver, Settings.System.DEBUG_APP);
6348 boolean waitForDebugger = Settings.System.getInt(
6349 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6350 boolean alwaysFinishActivities = Settings.System.getInt(
6351 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6352
6353 Configuration configuration = new Configuration();
6354 Settings.System.getConfiguration(resolver, configuration);
6355
6356 synchronized (this) {
6357 mDebugApp = mOrigDebugApp = debugApp;
6358 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6359 mAlwaysFinishActivities = alwaysFinishActivities;
6360 // This happens before any activities are started, so we can
6361 // change mConfiguration in-place.
6362 mConfiguration.updateFrom(configuration);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006363 mConfigurationSeq = mConfiguration.seq = 1;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006364 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 }
6366 }
6367
6368 public boolean testIsSystemReady() {
6369 // no need to synchronize(this) just to read & return the value
6370 return mSystemReady;
6371 }
6372
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006373 private static File getCalledPreBootReceiversFile() {
6374 File dataDir = Environment.getDataDirectory();
6375 File systemDir = new File(dataDir, "system");
6376 File fname = new File(systemDir, "called_pre_boots.dat");
6377 return fname;
6378 }
6379
6380 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6381 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6382 File file = getCalledPreBootReceiversFile();
6383 FileInputStream fis = null;
6384 try {
6385 fis = new FileInputStream(file);
6386 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
6387 int vers = dis.readInt();
6388 String codename = dis.readUTF();
6389 if (vers == android.os.Build.VERSION.SDK_INT
6390 && codename.equals(android.os.Build.VERSION.CODENAME)) {
6391 int num = dis.readInt();
6392 while (num > 0) {
6393 num--;
6394 String pkg = dis.readUTF();
6395 String cls = dis.readUTF();
6396 lastDoneReceivers.add(new ComponentName(pkg, cls));
6397 }
6398 }
6399 } catch (FileNotFoundException e) {
6400 } catch (IOException e) {
6401 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6402 } finally {
6403 if (fis != null) {
6404 try {
6405 fis.close();
6406 } catch (IOException e) {
6407 }
6408 }
6409 }
6410 return lastDoneReceivers;
6411 }
6412
6413 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
6414 File file = getCalledPreBootReceiversFile();
6415 FileOutputStream fos = null;
6416 DataOutputStream dos = null;
6417 try {
6418 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
6419 fos = new FileOutputStream(file);
6420 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
6421 dos.writeInt(android.os.Build.VERSION.SDK_INT);
6422 dos.writeUTF(android.os.Build.VERSION.CODENAME);
6423 dos.writeInt(list.size());
6424 for (int i=0; i<list.size(); i++) {
6425 dos.writeUTF(list.get(i).getPackageName());
6426 dos.writeUTF(list.get(i).getClassName());
6427 }
6428 } catch (IOException e) {
6429 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
6430 file.delete();
6431 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006432 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006433 if (dos != null) {
6434 try {
6435 dos.close();
6436 } catch (IOException e) {
6437 // TODO Auto-generated catch block
6438 e.printStackTrace();
6439 }
6440 }
6441 }
6442 }
6443
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006444 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 synchronized(this) {
6446 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006447 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 return;
6449 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006450
6451 // Check to see if there are any update receivers to run.
6452 if (!mDidUpdate) {
6453 if (mWaitingUpdate) {
6454 return;
6455 }
6456 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6457 List<ResolveInfo> ris = null;
6458 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006459 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006460 intent, null, 0);
6461 } catch (RemoteException e) {
6462 }
6463 if (ris != null) {
6464 for (int i=ris.size()-1; i>=0; i--) {
6465 if ((ris.get(i).activityInfo.applicationInfo.flags
6466 &ApplicationInfo.FLAG_SYSTEM) == 0) {
6467 ris.remove(i);
6468 }
6469 }
6470 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006471
6472 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
6473
6474 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006475 for (int i=0; i<ris.size(); i++) {
6476 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006477 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6478 if (lastDoneReceivers.contains(comp)) {
6479 ris.remove(i);
6480 i--;
6481 }
6482 }
6483
6484 for (int i=0; i<ris.size(); i++) {
6485 ActivityInfo ai = ris.get(i).activityInfo;
6486 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6487 doneReceivers.add(comp);
6488 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006489 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08006490 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006491 finisher = new IIntentReceiver.Stub() {
6492 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07006493 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006494 boolean sticky) {
6495 // The raw IIntentReceiver interface is called
6496 // with the AM lock held, so redispatch to
6497 // execute our code without the lock.
6498 mHandler.post(new Runnable() {
6499 public void run() {
6500 synchronized (ActivityManagerService.this) {
6501 mDidUpdate = true;
6502 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006503 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006504 systemReady(goingCallback);
6505 }
6506 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006507 }
6508 };
6509 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006510 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006511 broadcastIntentLocked(null, null, intent, null, finisher,
6512 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackbornd6847842010-01-12 18:14:19 -08006513 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006514 mWaitingUpdate = true;
6515 }
6516 }
6517 }
6518 if (mWaitingUpdate) {
6519 return;
6520 }
6521 mDidUpdate = true;
6522 }
6523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 mSystemReady = true;
6525 if (!mStartRunning) {
6526 return;
6527 }
6528 }
6529
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006530 ArrayList<ProcessRecord> procsToKill = null;
6531 synchronized(mPidsSelfLocked) {
6532 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
6533 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
6534 if (!isAllowedWhileBooting(proc.info)){
6535 if (procsToKill == null) {
6536 procsToKill = new ArrayList<ProcessRecord>();
6537 }
6538 procsToKill.add(proc);
6539 }
6540 }
6541 }
6542
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006543 synchronized(this) {
6544 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006545 for (int i=procsToKill.size()-1; i>=0; i--) {
6546 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006547 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07006548 removeProcessLocked(proc, true, false);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006549 }
6550 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006551
6552 // Now that we have cleaned up any update processes, we
6553 // are ready to start launching real processes and know that
6554 // we won't trample on them any more.
6555 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006556 }
6557
Joe Onorato8a9b2202010-02-26 18:56:32 -08006558 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006559 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 SystemClock.uptimeMillis());
6561
6562 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006563 // Make sure we have no pre-ready processes sitting around.
6564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006565 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
6566 ResolveInfo ri = mContext.getPackageManager()
6567 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07006568 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006569 CharSequence errorMsg = null;
6570 if (ri != null) {
6571 ActivityInfo ai = ri.activityInfo;
6572 ApplicationInfo app = ai.applicationInfo;
6573 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6574 mTopAction = Intent.ACTION_FACTORY_TEST;
6575 mTopData = null;
6576 mTopComponent = new ComponentName(app.packageName,
6577 ai.name);
6578 } else {
6579 errorMsg = mContext.getResources().getText(
6580 com.android.internal.R.string.factorytest_not_system);
6581 }
6582 } else {
6583 errorMsg = mContext.getResources().getText(
6584 com.android.internal.R.string.factorytest_no_action);
6585 }
6586 if (errorMsg != null) {
6587 mTopAction = null;
6588 mTopData = null;
6589 mTopComponent = null;
6590 Message msg = Message.obtain();
6591 msg.what = SHOW_FACTORY_ERROR_MSG;
6592 msg.getData().putCharSequence("msg", errorMsg);
6593 mHandler.sendMessage(msg);
6594 }
6595 }
6596 }
6597
6598 retrieveSettings();
6599
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006600 if (goingCallback != null) goingCallback.run();
6601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 synchronized (this) {
6603 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
6604 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006605 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006606 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 if (apps != null) {
6608 int N = apps.size();
6609 int i;
6610 for (i=0; i<N; i++) {
6611 ApplicationInfo info
6612 = (ApplicationInfo)apps.get(i);
6613 if (info != null &&
6614 !info.packageName.equals("android")) {
6615 addAppLocked(info);
6616 }
6617 }
6618 }
6619 } catch (RemoteException ex) {
6620 // pm is in same process, this will never happen.
6621 }
6622 }
6623
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006624 // Start up initial activity.
6625 mBooting = true;
6626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006628 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 Message msg = Message.obtain();
6630 msg.what = SHOW_UID_ERROR_MSG;
6631 mHandler.sendMessage(msg);
6632 }
6633 } catch (RemoteException e) {
6634 }
6635
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006636 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 }
6638 }
6639
Dan Egnorb7f03672009-12-09 16:22:32 -08006640 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006641 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08006643 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08006644 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 startAppProblemLocked(app);
6646 app.stopFreezingAllLocked();
6647 return handleAppCrashLocked(app);
6648 }
6649
Dan Egnorb7f03672009-12-09 16:22:32 -08006650 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006651 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006652 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08006653 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08006654 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
6655 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006656 startAppProblemLocked(app);
6657 app.stopFreezingAllLocked();
6658 }
6659
6660 /**
6661 * Generate a process error record, suitable for attachment to a ProcessRecord.
6662 *
6663 * @param app The ProcessRecord in which the error occurred.
6664 * @param condition Crashing, Application Not Responding, etc. Values are defined in
6665 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08006666 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 * @param shortMsg Short message describing the crash.
6668 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08006669 * @param stackTrace Full crash stack trace, may be null.
6670 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 * @return Returns a fully-formed AppErrorStateInfo record.
6672 */
6673 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006674 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08006676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 report.condition = condition;
6678 report.processName = app.processName;
6679 report.pid = app.pid;
6680 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08006681 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006682 report.shortMsg = shortMsg;
6683 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08006684 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685
6686 return report;
6687 }
6688
Dan Egnor42471dd2010-01-07 17:25:22 -08006689 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 synchronized (this) {
6691 app.crashing = false;
6692 app.crashingReport = null;
6693 app.notResponding = false;
6694 app.notRespondingReport = null;
6695 if (app.anrDialog == fromDialog) {
6696 app.anrDialog = null;
6697 }
6698 if (app.waitDialog == fromDialog) {
6699 app.waitDialog = null;
6700 }
6701 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08006702 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006703 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07006704 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
6705 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006706 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 }
6709 }
Dan Egnor42471dd2010-01-07 17:25:22 -08006710
Dan Egnorb7f03672009-12-09 16:22:32 -08006711 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 long now = SystemClock.uptimeMillis();
6713
6714 Long crashTime = mProcessCrashTimes.get(app.info.processName,
6715 app.info.uid);
Dianne Hackborn7d608422011-08-07 16:24:18 -07006716 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08006718 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006720 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 app.info.processName, app.info.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006722 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6723 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006725 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006727 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 }
6729 }
6730 if (!app.persistent) {
6731 // We don't want to start this process again until the user
6732 // explicitly does so... but for persistent process, we really
6733 // need to keep it running. If a persistent process is actually
6734 // repeatedly crashing, then badness for everyone.
Doug Zongker2bec3d42009-12-04 12:52:44 -08006735 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 app.info.processName);
6737 mBadProcesses.put(app.info.processName, app.info.uid, now);
6738 app.bad = true;
6739 mProcessCrashTimes.remove(app.info.processName, app.info.uid);
6740 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07006741 // Don't let services in this process be restarted and potentially
6742 // annoy the user repeatedly. Unless it is persistent, since those
6743 // processes run critical code.
6744 removeProcessLocked(app, false, false);
Dianne Hackborncb44d962011-03-10 17:02:27 -08006745 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 return false;
6747 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08006748 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006749 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006750 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006751 if (r.app == app) {
6752 // If the top running activity is from this crashing
6753 // process, then terminate it to avoid getting in a loop.
6754 Slog.w(TAG, " Force finishing activity "
6755 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006756 int index = mMainStack.indexOfTokenLocked(r);
6757 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006758 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08006759 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006760 // stopped, to avoid a situation where one will get
6761 // re-start our crashing activity once it gets resumed again.
6762 index--;
6763 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006764 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006765 if (r.state == ActivityState.RESUMED
6766 || r.state == ActivityState.PAUSING
6767 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08006768 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006769 Slog.w(TAG, " Force finishing activity "
6770 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006771 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006772 Activity.RESULT_CANCELED, null, "crashed");
6773 }
6774 }
6775 }
6776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777 }
6778
6779 // Bump up the crash count of any services currently running in the proc.
6780 if (app.services.size() != 0) {
6781 // Any services running in the application need to be placed
6782 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07006783 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006784 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07006785 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006786 sr.crashCount++;
6787 }
6788 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02006789
6790 // If the crashing process is what we consider to be the "home process" and it has been
6791 // replaced by a third-party app, clear the package preferred activities from packages
6792 // with a home activity running in the process to prevent a repeatedly crashing app
6793 // from blocking the user to manually clear the list.
6794 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
6795 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
6796 Iterator it = mHomeProcess.activities.iterator();
6797 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07006798 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02006799 if (r.isHomeActivity) {
6800 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
6801 try {
6802 ActivityThread.getPackageManager()
6803 .clearPackagePreferredActivities(r.packageName);
6804 } catch (RemoteException c) {
6805 // pm is in same process, this will never happen.
6806 }
6807 }
6808 }
6809 }
6810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 mProcessCrashTimes.put(app.info.processName, app.info.uid, now);
6812 return true;
6813 }
6814
6815 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006816 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
6817 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 skipCurrentReceiverLocked(app);
6819 }
6820
6821 void skipCurrentReceiverLocked(ProcessRecord app) {
6822 boolean reschedule = false;
6823 BroadcastRecord r = app.curReceiver;
6824 if (r != null) {
6825 // The current broadcast is waiting for this app's receiver
6826 // to be finished. Looks like that's not going to happen, so
6827 // let the broadcast continue.
Jeff Brown4d94a762010-09-23 11:33:28 -07006828 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006829 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
6830 r.resultExtras, r.resultAbort, true);
6831 reschedule = true;
6832 }
6833 r = mPendingBroadcast;
6834 if (r != null && r.curApp == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006835 if (DEBUG_BROADCAST) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 "skip & discard pending app " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -07006837 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
6839 r.resultExtras, r.resultAbort, true);
6840 reschedule = true;
6841 }
6842 if (reschedule) {
6843 scheduleBroadcastsLocked();
6844 }
6845 }
6846
Dan Egnor60d87622009-12-16 16:32:58 -08006847 /**
6848 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
6849 * The application process will exit immediately after this call returns.
6850 * @param app object of the crashing app, null for the system server
6851 * @param crashInfo describing the exception
6852 */
6853 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08006854 ProcessRecord r = findAppProcess(app, "Crash");
Dan Egnor60d87622009-12-16 16:32:58 -08006855
6856 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
6857 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08006858 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08006859 crashInfo.exceptionClassName,
6860 crashInfo.exceptionMessage,
6861 crashInfo.throwFileName,
6862 crashInfo.throwLineNumber);
6863
Dan Egnor42471dd2010-01-07 17:25:22 -08006864 addErrorToDropBox("crash", r, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08006865
6866 crashApplication(r, crashInfo);
6867 }
6868
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006869 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006870 IBinder app,
6871 int violationMask,
6872 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08006873 ProcessRecord r = findAppProcess(app, "StrictMode");
6874 if (r == null) {
6875 return;
6876 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006877
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006878 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08006879 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006880 boolean logIt = true;
6881 synchronized (mAlreadyLoggedViolatedStacks) {
6882 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
6883 logIt = false;
6884 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006885 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006886 // the relative pain numbers, without logging all
6887 // the stack traces repeatedly. We'd want to do
6888 // likewise in the client code, which also does
6889 // dup suppression, before the Binder call.
6890 } else {
6891 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
6892 mAlreadyLoggedViolatedStacks.clear();
6893 }
6894 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
6895 }
6896 }
6897 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006898 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006899 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006900 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006901
6902 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
6903 AppErrorResult result = new AppErrorResult();
6904 synchronized (this) {
6905 final long origId = Binder.clearCallingIdentity();
6906
6907 Message msg = Message.obtain();
6908 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
6909 HashMap<String, Object> data = new HashMap<String, Object>();
6910 data.put("result", result);
6911 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006912 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006913 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006914 msg.obj = data;
6915 mHandler.sendMessage(msg);
6916
6917 Binder.restoreCallingIdentity(origId);
6918 }
6919 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07006920 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006921 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006922 }
6923
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006924 // Depending on the policy in effect, there could be a bunch of
6925 // these in quick succession so we try to batch these together to
6926 // minimize disk writes, number of dropbox entries, and maximize
6927 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006928 private void logStrictModeViolationToDropBox(
6929 ProcessRecord process,
6930 StrictMode.ViolationInfo info) {
6931 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006932 return;
6933 }
6934 final boolean isSystemApp = process == null ||
6935 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
6936 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
6937 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
6938 final DropBoxManager dbox = (DropBoxManager)
6939 mContext.getSystemService(Context.DROPBOX_SERVICE);
6940
6941 // Exit early if the dropbox isn't configured to accept this report type.
6942 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
6943
6944 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006945 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006946 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
6947 synchronized (sb) {
6948 bufferWasEmpty = sb.length() == 0;
6949 appendDropBoxProcessHeaders(process, sb);
6950 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
6951 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006952 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
6953 if (info.violationNumThisLoop != 0) {
6954 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
6955 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07006956 if (info.numAnimationsRunning != 0) {
6957 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
6958 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07006959 if (info.broadcastIntentAction != null) {
6960 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
6961 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08006962 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006963 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006964 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08006965 if (info.numInstances != -1) {
6966 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
6967 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08006968 if (info.tags != null) {
6969 for (String tag : info.tags) {
6970 sb.append("Span-Tag: ").append(tag).append("\n");
6971 }
6972 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006973 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006974 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
6975 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006976 }
6977 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006978
6979 // Only buffer up to ~64k. Various logging bits truncate
6980 // things at 128k.
6981 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006982 }
6983
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006984 // Flush immediately if the buffer's grown too large, or this
6985 // is a non-system app. Non-system apps are isolated with a
6986 // different tag & policy and not batched.
6987 //
6988 // Batching is useful during internal testing with
6989 // StrictMode settings turned up high. Without batching,
6990 // thousands of separate files could be created on boot.
6991 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006992 new Thread("Error dump: " + dropboxTag) {
6993 @Override
6994 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006995 String report;
6996 synchronized (sb) {
6997 report = sb.toString();
6998 sb.delete(0, sb.length());
6999 sb.trimToSize();
7000 }
7001 if (report.length() != 0) {
7002 dbox.addText(dropboxTag, report);
7003 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007004 }
7005 }.start();
7006 return;
7007 }
7008
7009 // System app batching:
7010 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007011 // An existing dropbox-writing thread is outstanding, so
7012 // we don't need to start it up. The existing thread will
7013 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007014 return;
7015 }
7016
7017 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7018 // (After this point, we shouldn't access AMS internal data structures.)
7019 new Thread("Error dump: " + dropboxTag) {
7020 @Override
7021 public void run() {
7022 // 5 second sleep to let stacks arrive and be batched together
7023 try {
7024 Thread.sleep(5000); // 5 seconds
7025 } catch (InterruptedException e) {}
7026
7027 String errorReport;
7028 synchronized (mStrictModeBuffer) {
7029 errorReport = mStrictModeBuffer.toString();
7030 if (errorReport.length() == 0) {
7031 return;
7032 }
7033 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7034 mStrictModeBuffer.trimToSize();
7035 }
7036 dbox.addText(dropboxTag, errorReport);
7037 }
7038 }.start();
7039 }
7040
Dan Egnor60d87622009-12-16 16:32:58 -08007041 /**
7042 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7043 * @param app object of the crashing app, null for the system server
7044 * @param tag reported by the caller
7045 * @param crashInfo describing the context of the error
7046 * @return true if the process should exit immediately (WTF is fatal)
7047 */
7048 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007049 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007050 ProcessRecord r = findAppProcess(app, "WTF");
Dan Egnor60d87622009-12-16 16:32:58 -08007051
7052 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
7053 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08007054 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007055 tag, crashInfo.exceptionMessage);
7056
Dan Egnor42471dd2010-01-07 17:25:22 -08007057 addErrorToDropBox("wtf", r, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007058
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007059 if (r != null && r.pid != Process.myPid() &&
7060 Settings.Secure.getInt(mContext.getContentResolver(),
7061 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007062 crashApplication(r, crashInfo);
7063 return true;
7064 } else {
7065 return false;
7066 }
7067 }
7068
7069 /**
7070 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7071 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7072 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007073 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007074 if (app == null) {
7075 return null;
7076 }
7077
7078 synchronized (this) {
7079 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7080 final int NA = apps.size();
7081 for (int ia=0; ia<NA; ia++) {
7082 ProcessRecord p = apps.valueAt(ia);
7083 if (p.thread != null && p.thread.asBinder() == app) {
7084 return p;
7085 }
7086 }
7087 }
7088
Dianne Hackborncb44d962011-03-10 17:02:27 -08007089 Slog.w(TAG, "Can't find mystery application for " + reason
7090 + " from pid=" + Binder.getCallingPid()
7091 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007092 return null;
7093 }
7094 }
7095
7096 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007097 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7098 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007099 */
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007100 private void appendDropBoxProcessHeaders(ProcessRecord process, StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007101 // Watchdog thread ends up invoking this function (with
7102 // a null ProcessRecord) to add the stack file to dropbox.
7103 // Do not acquire a lock on this (am) in such cases, as it
7104 // could cause a potential deadlock, if and when watchdog
7105 // is invoked due to unavailability of lock on am and it
7106 // would prevent watchdog from killing system_server.
7107 if (process == null) {
7108 sb.append("Process: system_server\n");
7109 return;
7110 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007111 // Note: ProcessRecord 'process' is guarded by the service
7112 // instance. (notably process.pkgList, which could otherwise change
7113 // concurrently during execution of this method)
7114 synchronized (this) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007115 if (process.pid == MY_PID) {
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007116 sb.append("Process: system_server\n");
7117 } else {
7118 sb.append("Process: ").append(process.processName).append("\n");
7119 }
Dan Egnora455d192010-03-12 08:52:28 -08007120 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007121 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007122 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7123 for (String pkg : process.pkgList) {
7124 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007125 try {
Dan Egnora455d192010-03-12 08:52:28 -08007126 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7127 if (pi != null) {
7128 sb.append(" v").append(pi.versionCode);
7129 if (pi.versionName != null) {
7130 sb.append(" (").append(pi.versionName).append(")");
7131 }
7132 }
7133 } catch (RemoteException e) {
7134 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007135 }
Dan Egnora455d192010-03-12 08:52:28 -08007136 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007137 }
Dan Egnora455d192010-03-12 08:52:28 -08007138 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007139 }
7140
7141 private static String processClass(ProcessRecord process) {
7142 if (process == null || process.pid == MY_PID) {
7143 return "system_server";
7144 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7145 return "system_app";
7146 } else {
7147 return "data_app";
7148 }
7149 }
7150
7151 /**
7152 * Write a description of an error (crash, WTF, ANR) to the drop box.
7153 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7154 * @param process which caused the error, null means the system server
7155 * @param activity which triggered the error, null if unknown
7156 * @param parent activity related to the error, null if unknown
7157 * @param subject line related to the error, null if absent
7158 * @param report in long form describing the error, null if absent
7159 * @param logFile to include in the report, null if none
7160 * @param crashInfo giving an application stack trace, null if absent
7161 */
7162 public void addErrorToDropBox(String eventType,
7163 ProcessRecord process, ActivityRecord activity, ActivityRecord parent, String subject,
7164 final String report, final File logFile,
7165 final ApplicationErrorReport.CrashInfo crashInfo) {
7166 // NOTE -- this must never acquire the ActivityManagerService lock,
7167 // otherwise the watchdog may be prevented from resetting the system.
7168
7169 final String dropboxTag = processClass(process) + "_" + eventType;
7170 final DropBoxManager dbox = (DropBoxManager)
7171 mContext.getSystemService(Context.DROPBOX_SERVICE);
7172
7173 // Exit early if the dropbox isn't configured to accept this report type.
7174 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7175
7176 final StringBuilder sb = new StringBuilder(1024);
7177 appendDropBoxProcessHeaders(process, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007178 if (activity != null) {
7179 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7180 }
7181 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7182 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7183 }
7184 if (parent != null && parent != activity) {
7185 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7186 }
7187 if (subject != null) {
7188 sb.append("Subject: ").append(subject).append("\n");
7189 }
7190 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007191 if (Debug.isDebuggerConnected()) {
7192 sb.append("Debugger: Connected\n");
7193 }
Dan Egnora455d192010-03-12 08:52:28 -08007194 sb.append("\n");
7195
7196 // Do the rest in a worker thread to avoid blocking the caller on I/O
7197 // (After this point, we shouldn't access AMS internal data structures.)
7198 Thread worker = new Thread("Error dump: " + dropboxTag) {
7199 @Override
7200 public void run() {
7201 if (report != null) {
7202 sb.append(report);
7203 }
7204 if (logFile != null) {
7205 try {
7206 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7207 } catch (IOException e) {
7208 Slog.e(TAG, "Error reading " + logFile, e);
7209 }
7210 }
7211 if (crashInfo != null && crashInfo.stackTrace != null) {
7212 sb.append(crashInfo.stackTrace);
7213 }
7214
7215 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7216 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7217 if (lines > 0) {
7218 sb.append("\n");
7219
7220 // Merge several logcat streams, and take the last N lines
7221 InputStreamReader input = null;
7222 try {
7223 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7224 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7225 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7226
7227 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7228 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7229 input = new InputStreamReader(logcat.getInputStream());
7230
7231 int num;
7232 char[] buf = new char[8192];
7233 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7234 } catch (IOException e) {
7235 Slog.e(TAG, "Error running logcat", e);
7236 } finally {
7237 if (input != null) try { input.close(); } catch (IOException e) {}
7238 }
7239 }
7240
7241 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007242 }
Dan Egnora455d192010-03-12 08:52:28 -08007243 };
7244
7245 if (process == null || process.pid == MY_PID) {
7246 worker.run(); // We may be about to die -- need to run this synchronously
7247 } else {
7248 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007249 }
7250 }
7251
7252 /**
7253 * Bring up the "unexpected error" dialog box for a crashing app.
7254 * Deal with edge cases (intercepts from instrumented applications,
7255 * ActivityController, error intent receivers, that sort of thing).
7256 * @param r the application crashing
7257 * @param crashInfo describing the failure
7258 */
7259 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007260 long timeMillis = System.currentTimeMillis();
7261 String shortMsg = crashInfo.exceptionClassName;
7262 String longMsg = crashInfo.exceptionMessage;
7263 String stackTrace = crashInfo.stackTrace;
7264 if (shortMsg != null && longMsg != null) {
7265 longMsg = shortMsg + ": " + longMsg;
7266 } else if (shortMsg != null) {
7267 longMsg = shortMsg;
7268 }
7269
Dan Egnor60d87622009-12-16 16:32:58 -08007270 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007271 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007272 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007273 try {
7274 String name = r != null ? r.processName : null;
7275 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007276 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007277 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007278 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007279 + " at watcher's request");
7280 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007281 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007282 }
7283 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007284 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007285 }
7286 }
7287
7288 final long origId = Binder.clearCallingIdentity();
7289
7290 // If this process is running instrumentation, finish it.
7291 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007292 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007293 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007294 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7295 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 Bundle info = new Bundle();
7297 info.putString("shortMsg", shortMsg);
7298 info.putString("longMsg", longMsg);
7299 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7300 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007301 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007302 }
7303
Dan Egnor60d87622009-12-16 16:32:58 -08007304 // If we can't identify the process or it's already exceeded its crash quota,
7305 // quit right away without showing a crash dialog.
7306 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007307 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007308 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 }
7310
7311 Message msg = Message.obtain();
7312 msg.what = SHOW_ERROR_MSG;
7313 HashMap data = new HashMap();
7314 data.put("result", result);
7315 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316 msg.obj = data;
7317 mHandler.sendMessage(msg);
7318
7319 Binder.restoreCallingIdentity(origId);
7320 }
7321
7322 int res = result.get();
7323
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007324 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007325 synchronized (this) {
7326 if (r != null) {
7327 mProcessCrashTimes.put(r.info.processName, r.info.uid,
7328 SystemClock.uptimeMillis());
7329 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007330 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007331 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007332 }
7333 }
7334
7335 if (appErrorIntent != null) {
7336 try {
7337 mContext.startActivity(appErrorIntent);
7338 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007339 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007343
7344 Intent createAppErrorIntentLocked(ProcessRecord r,
7345 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7346 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007347 if (report == null) {
7348 return null;
7349 }
7350 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7351 result.setComponent(r.errorReportReceiver);
7352 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7353 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7354 return result;
7355 }
7356
Dan Egnorb7f03672009-12-09 16:22:32 -08007357 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7358 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007359 if (r.errorReportReceiver == null) {
7360 return null;
7361 }
7362
7363 if (!r.crashing && !r.notResponding) {
7364 return null;
7365 }
7366
Dan Egnorb7f03672009-12-09 16:22:32 -08007367 ApplicationErrorReport report = new ApplicationErrorReport();
7368 report.packageName = r.info.packageName;
7369 report.installerPackageName = r.errorReportReceiver.getPackageName();
7370 report.processName = r.processName;
7371 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007372 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007373
Dan Egnorb7f03672009-12-09 16:22:32 -08007374 if (r.crashing) {
7375 report.type = ApplicationErrorReport.TYPE_CRASH;
7376 report.crashInfo = crashInfo;
7377 } else if (r.notResponding) {
7378 report.type = ApplicationErrorReport.TYPE_ANR;
7379 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007380
Dan Egnorb7f03672009-12-09 16:22:32 -08007381 report.anrInfo.activity = r.notRespondingReport.tag;
7382 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7383 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007384 }
7385
Dan Egnorb7f03672009-12-09 16:22:32 -08007386 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007387 }
7388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007389 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
7390 // assume our apps are happy - lazy create the list
7391 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7392
7393 synchronized (this) {
7394
7395 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007396 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7397 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007398 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7399 // This one's in trouble, so we'll generate a report for it
7400 // crashes are higher priority (in case there's a crash *and* an anr)
7401 ActivityManager.ProcessErrorStateInfo report = null;
7402 if (app.crashing) {
7403 report = app.crashingReport;
7404 } else if (app.notResponding) {
7405 report = app.notRespondingReport;
7406 }
7407
7408 if (report != null) {
7409 if (errList == null) {
7410 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
7411 }
7412 errList.add(report);
7413 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007414 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 " crashing = " + app.crashing +
7416 " notResponding = " + app.notResponding);
7417 }
7418 }
7419 }
7420 }
7421
7422 return errList;
7423 }
7424
7425 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
7426 // Lazy instantiation of list
7427 List<ActivityManager.RunningAppProcessInfo> runList = null;
7428 synchronized (this) {
7429 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007430 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7431 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007432 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
7433 // Generate process state info for running application
7434 ActivityManager.RunningAppProcessInfo currApp =
7435 new ActivityManager.RunningAppProcessInfo(app.processName,
7436 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07007437 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007438 if (mHeavyWeightProcess == app) {
Dianne Hackborn482566e2010-09-03 12:51:28 -07007439 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007440 }
Dianne Hackborn42499172010-10-15 18:45:07 -07007441 if (app.persistent) {
7442 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
7443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007444 int adj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -07007445 if (adj >= ProcessList.EMPTY_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007446 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY;
Dianne Hackborn7d608422011-08-07 16:24:18 -07007447 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007448 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborn7d608422011-08-07 16:24:18 -07007449 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
7450 } else if (adj >= ProcessList.HOME_APP_ADJ) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08007451 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
7452 currApp.lru = 0;
Dianne Hackborn7d608422011-08-07 16:24:18 -07007453 } else if (adj >= ProcessList.SECONDARY_SERVER_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007454 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn7d608422011-08-07 16:24:18 -07007455 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackborn5383f502010-10-22 12:59:20 -07007456 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
Dianne Hackborn7d608422011-08-07 16:24:18 -07007457 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07007458 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
Dianne Hackborn7d608422011-08-07 16:24:18 -07007459 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007460 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
7461 } else {
7462 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
7463 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007464 currApp.importanceReasonCode = app.adjTypeCode;
7465 if (app.adjSource instanceof ProcessRecord) {
7466 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007467 } else if (app.adjSource instanceof ActivityRecord) {
7468 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007469 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
7470 }
7471 if (app.adjTarget instanceof ComponentName) {
7472 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
7473 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007474 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007475 // + " lru=" + currApp.lru);
7476 if (runList == null) {
7477 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
7478 }
7479 runList.add(currApp);
7480 }
7481 }
7482 }
7483 return runList;
7484 }
7485
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007486 public List<ApplicationInfo> getRunningExternalApplications() {
7487 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
7488 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
7489 if (runningApps != null && runningApps.size() > 0) {
7490 Set<String> extList = new HashSet<String>();
7491 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
7492 if (app.pkgList != null) {
7493 for (String pkg : app.pkgList) {
7494 extList.add(pkg);
7495 }
7496 }
7497 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007498 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007499 for (String pkg : extList) {
7500 try {
7501 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
7502 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
7503 retList.add(info);
7504 }
7505 } catch (RemoteException e) {
7506 }
7507 }
7508 }
7509 return retList;
7510 }
7511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007512 @Override
7513 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007514 if (checkCallingPermission(android.Manifest.permission.DUMP)
7515 != PackageManager.PERMISSION_GRANTED) {
7516 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7517 + Binder.getCallingPid()
7518 + ", uid=" + Binder.getCallingUid()
7519 + " without permission "
7520 + android.Manifest.permission.DUMP);
7521 return;
7522 }
7523
7524 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007525 boolean dumpClient = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007526
7527 int opti = 0;
7528 while (opti < args.length) {
7529 String opt = args[opti];
7530 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7531 break;
7532 }
7533 opti++;
7534 if ("-a".equals(opt)) {
7535 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007536 } else if ("-c".equals(opt)) {
7537 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007538 } else if ("-h".equals(opt)) {
7539 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007540 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007541 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07007542 pw.println(" a[ctivities]: activity stack state");
7543 pw.println(" b[roadcasts]: broadcast state");
7544 pw.println(" i[ntents]: pending intent state");
7545 pw.println(" p[rocesses]: process state");
7546 pw.println(" o[om]: out of memory management");
7547 pw.println(" prov[iders]: content provider state");
7548 pw.println(" s[ervices]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007549 pw.println(" service [COMP_SPEC]: service client-side state");
7550 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
7551 pw.println(" COMP_SPEC may also be a component name (com.foo/.myApp),");
7552 pw.println(" a partial substring in a component name, an");
7553 pw.println(" ActivityRecord hex object identifier, or");
Dianne Hackbornf9302322011-06-14 18:36:14 -07007554 pw.println(" \"all\" for all objects, or");
7555 pw.println(" \"top\" for the top activity.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007556 pw.println(" -a: include all available server state.");
7557 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007558 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007559 } else {
7560 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007562 }
7563
7564 // Is the caller requesting to dump a particular piece of data?
7565 if (opti < args.length) {
7566 String cmd = args[opti];
7567 opti++;
7568 if ("activities".equals(cmd) || "a".equals(cmd)) {
7569 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007570 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007571 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007572 return;
7573 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
7574 synchronized (this) {
7575 dumpBroadcastsLocked(fd, pw, args, opti, true);
7576 }
7577 return;
7578 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
7579 synchronized (this) {
7580 dumpPendingIntentsLocked(fd, pw, args, opti, true);
7581 }
7582 return;
7583 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
7584 synchronized (this) {
7585 dumpProcessesLocked(fd, pw, args, opti, true);
7586 }
7587 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07007588 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
7589 synchronized (this) {
7590 dumpOomLocked(fd, pw, args, opti, true);
7591 }
7592 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007593 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
7594 synchronized (this) {
7595 dumpProvidersLocked(fd, pw, args, opti, true);
7596 }
7597 return;
7598 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007599 String[] newArgs;
7600 String name;
7601 if (opti >= args.length) {
7602 name = null;
7603 newArgs = EMPTY_STRING_ARRAY;
7604 } else {
7605 name = args[opti];
7606 opti++;
7607 newArgs = new String[args.length - opti];
7608 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
7609 }
7610 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
7611 pw.println("No services match: " + name);
7612 pw.println("Use -h for help.");
7613 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007614 return;
7615 } else if ("services".equals(cmd) || "s".equals(cmd)) {
7616 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007617 dumpServicesLocked(fd, pw, args, opti, true, dumpClient);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007618 }
7619 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07007620 } else {
7621 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007622 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
7623 pw.println("Bad activity command, or no activities match: " + cmd);
7624 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07007625 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08007626 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007628 }
7629
7630 // No piece of data specified, dump everything.
7631 synchronized (this) {
7632 boolean needSep;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007633 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007634 if (needSep) {
7635 pw.println(" ");
7636 }
7637 if (dumpAll) {
7638 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007639 }
7640 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll);
7641 if (needSep) {
7642 pw.println(" ");
7643 }
7644 if (dumpAll) {
7645 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007646 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007647 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007648 if (needSep) {
7649 pw.println(" ");
7650 }
7651 if (dumpAll) {
7652 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007653 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007654 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007655 if (needSep) {
7656 pw.println(" ");
7657 }
7658 if (dumpAll) {
7659 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007660 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007661 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007662 if (needSep) {
7663 pw.println(" ");
7664 }
7665 if (dumpAll) {
7666 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007667 }
7668 dumpProcessesLocked(fd, pw, args, opti, dumpAll);
7669 }
7670 }
7671
7672 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007673 int opti, boolean dumpAll, boolean dumpClient) {
7674 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
7675 pw.println(" Main stack:");
7676 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007677 pw.println(" ");
7678 pw.println(" Running activities (most recent first):");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007679 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007680 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007681 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007682 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007683 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
7684 !dumpAll, false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007685 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007686 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007688 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007689 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
7690 !dumpAll, false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007691 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007692 if (mMainStack.mGoingToSleepActivities.size() > 0) {
7693 pw.println(" ");
7694 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007695 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
7696 !dumpAll, false);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007697 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007698 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007699 pw.println(" ");
7700 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007701 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
7702 !dumpAll, false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007704
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007705 pw.println(" ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007706 if (mMainStack.mPausingActivity != null) {
7707 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
7708 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007709 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007710 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007711 if (dumpAll) {
7712 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
7713 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
7714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007716 if (mRecentTasks.size() > 0) {
7717 pw.println();
7718 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007719
7720 final int N = mRecentTasks.size();
7721 for (int i=0; i<N; i++) {
7722 TaskRecord tr = mRecentTasks.get(i);
7723 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
7724 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007725 if (dumpAll) {
7726 mRecentTasks.get(i).dump(pw, " ");
7727 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007728 }
7729 }
7730
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007731 if (dumpAll) {
7732 pw.println(" ");
7733 pw.println(" mCurTask: " + mCurTask);
7734 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007735
7736 return true;
7737 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07007738
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007739 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7740 int opti, boolean dumpAll) {
7741 boolean needSep = false;
7742 int numPers = 0;
7743
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007744 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
7745
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007746 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
7748 final int NA = procs.size();
7749 for (int ia=0; ia<NA; ia++) {
7750 if (!needSep) {
7751 pw.println(" All known processes:");
7752 needSep = true;
7753 }
7754 ProcessRecord r = procs.valueAt(ia);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007755 pw.print(r.persistent ? " *PERS*" : " *APP*");
7756 pw.print(" UID "); pw.print(procs.keyAt(ia));
7757 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007758 r.dump(pw, " ");
7759 if (r.persistent) {
7760 numPers++;
7761 }
7762 }
7763 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007764 }
7765
7766 if (mLruProcesses.size() > 0) {
7767 if (needSep) pw.println(" ");
7768 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007769 pw.println(" Process LRU list (most recent first):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07007770 dumpProcessOomList(pw, this, mLruProcesses, " ",
7771 "Proc", "PERS", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007772 needSep = true;
7773 }
7774
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007775 if (dumpAll) {
7776 synchronized (mPidsSelfLocked) {
7777 if (mPidsSelfLocked.size() > 0) {
7778 if (needSep) pw.println(" ");
7779 needSep = true;
7780 pw.println(" PID mappings:");
7781 for (int i=0; i<mPidsSelfLocked.size(); i++) {
7782 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
7783 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
7784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 }
7786 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007787 }
7788
7789 if (mForegroundProcesses.size() > 0) {
7790 if (needSep) pw.println(" ");
7791 needSep = true;
7792 pw.println(" Foreground Processes:");
7793 for (int i=0; i<mForegroundProcesses.size(); i++) {
7794 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
7795 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007796 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007797 }
7798
7799 if (mPersistentStartingProcesses.size() > 0) {
7800 if (needSep) pw.println(" ");
7801 needSep = true;
7802 pw.println(" Persisent processes that are starting:");
7803 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007804 "Starting Norm", "Restarting PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007806
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007807 if (mRemovedProcesses.size() > 0) {
7808 if (needSep) pw.println(" ");
7809 needSep = true;
7810 pw.println(" Processes that are being removed:");
7811 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007812 "Removed Norm", "Removed PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007813 }
7814
7815 if (mProcessesOnHold.size() > 0) {
7816 if (needSep) pw.println(" ");
7817 needSep = true;
7818 pw.println(" Processes that are on old until the system is ready:");
7819 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007820 "OnHold Norm", "OnHold PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007822
Dianne Hackborn287952c2010-09-22 22:34:31 -07007823 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007824
7825 if (mProcessCrashTimes.getMap().size() > 0) {
7826 if (needSep) pw.println(" ");
7827 needSep = true;
7828 pw.println(" Time since processes crashed:");
7829 long now = SystemClock.uptimeMillis();
7830 for (Map.Entry<String, SparseArray<Long>> procs
7831 : mProcessCrashTimes.getMap().entrySet()) {
7832 SparseArray<Long> uids = procs.getValue();
7833 final int N = uids.size();
7834 for (int i=0; i<N; i++) {
7835 pw.print(" Process "); pw.print(procs.getKey());
7836 pw.print(" uid "); pw.print(uids.keyAt(i));
7837 pw.print(": last crashed ");
7838 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07007839 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07007840 }
7841 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007844 if (mBadProcesses.getMap().size() > 0) {
7845 if (needSep) pw.println(" ");
7846 needSep = true;
7847 pw.println(" Bad processes:");
7848 for (Map.Entry<String, SparseArray<Long>> procs
7849 : mBadProcesses.getMap().entrySet()) {
7850 SparseArray<Long> uids = procs.getValue();
7851 final int N = uids.size();
7852 for (int i=0; i<N; i++) {
7853 pw.print(" Bad process "); pw.print(procs.getKey());
7854 pw.print(" uid "); pw.print(uids.keyAt(i));
7855 pw.print(": crashed at time ");
7856 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 }
7858 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007860
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007861 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007862 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackborn860755f2010-06-03 18:47:52 -07007863 if (mHeavyWeightProcess != null) {
7864 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7865 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007866 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007867 if (dumpAll) {
7868 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07007869 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07007870 pw.println(" mScreenCompatPackages:");
7871 for (Map.Entry<String, Integer> entry
7872 : mCompatModePackages.getPackages().entrySet()) {
7873 String pkg = entry.getKey();
7874 int mode = entry.getValue();
7875 pw.print(" "); pw.print(pkg); pw.print(": ");
7876 pw.print(mode); pw.println();
7877 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07007878 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007879 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007880 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
7881 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
7882 || mOrigWaitForDebugger) {
7883 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
7884 + " mDebugTransient=" + mDebugTransient
7885 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
7886 }
7887 if (mAlwaysFinishActivities || mController != null) {
7888 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
7889 + " mController=" + mController);
7890 }
7891 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007893 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07007894 + " mProcessesReady=" + mProcessesReady
7895 + " mSystemReady=" + mSystemReady);
7896 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007897 + " mBooted=" + mBooted
7898 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07007899 pw.print(" mLastPowerCheckRealtime=");
7900 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
7901 pw.println("");
7902 pw.print(" mLastPowerCheckUptime=");
7903 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
7904 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007905 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
7906 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07007907 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007908 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007909
7910 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007911 }
7912
Dianne Hackborn287952c2010-09-22 22:34:31 -07007913 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
7914 int opti, boolean needSep, boolean dumpAll) {
7915 if (mProcessesToGc.size() > 0) {
7916 if (needSep) pw.println(" ");
7917 needSep = true;
7918 pw.println(" Processes that are waiting to GC:");
7919 long now = SystemClock.uptimeMillis();
7920 for (int i=0; i<mProcessesToGc.size(); i++) {
7921 ProcessRecord proc = mProcessesToGc.get(i);
7922 pw.print(" Process "); pw.println(proc);
7923 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
7924 pw.print(", last gced=");
7925 pw.print(now-proc.lastRequestedGc);
7926 pw.print(" ms ago, last lowMem=");
7927 pw.print(now-proc.lastLowMemory);
7928 pw.println(" ms ago");
7929
7930 }
7931 }
7932 return needSep;
7933 }
7934
7935 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7936 int opti, boolean dumpAll) {
7937 boolean needSep = false;
7938
7939 if (mLruProcesses.size() > 0) {
7940 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(mLruProcesses);
7941
7942 Comparator<ProcessRecord> comparator = new Comparator<ProcessRecord>() {
7943 @Override
7944 public int compare(ProcessRecord object1, ProcessRecord object2) {
7945 if (object1.setAdj != object2.setAdj) {
7946 return object1.setAdj > object2.setAdj ? -1 : 1;
7947 }
7948 if (object1.setSchedGroup != object2.setSchedGroup) {
7949 return object1.setSchedGroup > object2.setSchedGroup ? -1 : 1;
7950 }
7951 if (object1.keeping != object2.keeping) {
7952 return object1.keeping ? -1 : 1;
7953 }
7954 if (object1.pid != object2.pid) {
7955 return object1.pid > object2.pid ? -1 : 1;
7956 }
7957 return 0;
7958 }
7959 };
7960
7961 Collections.sort(procs, comparator);
7962
7963 if (needSep) pw.println(" ");
7964 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07007965 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07007966 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
7967 pw.print(" CORE_SERVER_ADJ: "); pw.println(ProcessList.CORE_SERVER_ADJ);
7968 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
7969 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
7970 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
7971 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
7972 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
7973 pw.print(" SECONDARY_SERVER_ADJ: "); pw.println(ProcessList.SECONDARY_SERVER_ADJ);
7974 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
7975 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
7976 pw.print(" EMPTY_APP_ADJ: "); pw.println(ProcessList.EMPTY_APP_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07007977
7978 if (needSep) pw.println(" ");
7979 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07007980 pw.println(" Process OOM control:");
7981 dumpProcessOomList(pw, this, procs, " ",
7982 "Proc", "PERS", true);
7983 needSep = true;
7984 }
7985
7986 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll);
7987
Dianne Hackborne17aeb32011-04-07 15:11:57 -07007988 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07007989 pw.println(" mHomeProcess: " + mHomeProcess);
7990 if (mHeavyWeightProcess != null) {
7991 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7992 }
7993
7994 return true;
7995 }
7996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 /**
7998 * There are three ways to call this:
7999 * - no service specified: dump all the services
8000 * - a flattened component name that matched an existing service was specified as the
8001 * first arg: dump that one service
8002 * - the first arg isn't the flattened component name of an existing service:
8003 * dump all services whose component contains the first arg as a substring
8004 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008005 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8006 int opti, boolean dumpAll) {
8007 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008008
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008009 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008010 synchronized (this) {
8011 for (ServiceRecord r1 : mServices.values()) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008012 services.add(r1);
8013 }
8014 }
8015 } else {
8016 ComponentName componentName = name != null
8017 ? ComponentName.unflattenFromString(name) : null;
8018 int objectId = 0;
8019 if (componentName == null) {
8020 // Not a '/' separated full component name; maybe an object ID?
8021 try {
8022 objectId = Integer.parseInt(name, 16);
8023 name = null;
8024 componentName = null;
8025 } catch (RuntimeException e) {
8026 }
8027 }
8028
8029 synchronized (this) {
8030 for (ServiceRecord r1 : mServices.values()) {
8031 if (componentName != null) {
8032 if (r1.name.equals(componentName)) {
8033 services.add(r1);
8034 }
8035 } else if (name != null) {
8036 if (r1.name.flattenToString().contains(name)) {
8037 services.add(r1);
8038 }
8039 } else if (System.identityHashCode(r1) == objectId) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008040 services.add(r1);
8041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008042 }
8043 }
8044 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008045
8046 if (services.size() <= 0) {
8047 return false;
8048 }
8049
8050 boolean needSep = false;
8051 for (int i=0; i<services.size(); i++) {
8052 if (needSep) {
8053 pw.println();
8054 }
8055 needSep = true;
8056 dumpService("", fd, pw, services.get(i), args, dumpAll);
8057 }
8058 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008059 }
8060
8061 /**
8062 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8063 * there is a thread associated with the service.
8064 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008065 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8066 final ServiceRecord r, String[] args, boolean dumpAll) {
8067 String innerPrefix = prefix + " ";
8068 synchronized (this) {
8069 pw.print(prefix); pw.print("SERVICE ");
8070 pw.print(r.shortName); pw.print(" ");
8071 pw.print(Integer.toHexString(System.identityHashCode(r)));
8072 pw.print(" pid=");
8073 if (r.app != null) pw.println(r.app.pid);
8074 else pw.println("(not running)");
8075 if (dumpAll) {
8076 r.dump(pw, innerPrefix);
8077 }
8078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008080 pw.print(prefix); pw.println(" Client:");
8081 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008083 TransferPipe tp = new TransferPipe();
8084 try {
8085 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8086 tp.setBufferPrefix(prefix + " ");
8087 tp.go(fd);
8088 } finally {
8089 tp.kill();
8090 }
8091 } catch (IOException e) {
8092 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008093 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008094 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 }
8096 }
8097 }
8098
Dianne Hackborn625ac272010-09-17 18:29:22 -07008099 /**
8100 * There are three things that cmd can be:
8101 * - a flattened component name that matched an existing activity
8102 * - the cmd arg isn't the flattened component name of an existing activity:
8103 * dump all activity whose component contains the cmd as a substring
8104 * - A hex number of the ActivityRecord object instance.
8105 */
8106 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8107 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008108 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008109
8110 if ("all".equals(name)) {
8111 synchronized (this) {
8112 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008113 activities.add(r1);
8114 }
8115 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07008116 } else if ("top".equals(name)) {
8117 synchronized (this) {
8118 final int N = mMainStack.mHistory.size();
8119 if (N > 0) {
8120 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
8121 }
8122 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008123 } else {
8124 ComponentName componentName = ComponentName.unflattenFromString(name);
8125 int objectId = 0;
8126 if (componentName == null) {
8127 // Not a '/' separated full component name; maybe an object ID?
8128 try {
8129 objectId = Integer.parseInt(name, 16);
8130 name = null;
8131 componentName = null;
8132 } catch (RuntimeException e) {
8133 }
8134 }
8135
8136 synchronized (this) {
8137 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
8138 if (componentName != null) {
8139 if (r1.intent.getComponent().equals(componentName)) {
8140 activities.add(r1);
8141 }
8142 } else if (name != null) {
8143 if (r1.intent.getComponent().flattenToString().contains(name)) {
8144 activities.add(r1);
8145 }
8146 } else if (System.identityHashCode(r1) == objectId) {
8147 activities.add(r1);
8148 }
8149 }
8150 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008151 }
8152
8153 if (activities.size() <= 0) {
8154 return false;
8155 }
8156
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008157 String[] newArgs = new String[args.length - opti];
8158 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8159
Dianne Hackborn30d71892010-12-11 10:37:55 -08008160 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008161 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08008162 for (int i=activities.size()-1; i>=0; i--) {
8163 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008164 if (needSep) {
8165 pw.println();
8166 }
8167 needSep = true;
8168 synchronized (this) {
8169 if (lastTask != r.task) {
8170 lastTask = r.task;
8171 pw.print("TASK "); pw.print(lastTask.affinity);
8172 pw.print(" id="); pw.println(lastTask.taskId);
8173 if (dumpAll) {
8174 lastTask.dump(pw, " ");
8175 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008176 }
8177 }
8178 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008179 }
8180 return true;
8181 }
8182
8183 /**
8184 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
8185 * there is a thread associated with the activity.
8186 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08008187 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008188 final ActivityRecord r, String[] args, boolean dumpAll) {
8189 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08008190 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008191 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
8192 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
8193 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08008194 if (r.app != null) pw.println(r.app.pid);
8195 else pw.println("(not running)");
8196 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008197 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008198 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008199 }
8200 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008201 // flush anything that is already in the PrintWriter since the thread is going
8202 // to write to the file descriptor directly
8203 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07008204 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008205 TransferPipe tp = new TransferPipe();
8206 try {
8207 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(), r,
8208 innerPrefix, args);
8209 tp.go(fd);
8210 } finally {
8211 tp.kill();
8212 }
8213 } catch (IOException e) {
8214 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008215 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008216 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008217 }
8218 }
8219 }
8220
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008221 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8222 int opti, boolean dumpAll) {
8223 boolean needSep = false;
8224
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008225 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008226 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008227 if (mRegisteredReceivers.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228 pw.println(" Registered Receivers:");
8229 Iterator it = mRegisteredReceivers.values().iterator();
8230 while (it.hasNext()) {
8231 ReceiverList r = (ReceiverList)it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008232 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008233 r.dump(pw, " ");
8234 }
8235 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008236
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008237 pw.println();
8238 pw.println(" Receiver Resolver Table:");
8239 mReceiverResolver.dump(pw, null, " ", null, false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008240 needSep = true;
8241 }
8242
8243 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
8244 || mPendingBroadcast != null) {
8245 if (mParallelBroadcasts.size() > 0) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008246 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008247 pw.println(" Active broadcasts:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008248 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008249 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
8250 pw.println(" Broadcast #" + i + ":");
8251 mParallelBroadcasts.get(i).dump(pw, " ");
8252 }
8253 if (mOrderedBroadcasts.size() > 0) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008254 pw.println();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07008255 pw.println(" Active ordered broadcasts:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008256 }
8257 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
8258 pw.println(" Serialized Broadcast #" + i + ":");
8259 mOrderedBroadcasts.get(i).dump(pw, " ");
8260 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008261 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008262 pw.println(" Pending broadcast:");
8263 if (mPendingBroadcast != null) {
8264 mPendingBroadcast.dump(pw, " ");
8265 } else {
8266 pw.println(" (null)");
8267 }
8268 needSep = true;
8269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008270
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008271 if (needSep) {
8272 pw.println();
8273 }
8274 pw.println(" Historical broadcasts:");
8275 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
8276 BroadcastRecord r = mBroadcastHistory[i];
8277 if (r == null) {
8278 break;
8279 }
8280 if (dumpAll) {
8281 pw.print(" Historical Broadcast #"); pw.print(i); pw.println(":");
8282 r.dump(pw, " ");
8283 } else {
8284 if (i >= 50) {
8285 pw.println(" ...");
Dianne Hackborn12527f92009-11-11 17:39:50 -08008286 break;
8287 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008288 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
Dianne Hackborn12527f92009-11-11 17:39:50 -08008289 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008290 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008291 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008292
8293 if (mStickyBroadcasts != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008294 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008295 pw.println(" Sticky broadcasts:");
8296 StringBuilder sb = new StringBuilder(128);
8297 for (Map.Entry<String, ArrayList<Intent>> ent
8298 : mStickyBroadcasts.entrySet()) {
8299 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008300 if (dumpAll) {
8301 pw.println(":");
8302 ArrayList<Intent> intents = ent.getValue();
8303 final int N = intents.size();
8304 for (int i=0; i<N; i++) {
8305 sb.setLength(0);
8306 sb.append(" Intent: ");
8307 intents.get(i).toShortString(sb, true, false);
8308 pw.println(sb.toString());
8309 Bundle bundle = intents.get(i).getExtras();
8310 if (bundle != null) {
8311 pw.print(" ");
8312 pw.println(bundle.toString());
8313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008314 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008315 } else {
8316 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008317 }
8318 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008319 needSep = true;
8320 }
8321
8322 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008323 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008324 pw.println(" mBroadcastsScheduled=" + mBroadcastsScheduled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008325 pw.println(" mHandler:");
8326 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008327 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008328 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008329
8330 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008331 }
8332
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008333 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008334 int opti, boolean dumpAll, boolean dumpClient) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008335 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008337 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
8338 if (mServices.size() > 0) {
8339 pw.println(" Active services:");
8340 long nowReal = SystemClock.elapsedRealtime();
8341 Iterator<ServiceRecord> it = mServices.values().iterator();
8342 needSep = false;
8343 while (it.hasNext()) {
8344 ServiceRecord r = it.next();
8345 if (needSep) {
8346 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008347 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008348 pw.print(" * "); pw.println(r);
8349 if (dumpAll) {
8350 r.dump(pw, " ");
8351 needSep = true;
8352 } else {
8353 pw.print(" app="); pw.println(r.app);
8354 pw.print(" created=");
8355 TimeUtils.formatDuration(r.createTime, nowReal, pw);
8356 pw.print(" started="); pw.print(r.startRequested);
8357 pw.print(" connections="); pw.println(r.connections.size());
8358 }
8359 if (dumpClient && r.app != null && r.app.thread != null) {
8360 pw.println(" Client:");
8361 pw.flush();
8362 try {
8363 TransferPipe tp = new TransferPipe();
8364 try {
8365 r.app.thread.dumpService(
8366 tp.getWriteFd().getFileDescriptor(), r, args);
8367 tp.setBufferPrefix(" ");
8368 // Short timeout, since blocking here can
8369 // deadlock with the application.
8370 tp.go(fd, 2000);
8371 } finally {
8372 tp.kill();
8373 }
8374 } catch (IOException e) {
8375 pw.println(" Failure while dumping the service: " + e);
8376 } catch (RemoteException e) {
8377 pw.println(" Got a RemoteException while dumping the service");
8378 }
8379 needSep = true;
8380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008381 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008382 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008384
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008385 if (mPendingServices.size() > 0) {
8386 if (needSep) pw.println(" ");
8387 pw.println(" Pending services:");
8388 for (int i=0; i<mPendingServices.size(); i++) {
8389 ServiceRecord r = mPendingServices.get(i);
8390 pw.print(" * Pending "); pw.println(r);
8391 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008392 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008393 needSep = true;
8394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008395
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008396 if (mRestartingServices.size() > 0) {
8397 if (needSep) pw.println(" ");
8398 pw.println(" Restarting services:");
8399 for (int i=0; i<mRestartingServices.size(); i++) {
8400 ServiceRecord r = mRestartingServices.get(i);
8401 pw.print(" * Restarting "); pw.println(r);
8402 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008403 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008404 needSep = true;
8405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008406
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008407 if (mStoppingServices.size() > 0) {
8408 if (needSep) pw.println(" ");
8409 pw.println(" Stopping services:");
8410 for (int i=0; i<mStoppingServices.size(); i++) {
8411 ServiceRecord r = mStoppingServices.get(i);
8412 pw.print(" * Stopping "); pw.println(r);
8413 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008414 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008415 needSep = true;
8416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008417
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008418 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008419 if (mServiceConnections.size() > 0) {
8420 if (needSep) pw.println(" ");
8421 pw.println(" Connection bindings to services:");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008422 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008423 = mServiceConnections.values().iterator();
8424 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008425 ArrayList<ConnectionRecord> r = it.next();
8426 for (int i=0; i<r.size(); i++) {
8427 pw.print(" * "); pw.println(r.get(i));
8428 r.get(i).dump(pw, " ");
8429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008430 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008431 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008432 }
8433 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008434
8435 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008436 }
8437
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008438 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8439 int opti, boolean dumpAll) {
8440 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008441
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008442 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
8443 if (mProvidersByClass.size() > 0) {
8444 if (needSep) pw.println(" ");
8445 pw.println(" Published content providers (by class):");
8446 Iterator<Map.Entry<String, ContentProviderRecord>> it
8447 = mProvidersByClass.entrySet().iterator();
8448 while (it.hasNext()) {
8449 Map.Entry<String, ContentProviderRecord> e = it.next();
8450 ContentProviderRecord r = e.getValue();
8451 if (dumpAll) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008452 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008453 r.dump(pw, " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008454 } else {
8455 pw.print(" * "); pw.print(r.name.toShortString());
8456 if (r.app != null) {
8457 pw.println(":");
8458 pw.print(" "); pw.println(r.app);
8459 } else {
8460 pw.println();
8461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008463 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008464 needSep = true;
8465 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008466
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008467 if (dumpAll) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008468 if (mProvidersByName.size() > 0) {
8469 pw.println(" ");
8470 pw.println(" Authority to provider mappings:");
Dianne Hackborn860755f2010-06-03 18:47:52 -07008471 Iterator<Map.Entry<String, ContentProviderRecord>> it
8472 = mProvidersByName.entrySet().iterator();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008473 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008474 Map.Entry<String, ContentProviderRecord> e = it.next();
8475 ContentProviderRecord r = e.getValue();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008476 pw.print(" "); pw.print(e.getKey()); pw.print(": ");
8477 pw.println(r);
8478 }
8479 needSep = true;
8480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008482
8483 if (mLaunchingProviders.size() > 0) {
8484 if (needSep) pw.println(" ");
8485 pw.println(" Launching content providers:");
8486 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
8487 pw.print(" Launching #"); pw.print(i); pw.print(": ");
8488 pw.println(mLaunchingProviders.get(i));
8489 }
8490 needSep = true;
8491 }
8492
8493 if (mGrantedUriPermissions.size() > 0) {
8494 pw.println();
8495 pw.println("Granted Uri Permissions:");
8496 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
8497 int uid = mGrantedUriPermissions.keyAt(i);
8498 HashMap<Uri, UriPermission> perms
8499 = mGrantedUriPermissions.valueAt(i);
8500 pw.print(" * UID "); pw.print(uid);
8501 pw.println(" holds:");
8502 for (UriPermission perm : perms.values()) {
8503 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008504 if (dumpAll) {
8505 perm.dump(pw, " ");
8506 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008507 }
8508 }
8509 needSep = true;
8510 }
8511
8512 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008513 }
8514
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008515 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8516 int opti, boolean dumpAll) {
8517 boolean needSep = false;
8518
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008519 if (this.mIntentSenderRecords.size() > 0) {
8520 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
8521 Iterator<WeakReference<PendingIntentRecord>> it
8522 = mIntentSenderRecords.values().iterator();
8523 while (it.hasNext()) {
8524 WeakReference<PendingIntentRecord> ref = it.next();
8525 PendingIntentRecord rec = ref != null ? ref.get(): null;
8526 needSep = true;
8527 if (rec != null) {
8528 pw.print(" * "); pw.println(rec);
8529 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008532 } else {
8533 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008534 }
8535 }
8536 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008537
8538 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008539 }
8540
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008541 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
8542 String prefix, String label, boolean complete, boolean brief, boolean client) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008543 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008544 boolean needNL = false;
8545 final String innerPrefix = prefix + " ";
8546 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008548 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07008549 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008550 if (needNL) {
8551 pw.println(" ");
8552 needNL = false;
8553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 if (lastTask != r.task) {
8555 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008556 pw.print(prefix);
8557 pw.print(full ? "* " : " ");
8558 pw.println(lastTask);
8559 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008560 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008561 } else if (complete) {
8562 // Complete + brief == give a summary. Isn't that obvious?!?
8563 if (lastTask.intent != null) {
8564 pw.print(prefix); pw.print(" "); pw.println(lastTask.intent);
8565 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008567 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008568 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
8569 pw.print(" #"); pw.print(i); pw.print(": ");
8570 pw.println(r);
8571 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008572 r.dump(pw, innerPrefix);
8573 } else if (complete) {
8574 // Complete + brief == give a summary. Isn't that obvious?!?
8575 pw.print(innerPrefix); pw.println(r.intent);
8576 if (r.app != null) {
8577 pw.print(innerPrefix); pw.println(r.app);
8578 }
8579 }
8580 if (client && r.app != null && r.app.thread != null) {
8581 // flush anything that is already in the PrintWriter since the thread is going
8582 // to write to the file descriptor directly
8583 pw.flush();
8584 try {
8585 TransferPipe tp = new TransferPipe();
8586 try {
8587 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(), r,
8588 innerPrefix, args);
8589 // Short timeout, since blocking here can
8590 // deadlock with the application.
8591 tp.go(fd, 2000);
8592 } finally {
8593 tp.kill();
8594 }
8595 } catch (IOException e) {
8596 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
8597 } catch (RemoteException e) {
8598 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
8599 }
8600 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008602 }
8603 }
8604
Dianne Hackborn09c916b2009-12-08 14:50:51 -08008605 private static String buildOomTag(String prefix, String space, int val, int base) {
8606 if (val == base) {
8607 if (space == null) return prefix;
8608 return prefix + " ";
8609 }
8610 return prefix + "+" + Integer.toString(val-base);
8611 }
8612
8613 private static final int dumpProcessList(PrintWriter pw,
8614 ActivityManagerService service, List list,
Dianne Hackborn287952c2010-09-22 22:34:31 -07008615 String prefix, String normalLabel, String persistentLabel) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008616 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07008617 final int N = list.size()-1;
8618 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008619 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008620 pw.println(String.format("%s%s #%2d: %s",
8621 prefix, (r.persistent ? persistentLabel : normalLabel),
8622 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008623 if (r.persistent) {
8624 numPers++;
8625 }
8626 }
8627 return numPers;
8628 }
8629
Dianne Hackborn287952c2010-09-22 22:34:31 -07008630 private static final void dumpProcessOomList(PrintWriter pw,
8631 ActivityManagerService service, List<ProcessRecord> list,
8632 String prefix, String normalLabel, String persistentLabel,
8633 boolean inclDetails) {
8634
8635 final long curRealtime = SystemClock.elapsedRealtime();
8636 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
8637 final long curUptime = SystemClock.uptimeMillis();
8638 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
8639
8640 final int N = list.size()-1;
8641 for (int i=N; i>=0; i--) {
8642 ProcessRecord r = list.get(i);
8643 String oomAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -07008644 if (r.setAdj >= ProcessList.EMPTY_APP_ADJ) {
8645 oomAdj = buildOomTag("empty", null, r.setAdj, ProcessList.EMPTY_APP_ADJ);
8646 } else if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
8647 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
8648 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
8649 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
8650 } else if (r.setAdj >= ProcessList.SECONDARY_SERVER_ADJ) {
8651 oomAdj = buildOomTag("svc", " ", r.setAdj, ProcessList.SECONDARY_SERVER_ADJ);
8652 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
8653 oomAdj = buildOomTag("bckup", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
8654 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8655 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
8656 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8657 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
8658 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
8659 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
8660 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
8661 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
8662 } else if (r.setAdj >= ProcessList.CORE_SERVER_ADJ) {
8663 oomAdj = buildOomTag("core ", null, r.setAdj, ProcessList.CORE_SERVER_ADJ);
8664 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
8665 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008666 } else {
8667 oomAdj = Integer.toString(r.setAdj);
8668 }
8669 String schedGroup;
8670 switch (r.setSchedGroup) {
8671 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
8672 schedGroup = "B";
8673 break;
8674 case Process.THREAD_GROUP_DEFAULT:
8675 schedGroup = "F";
8676 break;
8677 default:
8678 schedGroup = Integer.toString(r.setSchedGroup);
8679 break;
8680 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07008681 String foreground;
8682 if (r.foregroundActivities) {
8683 foreground = "A";
8684 } else if (r.foregroundServices) {
8685 foreground = "S";
8686 } else {
8687 foreground = " ";
8688 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07008689 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07008690 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornce86ba82011-07-13 19:33:41 -07008691 N-i, oomAdj, schedGroup, foreground, r.trimMemoryLevel,
8692 r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07008693 if (r.adjSource != null || r.adjTarget != null) {
8694 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008695 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008696 if (r.adjTarget instanceof ComponentName) {
8697 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
8698 } else if (r.adjTarget != null) {
8699 pw.print(r.adjTarget.toString());
8700 } else {
8701 pw.print("{null}");
8702 }
8703 pw.print("<=");
8704 if (r.adjSource instanceof ProcessRecord) {
8705 pw.print("Proc{");
8706 pw.print(((ProcessRecord)r.adjSource).toShortString());
8707 pw.println("}");
8708 } else if (r.adjSource != null) {
8709 pw.println(r.adjSource.toString());
8710 } else {
8711 pw.println("{null}");
8712 }
8713 }
8714 if (inclDetails) {
8715 pw.print(prefix);
8716 pw.print(" ");
8717 pw.print("oom: max="); pw.print(r.maxAdj);
8718 pw.print(" hidden="); pw.print(r.hiddenAdj);
8719 pw.print(" curRaw="); pw.print(r.curRawAdj);
8720 pw.print(" setRaw="); pw.print(r.setRawAdj);
8721 pw.print(" cur="); pw.print(r.curAdj);
8722 pw.print(" set="); pw.println(r.setAdj);
8723 pw.print(prefix);
8724 pw.print(" ");
8725 pw.print("keeping="); pw.print(r.keeping);
8726 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008727 pw.print(" empty="); pw.print(r.empty);
8728 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008729
8730 if (!r.keeping) {
8731 if (r.lastWakeTime != 0) {
8732 long wtime;
8733 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
8734 synchronized (stats) {
8735 wtime = stats.getProcessWakeTime(r.info.uid,
8736 r.pid, curRealtime);
8737 }
8738 long timeUsed = wtime - r.lastWakeTime;
8739 pw.print(prefix);
8740 pw.print(" ");
8741 pw.print("keep awake over ");
8742 TimeUtils.formatDuration(realtimeSince, pw);
8743 pw.print(" used ");
8744 TimeUtils.formatDuration(timeUsed, pw);
8745 pw.print(" (");
8746 pw.print((timeUsed*100)/realtimeSince);
8747 pw.println("%)");
8748 }
8749 if (r.lastCpuTime != 0) {
8750 long timeUsed = r.curCpuTime - r.lastCpuTime;
8751 pw.print(prefix);
8752 pw.print(" ");
8753 pw.print("run cpu over ");
8754 TimeUtils.formatDuration(uptimeSince, pw);
8755 pw.print(" used ");
8756 TimeUtils.formatDuration(timeUsed, pw);
8757 pw.print(" (");
8758 pw.print((timeUsed*100)/uptimeSince);
8759 pw.println("%)");
8760 }
8761 }
8762 }
8763 }
8764 }
8765
Dianne Hackbornb437e092011-08-05 17:50:29 -07008766 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008767 ArrayList<ProcessRecord> procs;
8768 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07008769 if (args != null && args.length > start
8770 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008771 procs = new ArrayList<ProcessRecord>();
8772 int pid = -1;
8773 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07008774 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008775 } catch (NumberFormatException e) {
8776
8777 }
8778 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8779 ProcessRecord proc = mLruProcesses.get(i);
8780 if (proc.pid == pid) {
8781 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07008782 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008783 procs.add(proc);
8784 }
8785 }
8786 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07008787 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008788 return null;
8789 }
8790 } else {
8791 procs = new ArrayList<ProcessRecord>(mLruProcesses);
8792 }
8793 }
8794 return procs;
8795 }
8796
8797 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
8798 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07008799 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008800 if (procs == null) {
8801 return;
8802 }
8803
8804 long uptime = SystemClock.uptimeMillis();
8805 long realtime = SystemClock.elapsedRealtime();
8806 pw.println("Applications Graphics Acceleration Info:");
8807 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
8808
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008809 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
8810 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07008811 if (r.thread != null) {
8812 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
8813 pw.flush();
8814 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008815 TransferPipe tp = new TransferPipe();
8816 try {
8817 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
8818 tp.go(fd);
8819 } finally {
8820 tp.kill();
8821 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008822 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008823 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008824 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07008825 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008826 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07008827 pw.flush();
8828 }
8829 }
8830 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07008831 }
8832
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008833 final static class MemItem {
8834 final String label;
8835 final long pss;
8836
8837 public MemItem(String _label, long _pss) {
8838 label = _label;
8839 pss = _pss;
8840 }
8841 }
8842
Dianne Hackbornb437e092011-08-05 17:50:29 -07008843 final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
8844 boolean sort) {
8845 if (sort) {
8846 Collections.sort(items, new Comparator<MemItem>() {
8847 @Override
8848 public int compare(MemItem lhs, MemItem rhs) {
8849 if (lhs.pss < rhs.pss) {
8850 return 1;
8851 } else if (lhs.pss > rhs.pss) {
8852 return -1;
8853 }
8854 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008855 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07008856 });
8857 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008858
8859 for (int i=0; i<items.size(); i++) {
8860 MemItem mi = items.get(i);
8861 pw.print(prefix); pw.printf("%8d Kb: ", mi.pss); pw.println(mi.label);
8862 }
8863 }
8864
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008865 final void dumpApplicationMemoryUsage(FileDescriptor fd,
8866 PrintWriter pw, String prefix, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07008867 boolean dumpAll = false;
8868
8869 int opti = 0;
8870 while (opti < args.length) {
8871 String opt = args[opti];
8872 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8873 break;
8874 }
8875 opti++;
8876 if ("-a".equals(opt)) {
8877 dumpAll = true;
8878 } else if ("-h".equals(opt)) {
8879 pw.println("meminfo dump options: [-a] [process]");
8880 pw.println(" -a: include all available information for each process.");
8881 pw.println("If [process] is specified it can be the name or ");
8882 pw.println("pid of a specific process to dump.");
8883 return;
8884 } else {
8885 pw.println("Unknown argument: " + opt + "; use -h for help");
8886 }
8887 }
8888
8889 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008890 if (procs == null) {
8891 return;
8892 }
8893
Dianne Hackborn6447ca32009-04-07 19:50:08 -07008894 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008895 long uptime = SystemClock.uptimeMillis();
8896 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -07008897
8898 if (procs.size() == 1 || isCheckinRequest) {
8899 dumpAll = true;
8900 }
8901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008902 if (isCheckinRequest) {
8903 // short checkin version
8904 pw.println(uptime + "," + realtime);
8905 pw.flush();
8906 } else {
8907 pw.println("Applications Memory Usage (kB):");
8908 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
8909 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008910
Dianne Hackbornb437e092011-08-05 17:50:29 -07008911 String[] innerArgs = new String[args.length-opti];
8912 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
8913
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008914 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
8915 long nativePss=0, dalvikPss=0, otherPss=0;
8916 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
8917
Dianne Hackbornb437e092011-08-05 17:50:29 -07008918 final int[] oomAdj = new int[] {
Dianne Hackborn7d608422011-08-07 16:24:18 -07008919 ProcessList.SYSTEM_ADJ, ProcessList.CORE_SERVER_ADJ, ProcessList.FOREGROUND_APP_ADJ,
8920 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
8921 ProcessList.BACKUP_APP_ADJ, ProcessList.SECONDARY_SERVER_ADJ, ProcessList.HOME_APP_ADJ, ProcessList.EMPTY_APP_ADJ
Dianne Hackbornb437e092011-08-05 17:50:29 -07008922 };
8923 final String[] oomLabel = new String[] {
8924 "System", "Persistent", "Foreground",
8925 "Visible", "Perceptible", "Heavy Weight",
8926 "Backup", "Services", "Home", "Background"
8927 };
8928 long oomPss[] = new long[oomLabel.length];
8929
8930 long totalPss = 0;
8931
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008932 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
8933 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07008935 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
8937 pw.flush();
8938 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008939 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -07008940 if (dumpAll) {
8941 try {
8942 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
8943 } catch (RemoteException e) {
8944 if (!isCheckinRequest) {
8945 pw.println("Got RemoteException!");
8946 pw.flush();
8947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008948 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07008949 } else {
8950 mi = new Debug.MemoryInfo();
8951 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07008953
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008954 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07008955 long myTotalPss = mi.getTotalPss();
8956 totalPss += myTotalPss;
8957 procMems.add(new MemItem(r.processName + " (pid " + r.pid + ")", myTotalPss));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008958
8959 nativePss += mi.nativePss;
8960 dalvikPss += mi.dalvikPss;
8961 otherPss += mi.otherPss;
8962 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
8963 long mem = mi.getOtherPss(j);
8964 miscPss[j] += mem;
8965 otherPss -= mem;
8966 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07008967
8968 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
8969 if (r.setAdj <= oomAdj[oomIndex] || oomIndex == (oomPss.length-1)) {
8970 oomPss[oomIndex] += myTotalPss;
8971 break;
8972 }
8973 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008975 }
8976 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008977
8978 if (!isCheckinRequest && procs.size() > 1) {
8979 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
8980
8981 catMems.add(new MemItem("Native", nativePss));
8982 catMems.add(new MemItem("Dalvik", dalvikPss));
8983 catMems.add(new MemItem("Unknown", otherPss));
8984 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
8985 catMems.add(new MemItem(Debug.MemoryInfo.getOtherLabel(j), miscPss[j]));
8986 }
8987
Dianne Hackbornb437e092011-08-05 17:50:29 -07008988 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
8989 for (int j=0; j<oomPss.length; j++) {
8990 if (oomPss[j] != 0) {
8991 oomMems.add(new MemItem(oomLabel[j], oomPss[j]));
8992 }
8993 }
8994
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07008995 pw.println();
8996 pw.println("Total PSS by process:");
Dianne Hackbornb437e092011-08-05 17:50:29 -07008997 dumpMemItems(pw, " ", procMems, true);
8998 pw.println();
8999 pw.println("Total PSS by OOM adjustment:");
9000 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009001 pw.println();
9002 pw.println("Total PSS by category:");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009003 dumpMemItems(pw, " ", catMems, true);
9004 pw.println();
9005 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" Kb");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009007 }
9008
9009 /**
9010 * Searches array of arguments for the specified string
9011 * @param args array of argument strings
9012 * @param value value to search for
9013 * @return true if the value is contained in the array
9014 */
9015 private static boolean scanArgs(String[] args, String value) {
9016 if (args != null) {
9017 for (String arg : args) {
9018 if (value.equals(arg)) {
9019 return true;
9020 }
9021 }
9022 }
9023 return false;
9024 }
9025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009026 private final void killServicesLocked(ProcessRecord app,
9027 boolean allowRestart) {
9028 // Report disconnected services.
9029 if (false) {
9030 // XXX we are letting the client link to the service for
9031 // death notifications.
9032 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07009033 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009034 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07009035 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009036 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009037 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009038 = r.connections.values().iterator();
9039 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009040 ArrayList<ConnectionRecord> cl = jt.next();
9041 for (int i=0; i<cl.size(); i++) {
9042 ConnectionRecord c = cl.get(i);
9043 if (c.binding.client != app) {
9044 try {
9045 //c.conn.connected(r.className, null);
9046 } catch (Exception e) {
9047 // todo: this should be asynchronous!
9048 Slog.w(TAG, "Exception thrown disconnected servce "
9049 + r.shortName
9050 + " from app " + app.processName, e);
9051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009052 }
9053 }
9054 }
9055 }
9056 }
9057 }
9058 }
9059
9060 // Clean up any connections this application has to other services.
9061 if (app.connections.size() > 0) {
9062 Iterator<ConnectionRecord> it = app.connections.iterator();
9063 while (it.hasNext()) {
9064 ConnectionRecord r = it.next();
9065 removeConnectionLocked(r, app, null);
9066 }
9067 }
9068 app.connections.clear();
9069
9070 if (app.services.size() != 0) {
9071 // Any services running in the application need to be placed
9072 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07009073 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009074 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07009075 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009076 synchronized (sr.stats.getBatteryStats()) {
9077 sr.stats.stopLaunchedLocked();
9078 }
9079 sr.app = null;
9080 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009081 if (mStoppingServices.remove(sr)) {
9082 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
9083 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009084
9085 boolean hasClients = sr.bindings.size() > 0;
9086 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009087 Iterator<IntentBindRecord> bindings
9088 = sr.bindings.values().iterator();
9089 while (bindings.hasNext()) {
9090 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -08009091 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 + ": shouldUnbind=" + b.hasBound);
9093 b.binder = null;
9094 b.requested = b.received = b.hasBound = false;
9095 }
9096 }
9097
Dianne Hackborn070783f2010-12-29 16:46:28 -08009098 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
9099 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009100 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009101 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -08009102 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009103 sr.crashCount, sr.shortName, app.pid);
9104 bringDownServiceLocked(sr, true);
9105 } else if (!allowRestart) {
9106 bringDownServiceLocked(sr, true);
9107 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009108 boolean canceled = scheduleServiceRestartLocked(sr, true);
9109
9110 // Should the service remain running? Note that in the
9111 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -07009112 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009113 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
9114 if (sr.pendingStarts.size() == 0) {
9115 sr.startRequested = false;
9116 if (!hasClients) {
9117 // Whoops, no reason to restart!
9118 bringDownServiceLocked(sr, true);
9119 }
9120 }
9121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009122 }
9123 }
9124
9125 if (!allowRestart) {
9126 app.services.clear();
9127 }
9128 }
9129
Dianne Hackbornde42bb62009-08-05 12:26:15 -07009130 // Make sure we have no more records on the stopping list.
9131 int i = mStoppingServices.size();
9132 while (i > 0) {
9133 i--;
9134 ServiceRecord sr = mStoppingServices.get(i);
9135 if (sr.app == app) {
9136 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009137 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -07009138 }
9139 }
9140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009141 app.executingServices.clear();
9142 }
9143
9144 private final void removeDyingProviderLocked(ProcessRecord proc,
9145 ContentProviderRecord cpr) {
9146 synchronized (cpr) {
9147 cpr.launchingApp = null;
9148 cpr.notifyAll();
9149 }
9150
9151 mProvidersByClass.remove(cpr.info.name);
9152 String names[] = cpr.info.authority.split(";");
9153 for (int j = 0; j < names.length; j++) {
9154 mProvidersByName.remove(names[j]);
9155 }
9156
9157 Iterator<ProcessRecord> cit = cpr.clients.iterator();
9158 while (cit.hasNext()) {
9159 ProcessRecord capp = cit.next();
9160 if (!capp.persistent && capp.thread != null
9161 && capp.pid != 0
9162 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07009163 Slog.i(TAG, "Kill " + capp.processName
9164 + " (pid " + capp.pid + "): provider " + cpr.info.name
9165 + " in dying process " + proc.processName);
9166 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
9167 capp.processName, capp.setAdj, "dying provider " + proc.processName);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07009168 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169 }
9170 }
9171
9172 mLaunchingProviders.remove(cpr);
9173 }
9174
9175 /**
9176 * Main code for cleaning up a process when it has gone away. This is
9177 * called both as a result of the process dying, or directly when stopping
9178 * a process when running in single process mode.
9179 */
9180 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07009181 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009182 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009183 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009184 }
9185
Dianne Hackborn36124872009-10-08 16:22:03 -07009186 mProcessesToGc.remove(app);
9187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009188 // Dismiss any open dialogs.
9189 if (app.crashDialog != null) {
9190 app.crashDialog.dismiss();
9191 app.crashDialog = null;
9192 }
9193 if (app.anrDialog != null) {
9194 app.anrDialog.dismiss();
9195 app.anrDialog = null;
9196 }
9197 if (app.waitDialog != null) {
9198 app.waitDialog.dismiss();
9199 app.waitDialog = null;
9200 }
9201
9202 app.crashing = false;
9203 app.notResponding = false;
9204
9205 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07009206 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009207 app.thread = null;
9208 app.forcingToForeground = null;
9209 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009210 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07009211 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009212 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009213
Dianne Hackborn130b0d22011-07-26 22:07:48 -07009214 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009215
9216 boolean restart = false;
9217
9218 int NL = mLaunchingProviders.size();
9219
9220 // Remove published content providers.
9221 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07009222 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009223 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07009224 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009225 cpr.provider = null;
9226 cpr.app = null;
9227
9228 // See if someone is waiting for this provider... in which
9229 // case we don't remove it, but just let it restart.
9230 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07009231 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009232 for (; i<NL; i++) {
9233 if (mLaunchingProviders.get(i) == cpr) {
9234 restart = true;
9235 break;
9236 }
9237 }
9238 } else {
9239 i = NL;
9240 }
9241
9242 if (i >= NL) {
9243 removeDyingProviderLocked(app, cpr);
9244 NL = mLaunchingProviders.size();
9245 }
9246 }
9247 app.pubProviders.clear();
9248 }
9249
Dianne Hackbornf670ef72009-11-16 13:59:16 -08009250 // Take care of any launching providers waiting for this process.
9251 if (checkAppInLaunchingProvidersLocked(app, false)) {
9252 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009253 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08009254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009255 // Unregister from connected content providers.
9256 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07009257 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009258 while (it.hasNext()) {
9259 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
9260 cpr.clients.remove(app);
9261 }
9262 app.conProviders.clear();
9263 }
9264
Dianne Hackbornde42bb62009-08-05 12:26:15 -07009265 // At this point there may be remaining entries in mLaunchingProviders
9266 // where we were the only one waiting, so they are no longer of use.
9267 // Look for these and clean up if found.
9268 // XXX Commented out for now. Trying to figure out a way to reproduce
9269 // the actual situation to identify what is actually going on.
9270 if (false) {
9271 for (int i=0; i<NL; i++) {
9272 ContentProviderRecord cpr = (ContentProviderRecord)
9273 mLaunchingProviders.get(i);
9274 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
9275 synchronized (cpr) {
9276 cpr.launchingApp = null;
9277 cpr.notifyAll();
9278 }
9279 }
9280 }
9281 }
9282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009283 skipCurrentReceiverLocked(app);
9284
9285 // Unregister any receivers.
9286 if (app.receivers.size() > 0) {
9287 Iterator<ReceiverList> it = app.receivers.iterator();
9288 while (it.hasNext()) {
9289 removeReceiverLocked(it.next());
9290 }
9291 app.receivers.clear();
9292 }
9293
Christopher Tate181fafa2009-05-14 11:12:14 -07009294 // If the app is undergoing backup, tell the backup manager about it
9295 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009296 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -07009297 try {
9298 IBackupManager bm = IBackupManager.Stub.asInterface(
9299 ServiceManager.getService(Context.BACKUP_SERVICE));
9300 bm.agentDisconnected(app.info.packageName);
9301 } catch (RemoteException e) {
9302 // can't happen; backup manager is local
9303 }
9304 }
9305
Jeff Sharkey287bd832011-05-28 19:36:26 -07009306 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009308 // If the caller is restarting this app, then leave it in its
9309 // current lists and let the caller take care of it.
9310 if (restarting) {
9311 return;
9312 }
9313
9314 if (!app.persistent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009315 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009316 "Removing non-persistent process during cleanup: " + app);
9317 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07009318 if (mHeavyWeightProcess == app) {
9319 mHeavyWeightProcess = null;
9320 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
9321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009322 } else if (!app.removed) {
9323 // This app is persistent, so we need to keep its record around.
9324 // If it is not already on the pending app list, add it there
9325 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009326 if (mPersistentStartingProcesses.indexOf(app) < 0) {
9327 mPersistentStartingProcesses.add(app);
9328 restart = true;
9329 }
9330 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009331 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
9332 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009333 mProcessesOnHold.remove(app);
9334
The Android Open Source Project4df24232009-03-05 14:34:35 -08009335 if (app == mHomeProcess) {
9336 mHomeProcess = null;
9337 }
9338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009339 if (restart) {
9340 // We have components that still need to be running in the
9341 // process, so re-launch it.
9342 mProcessNames.put(app.processName, app.info.uid, app);
9343 startProcessLocked(app, "restart", app.processName);
9344 } else if (app.pid > 0 && app.pid != MY_PID) {
9345 // Goodbye!
9346 synchronized (mPidsSelfLocked) {
9347 mPidsSelfLocked.remove(app.pid);
9348 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
9349 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009350 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009351 }
9352 }
9353
Dianne Hackbornf670ef72009-11-16 13:59:16 -08009354 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
9355 // Look through the content providers we are waiting to have launched,
9356 // and if any run in this process then either schedule a restart of
9357 // the process or kill the client waiting for it if this process has
9358 // gone bad.
9359 int NL = mLaunchingProviders.size();
9360 boolean restart = false;
9361 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07009362 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08009363 if (cpr.launchingApp == app) {
9364 if (!alwaysBad && !app.bad) {
9365 restart = true;
9366 } else {
9367 removeDyingProviderLocked(app, cpr);
9368 NL = mLaunchingProviders.size();
9369 }
9370 }
9371 }
9372 return restart;
9373 }
9374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009375 // =========================================================
9376 // SERVICES
9377 // =========================================================
9378
9379 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
9380 ActivityManager.RunningServiceInfo info =
9381 new ActivityManager.RunningServiceInfo();
9382 info.service = r.name;
9383 if (r.app != null) {
9384 info.pid = r.app.pid;
9385 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -07009386 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009387 info.process = r.processName;
9388 info.foreground = r.isForeground;
9389 info.activeSince = r.createTime;
9390 info.started = r.startRequested;
9391 info.clientCount = r.connections.size();
9392 info.crashCount = r.crashCount;
9393 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07009394 if (r.isForeground) {
9395 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
9396 }
9397 if (r.startRequested) {
9398 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
9399 }
Dan Egnor42471dd2010-01-07 17:25:22 -08009400 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -07009401 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
9402 }
9403 if (r.app != null && r.app.persistent) {
9404 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
9405 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009406
9407 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
9408 for (int i=0; i<connl.size(); i++) {
9409 ConnectionRecord conn = connl.get(i);
9410 if (conn.clientLabel != 0) {
9411 info.clientPackage = conn.binding.client.info.packageName;
9412 info.clientLabel = conn.clientLabel;
9413 return info;
9414 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009415 }
9416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009417 return info;
9418 }
9419
9420 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
9421 int flags) {
9422 synchronized (this) {
9423 ArrayList<ActivityManager.RunningServiceInfo> res
9424 = new ArrayList<ActivityManager.RunningServiceInfo>();
9425
9426 if (mServices.size() > 0) {
9427 Iterator<ServiceRecord> it = mServices.values().iterator();
9428 while (it.hasNext() && res.size() < maxNum) {
9429 res.add(makeRunningServiceInfoLocked(it.next()));
9430 }
9431 }
9432
9433 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
9434 ServiceRecord r = mRestartingServices.get(i);
9435 ActivityManager.RunningServiceInfo info =
9436 makeRunningServiceInfoLocked(r);
9437 info.restarting = r.nextRestartTime;
9438 res.add(info);
9439 }
9440
9441 return res;
9442 }
9443 }
9444
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009445 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
9446 synchronized (this) {
9447 ServiceRecord r = mServices.get(name);
9448 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009449 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
9450 for (int i=0; i<conn.size(); i++) {
9451 if (conn.get(i).clientIntent != null) {
9452 return conn.get(i).clientIntent;
9453 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009454 }
9455 }
9456 }
9457 }
9458 return null;
9459 }
9460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009461 private final ServiceRecord findServiceLocked(ComponentName name,
9462 IBinder token) {
9463 ServiceRecord r = mServices.get(name);
9464 return r == token ? r : null;
9465 }
9466
9467 private final class ServiceLookupResult {
9468 final ServiceRecord record;
9469 final String permission;
9470
9471 ServiceLookupResult(ServiceRecord _record, String _permission) {
9472 record = _record;
9473 permission = _permission;
9474 }
9475 };
9476
9477 private ServiceLookupResult findServiceLocked(Intent service,
9478 String resolvedType) {
9479 ServiceRecord r = null;
9480 if (service.getComponent() != null) {
9481 r = mServices.get(service.getComponent());
9482 }
9483 if (r == null) {
9484 Intent.FilterComparison filter = new Intent.FilterComparison(service);
9485 r = mServicesByIntent.get(filter);
9486 }
9487
9488 if (r == null) {
9489 try {
9490 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009491 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009492 service, resolvedType, 0);
9493 ServiceInfo sInfo =
9494 rInfo != null ? rInfo.serviceInfo : null;
9495 if (sInfo == null) {
9496 return null;
9497 }
9498
9499 ComponentName name = new ComponentName(
9500 sInfo.applicationInfo.packageName, sInfo.name);
9501 r = mServices.get(name);
9502 } catch (RemoteException ex) {
9503 // pm is in same process, this will never happen.
9504 }
9505 }
9506 if (r != null) {
9507 int callingPid = Binder.getCallingPid();
9508 int callingUid = Binder.getCallingUid();
9509 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009510 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009511 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009512 if (!r.exported) {
9513 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
9514 + " from pid=" + callingPid
9515 + ", uid=" + callingUid
9516 + " that is not exported from uid " + r.appInfo.uid);
9517 return new ServiceLookupResult(null, "not exported from uid "
9518 + r.appInfo.uid);
9519 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08009520 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009521 + " from pid=" + callingPid
9522 + ", uid=" + callingUid
9523 + " requires " + r.permission);
9524 return new ServiceLookupResult(null, r.permission);
9525 }
9526 return new ServiceLookupResult(r, null);
9527 }
9528 return null;
9529 }
9530
9531 private class ServiceRestarter implements Runnable {
9532 private ServiceRecord mService;
9533
9534 void setService(ServiceRecord service) {
9535 mService = service;
9536 }
9537
9538 public void run() {
9539 synchronized(ActivityManagerService.this) {
9540 performServiceRestartLocked(mService);
9541 }
9542 }
9543 }
9544
9545 private ServiceLookupResult retrieveServiceLocked(Intent service,
9546 String resolvedType, int callingPid, int callingUid) {
9547 ServiceRecord r = null;
9548 if (service.getComponent() != null) {
9549 r = mServices.get(service.getComponent());
9550 }
9551 Intent.FilterComparison filter = new Intent.FilterComparison(service);
9552 r = mServicesByIntent.get(filter);
9553 if (r == null) {
9554 try {
9555 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009556 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -07009557 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009558 ServiceInfo sInfo =
9559 rInfo != null ? rInfo.serviceInfo : null;
9560 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009561 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009562 ": not found");
9563 return null;
9564 }
9565
9566 ComponentName name = new ComponentName(
9567 sInfo.applicationInfo.packageName, sInfo.name);
9568 r = mServices.get(name);
9569 if (r == null) {
9570 filter = new Intent.FilterComparison(service.cloneFilter());
9571 ServiceRestarter res = new ServiceRestarter();
9572 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
9573 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
9574 synchronized (stats) {
9575 ss = stats.getServiceStatsLocked(
9576 sInfo.applicationInfo.uid, sInfo.packageName,
9577 sInfo.name);
9578 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -08009579 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009580 res.setService(r);
9581 mServices.put(name, r);
9582 mServicesByIntent.put(filter, r);
9583
9584 // Make sure this component isn't in the pending list.
9585 int N = mPendingServices.size();
9586 for (int i=0; i<N; i++) {
9587 ServiceRecord pr = mPendingServices.get(i);
9588 if (pr.name.equals(name)) {
9589 mPendingServices.remove(i);
9590 i--;
9591 N--;
9592 }
9593 }
9594 }
9595 } catch (RemoteException ex) {
9596 // pm is in same process, this will never happen.
9597 }
9598 }
9599 if (r != null) {
9600 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009601 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009602 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009603 if (!r.exported) {
9604 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
9605 + " from pid=" + callingPid
9606 + ", uid=" + callingUid
9607 + " that is not exported from uid " + r.appInfo.uid);
9608 return new ServiceLookupResult(null, "not exported from uid "
9609 + r.appInfo.uid);
9610 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08009611 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009612 + " from pid=" + callingPid
9613 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009614 + " requires " + r.permission);
9615 return new ServiceLookupResult(null, r.permission);
9616 }
9617 return new ServiceLookupResult(r, null);
9618 }
9619 return null;
9620 }
9621
Dianne Hackborn287952c2010-09-22 22:34:31 -07009622 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
9623 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
9624 + why + " of " + r + " in app " + r.app);
9625 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
9626 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009627 long now = SystemClock.uptimeMillis();
9628 if (r.executeNesting == 0 && r.app != null) {
9629 if (r.app.executingServices.size() == 0) {
9630 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
9631 msg.obj = r.app;
9632 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
9633 }
9634 r.app.executingServices.add(r);
9635 }
9636 r.executeNesting++;
9637 r.executingStart = now;
9638 }
9639
9640 private final void sendServiceArgsLocked(ServiceRecord r,
9641 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009642 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009643 if (N == 0) {
9644 return;
9645 }
9646
Dianne Hackborn39792d22010-08-19 18:01:52 -07009647 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009648 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -07009649 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009650 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
9651 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -08009652 if (si.intent == null && N > 1) {
9653 // If somehow we got a dummy null intent in the middle,
9654 // then skip it. DO NOT skip a null intent when it is
9655 // the only one in the list -- this is to support the
9656 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009657 continue;
9658 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07009659 si.deliveredTime = SystemClock.uptimeMillis();
9660 r.deliveredStarts.add(si);
9661 si.deliveryCount++;
Dianne Hackborn3a28f222011-03-01 12:25:54 -08009662 if (si.targetPermissionUid >= 0 && si.intent != null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07009663 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -07009664 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07009665 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009666 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009667 if (!oomAdjusted) {
9668 oomAdjusted = true;
9669 updateOomAdjLocked(r.app);
9670 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009671 int flags = 0;
9672 if (si.deliveryCount > 0) {
9673 flags |= Service.START_FLAG_RETRY;
9674 }
9675 if (si.doneExecutingCount > 0) {
9676 flags |= Service.START_FLAG_REDELIVERY;
9677 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07009678 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009679 } catch (RemoteException e) {
9680 // Remote process gone... we'll let the normal cleanup take
9681 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009682 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009683 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009684 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009685 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009686 break;
9687 }
9688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009689 }
9690
9691 private final boolean requestServiceBindingLocked(ServiceRecord r,
9692 IntentBindRecord i, boolean rebind) {
9693 if (r.app == null || r.app.thread == null) {
9694 // If service is not currently running, can't yet bind.
9695 return false;
9696 }
9697 if ((!i.requested || rebind) && i.apps.size() > 0) {
9698 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009699 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009700 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
9701 if (!rebind) {
9702 i.requested = true;
9703 }
9704 i.hasBound = true;
9705 i.doRebind = false;
9706 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009707 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009708 return false;
9709 }
9710 }
9711 return true;
9712 }
9713
9714 private final void requestServiceBindingsLocked(ServiceRecord r) {
9715 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
9716 while (bindings.hasNext()) {
9717 IntentBindRecord i = bindings.next();
9718 if (!requestServiceBindingLocked(r, i, false)) {
9719 break;
9720 }
9721 }
9722 }
9723
9724 private final void realStartServiceLocked(ServiceRecord r,
9725 ProcessRecord app) throws RemoteException {
9726 if (app.thread == null) {
9727 throw new RemoteException();
9728 }
9729
9730 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -07009731 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009732
9733 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009734 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009735 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009736
9737 boolean created = false;
9738 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07009739 mStringBuilder.setLength(0);
9740 r.intent.getIntent().toShortString(mStringBuilder, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -08009741 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009742 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -07009743 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009744 synchronized (r.stats.getBatteryStats()) {
9745 r.stats.startLaunchedLocked();
9746 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07009747 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04009748 app.thread.scheduleCreateService(r, r.serviceInfo,
9749 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009750 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009751 created = true;
9752 } finally {
9753 if (!created) {
9754 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009755 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009756 }
9757 }
9758
9759 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009760
9761 // If the service is in the started state, and there are no
9762 // pending arguments, then fake up one so its onStartCommand() will
9763 // be called.
9764 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07009765 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
9766 null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009767 }
9768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009769 sendServiceArgsLocked(r, true);
9770 }
9771
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009772 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
9773 boolean allowCancel) {
9774 boolean canceled = false;
9775
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009776 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009777 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -07009778 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009779
Dianne Hackborn070783f2010-12-29 16:46:28 -08009780 if ((r.serviceInfo.applicationInfo.flags
9781 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
9782 minDuration /= 4;
9783 }
9784
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009785 // Any delivered but not yet finished starts should be put back
9786 // on the pending list.
9787 final int N = r.deliveredStarts.size();
9788 if (N > 0) {
9789 for (int i=N-1; i>=0; i--) {
9790 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -07009791 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009792 if (si.intent == null) {
9793 // We'll generate this again if needed.
9794 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
9795 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
9796 r.pendingStarts.add(0, si);
9797 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
9798 dur *= 2;
9799 if (minDuration < dur) minDuration = dur;
9800 if (resetTime < dur) resetTime = dur;
9801 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009802 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009803 + r.name);
9804 canceled = true;
9805 }
9806 }
9807 r.deliveredStarts.clear();
9808 }
9809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009810 r.totalRestartCount++;
9811 if (r.restartDelay == 0) {
9812 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009813 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009814 } else {
9815 // If it has been a "reasonably long time" since the service
9816 // was started, then reset our restart duration back to
9817 // the beginning, so we don't infinitely increase the duration
9818 // on a service that just occasionally gets killed (which is
9819 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009820 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009821 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009822 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009823 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -08009824 if ((r.serviceInfo.applicationInfo.flags
9825 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
9826 // Services in peristent processes will restart much more
9827 // quickly, since they are pretty important. (Think SystemUI).
9828 r.restartDelay += minDuration/2;
9829 } else {
9830 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
9831 if (r.restartDelay < minDuration) {
9832 r.restartDelay = minDuration;
9833 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009835 }
9836 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009837
9838 r.nextRestartTime = now + r.restartDelay;
9839
9840 // Make sure that we don't end up restarting a bunch of services
9841 // all at the same time.
9842 boolean repeat;
9843 do {
9844 repeat = false;
9845 for (int i=mRestartingServices.size()-1; i>=0; i--) {
9846 ServiceRecord r2 = mRestartingServices.get(i);
9847 if (r2 != r && r.nextRestartTime
9848 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
9849 && r.nextRestartTime
9850 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
9851 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
9852 r.restartDelay = r.nextRestartTime - now;
9853 repeat = true;
9854 break;
9855 }
9856 }
9857 } while (repeat);
9858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009859 if (!mRestartingServices.contains(r)) {
9860 mRestartingServices.add(r);
9861 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009862
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009863 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009865 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009866 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009867 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -08009868 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009869 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -08009870 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009871 r.shortName, r.restartDelay);
9872
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009873 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009874 }
9875
9876 final void performServiceRestartLocked(ServiceRecord r) {
9877 if (!mRestartingServices.contains(r)) {
9878 return;
9879 }
9880 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
9881 }
9882
9883 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
9884 if (r.restartDelay == 0) {
9885 return false;
9886 }
9887 r.resetRestartCounter();
9888 mRestartingServices.remove(r);
9889 mHandler.removeCallbacks(r.restarter);
9890 return true;
9891 }
9892
9893 private final boolean bringUpServiceLocked(ServiceRecord r,
9894 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009895 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009896 //r.dump(" ");
9897
Dianne Hackborn36124872009-10-08 16:22:03 -07009898 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009899 sendServiceArgsLocked(r, false);
9900 return true;
9901 }
9902
9903 if (!whileRestarting && r.restartDelay > 0) {
9904 // If waiting for a restart, then do nothing.
9905 return true;
9906 }
9907
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009908 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009909
Dianne Hackbornde42bb62009-08-05 12:26:15 -07009910 // We are now bringing the service up, so no longer in the
9911 // restarting state.
9912 mRestartingServices.remove(r);
9913
Dianne Hackborne7f97212011-02-24 14:40:20 -08009914 // Service is now being launched, its package can't be stopped.
9915 try {
9916 AppGlobals.getPackageManager().setPackageStoppedState(
9917 r.packageName, false);
9918 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08009919 } catch (IllegalArgumentException e) {
9920 Slog.w(TAG, "Failed trying to unstop package "
9921 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08009922 }
9923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009924 final String appName = r.processName;
9925 ProcessRecord app = getProcessRecordLocked(appName, r.appInfo.uid);
9926 if (app != null && app.thread != null) {
9927 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -07009928 app.addPackage(r.appInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009929 realStartServiceLocked(r, app);
9930 return true;
9931 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009932 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009933 }
9934
9935 // If a dead object exception was thrown -- fall through to
9936 // restart the application.
9937 }
9938
Dianne Hackborn36124872009-10-08 16:22:03 -07009939 // Not running -- get it started, and enqueue this service record
9940 // to be executed when the app comes up.
9941 if (startProcessLocked(appName, r.appInfo, true, intentFlags,
9942 "service", r.name, false) == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009943 Slog.w(TAG, "Unable to launch app "
Dianne Hackborn36124872009-10-08 16:22:03 -07009944 + r.appInfo.packageName + "/"
9945 + r.appInfo.uid + " for service "
9946 + r.intent.getIntent() + ": process is bad");
9947 bringDownServiceLocked(r, true);
9948 return false;
9949 }
9950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009951 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009952 mPendingServices.add(r);
9953 }
Dianne Hackborn36124872009-10-08 16:22:03 -07009954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009955 return true;
9956 }
9957
9958 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009959 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009960 //r.dump(" ");
9961
9962 // Does it still need to run?
9963 if (!force && r.startRequested) {
9964 return;
9965 }
9966 if (r.connections.size() > 0) {
9967 if (!force) {
9968 // XXX should probably keep a count of the number of auto-create
9969 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009970 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009971 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009972 ArrayList<ConnectionRecord> cr = it.next();
9973 for (int i=0; i<cr.size(); i++) {
9974 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
9975 return;
9976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009977 }
9978 }
9979 }
9980
9981 // Report to all of the connections that the service is no longer
9982 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009983 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009984 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009985 ArrayList<ConnectionRecord> c = it.next();
9986 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07009987 ConnectionRecord cr = c.get(i);
9988 // There is still a connection to the service that is
9989 // being brought down. Mark it as dead.
9990 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009991 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07009992 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009993 } catch (Exception e) {
9994 Slog.w(TAG, "Failure disconnecting service " + r.name +
9995 " to connection " + c.get(i).conn.asBinder() +
9996 " (in " + c.get(i).binding.client.processName + ")", e);
9997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009998 }
9999 }
10000 }
10001
10002 // Tell the service that it has been unbound.
10003 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
10004 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
10005 while (it.hasNext()) {
10006 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010007 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010008 + ": hasBound=" + ibr.hasBound);
10009 if (r.app != null && r.app.thread != null && ibr.hasBound) {
10010 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010011 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010012 updateOomAdjLocked(r.app);
10013 ibr.hasBound = false;
10014 r.app.thread.scheduleUnbindService(r,
10015 ibr.intent.getIntent());
10016 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010017 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010018 + r.shortName, e);
10019 serviceDoneExecutingLocked(r, true);
10020 }
10021 }
10022 }
10023 }
10024
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010025 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010026 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010027 System.identityHashCode(r), r.shortName,
10028 (r.app != null) ? r.app.pid : -1);
10029
10030 mServices.remove(r.name);
10031 mServicesByIntent.remove(r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010032 r.totalRestartCount = 0;
10033 unscheduleServiceRestartLocked(r);
10034
10035 // Also make sure it is not on the pending list.
10036 int N = mPendingServices.size();
10037 for (int i=0; i<N; i++) {
10038 if (mPendingServices.get(i) == r) {
10039 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010040 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010041 i--;
10042 N--;
10043 }
10044 }
10045
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010046 r.cancelNotification();
10047 r.isForeground = false;
10048 r.foregroundId = 0;
10049 r.foregroundNoti = null;
10050
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010051 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070010052 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010053 r.pendingStarts.clear();
10054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010055 if (r.app != null) {
10056 synchronized (r.stats.getBatteryStats()) {
10057 r.stats.stopLaunchedLocked();
10058 }
10059 r.app.services.remove(r);
10060 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010061 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010062 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010063 mStoppingServices.add(r);
10064 updateOomAdjLocked(r.app);
10065 r.app.thread.scheduleStopService(r);
10066 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010067 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010068 + r.shortName, e);
10069 serviceDoneExecutingLocked(r, true);
10070 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010071 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010072 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010073 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010074 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010075 }
10076 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010077 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010078 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010079 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080010080
10081 if (r.bindings.size() > 0) {
10082 r.bindings.clear();
10083 }
10084
10085 if (r.restarter instanceof ServiceRestarter) {
10086 ((ServiceRestarter)r.restarter).setService(null);
10087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010088 }
10089
10090 ComponentName startServiceLocked(IApplicationThread caller,
10091 Intent service, String resolvedType,
10092 int callingPid, int callingUid) {
10093 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010094 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010095 + " type=" + resolvedType + " args=" + service.getExtras());
10096
10097 if (caller != null) {
10098 final ProcessRecord callerApp = getRecordForAppLocked(caller);
10099 if (callerApp == null) {
10100 throw new SecurityException(
10101 "Unable to find app for caller " + caller
10102 + " (pid=" + Binder.getCallingPid()
10103 + ") when starting service " + service);
10104 }
10105 }
10106
10107 ServiceLookupResult res =
10108 retrieveServiceLocked(service, resolvedType,
10109 callingPid, callingUid);
10110 if (res == null) {
10111 return null;
10112 }
10113 if (res.record == null) {
10114 return new ComponentName("!", res.permission != null
10115 ? res.permission : "private to package");
10116 }
10117 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -070010118 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
10119 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010120 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010121 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010122 }
10123 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010124 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010125 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn39792d22010-08-19 18:01:52 -070010126 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010127 r.lastActivity = SystemClock.uptimeMillis();
10128 synchronized (r.stats.getBatteryStats()) {
10129 r.stats.startRunningLocked();
10130 }
10131 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
10132 return new ComponentName("!", "Service process is bad");
10133 }
10134 return r.name;
10135 }
10136 }
10137
10138 public ComponentName startService(IApplicationThread caller, Intent service,
10139 String resolvedType) {
10140 // Refuse possible leaked file descriptors
10141 if (service != null && service.hasFileDescriptors() == true) {
10142 throw new IllegalArgumentException("File descriptors passed in Intent");
10143 }
10144
10145 synchronized(this) {
10146 final int callingPid = Binder.getCallingPid();
10147 final int callingUid = Binder.getCallingUid();
10148 final long origId = Binder.clearCallingIdentity();
10149 ComponentName res = startServiceLocked(caller, service,
10150 resolvedType, callingPid, callingUid);
10151 Binder.restoreCallingIdentity(origId);
10152 return res;
10153 }
10154 }
10155
10156 ComponentName startServiceInPackage(int uid,
10157 Intent service, String resolvedType) {
10158 synchronized(this) {
10159 final long origId = Binder.clearCallingIdentity();
10160 ComponentName res = startServiceLocked(null, service,
10161 resolvedType, -1, uid);
10162 Binder.restoreCallingIdentity(origId);
10163 return res;
10164 }
10165 }
10166
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010167 private void stopServiceLocked(ServiceRecord service) {
10168 synchronized (service.stats.getBatteryStats()) {
10169 service.stats.stopRunningLocked();
10170 }
10171 service.startRequested = false;
10172 service.callStart = false;
10173 bringDownServiceLocked(service, false);
10174 }
10175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010176 public int stopService(IApplicationThread caller, Intent service,
10177 String resolvedType) {
10178 // Refuse possible leaked file descriptors
10179 if (service != null && service.hasFileDescriptors() == true) {
10180 throw new IllegalArgumentException("File descriptors passed in Intent");
10181 }
10182
10183 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010184 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010185 + " type=" + resolvedType);
10186
10187 final ProcessRecord callerApp = getRecordForAppLocked(caller);
10188 if (caller != null && callerApp == null) {
10189 throw new SecurityException(
10190 "Unable to find app for caller " + caller
10191 + " (pid=" + Binder.getCallingPid()
10192 + ") when stopping service " + service);
10193 }
10194
10195 // If this service is active, make sure it is stopped.
10196 ServiceLookupResult r = findServiceLocked(service, resolvedType);
10197 if (r != null) {
10198 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010199 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010200 try {
10201 stopServiceLocked(r.record);
10202 } finally {
10203 Binder.restoreCallingIdentity(origId);
10204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010205 return 1;
10206 }
10207 return -1;
10208 }
10209 }
10210
10211 return 0;
10212 }
10213
10214 public IBinder peekService(Intent service, String resolvedType) {
10215 // Refuse possible leaked file descriptors
10216 if (service != null && service.hasFileDescriptors() == true) {
10217 throw new IllegalArgumentException("File descriptors passed in Intent");
10218 }
10219
10220 IBinder ret = null;
10221
10222 synchronized(this) {
10223 ServiceLookupResult r = findServiceLocked(service, resolvedType);
10224
10225 if (r != null) {
10226 // r.record is null if findServiceLocked() failed the caller permission check
10227 if (r.record == null) {
10228 throw new SecurityException(
10229 "Permission Denial: Accessing service " + r.record.name
10230 + " from pid=" + Binder.getCallingPid()
10231 + ", uid=" + Binder.getCallingUid()
10232 + " requires " + r.permission);
10233 }
10234 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
10235 if (ib != null) {
10236 ret = ib.binder;
10237 }
10238 }
10239 }
10240
10241 return ret;
10242 }
10243
10244 public boolean stopServiceToken(ComponentName className, IBinder token,
10245 int startId) {
10246 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010247 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010248 + " " + token + " startId=" + startId);
10249 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010250 if (r != null) {
10251 if (startId >= 0) {
10252 // Asked to only stop if done with all work. Note that
10253 // to avoid leaks, we will take this as dropping all
10254 // start items up to and including this one.
10255 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
10256 if (si != null) {
10257 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010258 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
10259 cur.removeUriPermissionsLocked();
10260 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010261 break;
10262 }
10263 }
10264 }
10265
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010266 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010267 return false;
10268 }
10269
10270 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010271 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010272 + " is last, but have " + r.deliveredStarts.size()
10273 + " remaining args");
10274 }
10275 }
10276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010277 synchronized (r.stats.getBatteryStats()) {
10278 r.stats.stopRunningLocked();
10279 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010280 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010281 }
10282 final long origId = Binder.clearCallingIdentity();
10283 bringDownServiceLocked(r, false);
10284 Binder.restoreCallingIdentity(origId);
10285 return true;
10286 }
10287 }
10288 return false;
10289 }
10290
10291 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010292 int id, Notification notification, boolean removeNotification) {
10293 final long origId = Binder.clearCallingIdentity();
10294 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010295 synchronized(this) {
10296 ServiceRecord r = findServiceLocked(className, token);
10297 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010298 if (id != 0) {
10299 if (notification == null) {
10300 throw new IllegalArgumentException("null notification");
10301 }
10302 if (r.foregroundId != id) {
10303 r.cancelNotification();
10304 r.foregroundId = id;
10305 }
10306 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
10307 r.foregroundNoti = notification;
10308 r.isForeground = true;
10309 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010310 if (r.app != null) {
10311 updateServiceForegroundLocked(r.app, true);
10312 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010313 } else {
10314 if (r.isForeground) {
10315 r.isForeground = false;
10316 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010317 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010318 updateServiceForegroundLocked(r.app, true);
10319 }
10320 }
10321 if (removeNotification) {
10322 r.cancelNotification();
10323 r.foregroundId = 0;
10324 r.foregroundNoti = null;
10325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010326 }
10327 }
10328 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010329 } finally {
10330 Binder.restoreCallingIdentity(origId);
10331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010332 }
10333
10334 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
10335 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010336 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010337 if (sr.isForeground) {
10338 anyForeground = true;
10339 break;
10340 }
10341 }
10342 if (anyForeground != proc.foregroundServices) {
10343 proc.foregroundServices = anyForeground;
10344 if (oomAdj) {
10345 updateOomAdjLocked();
10346 }
10347 }
10348 }
10349
10350 public int bindService(IApplicationThread caller, IBinder token,
10351 Intent service, String resolvedType,
10352 IServiceConnection connection, int flags) {
10353 // Refuse possible leaked file descriptors
10354 if (service != null && service.hasFileDescriptors() == true) {
10355 throw new IllegalArgumentException("File descriptors passed in Intent");
10356 }
10357
10358 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010359 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010360 + " type=" + resolvedType + " conn=" + connection.asBinder()
10361 + " flags=0x" + Integer.toHexString(flags));
10362 final ProcessRecord callerApp = getRecordForAppLocked(caller);
10363 if (callerApp == null) {
10364 throw new SecurityException(
10365 "Unable to find app for caller " + caller
10366 + " (pid=" + Binder.getCallingPid()
10367 + ") when binding service " + service);
10368 }
10369
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010370 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010371 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010372 activity = mMainStack.isInStackLocked(token);
10373 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010374 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010375 return 0;
10376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010377 }
10378
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010379 int clientLabel = 0;
10380 PendingIntent clientIntent = null;
10381
10382 if (callerApp.info.uid == Process.SYSTEM_UID) {
10383 // Hacky kind of thing -- allow system stuff to tell us
10384 // what they are, so we can report this elsewhere for
10385 // others to know why certain services are running.
10386 try {
10387 clientIntent = (PendingIntent)service.getParcelableExtra(
10388 Intent.EXTRA_CLIENT_INTENT);
10389 } catch (RuntimeException e) {
10390 }
10391 if (clientIntent != null) {
10392 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
10393 if (clientLabel != 0) {
10394 // There are no useful extras in the intent, trash them.
10395 // System code calling with this stuff just needs to know
10396 // this will happen.
10397 service = service.cloneFilter();
10398 }
10399 }
10400 }
10401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010402 ServiceLookupResult res =
10403 retrieveServiceLocked(service, resolvedType,
10404 Binder.getCallingPid(), Binder.getCallingUid());
10405 if (res == null) {
10406 return 0;
10407 }
10408 if (res.record == null) {
10409 return -1;
10410 }
10411 ServiceRecord s = res.record;
10412
10413 final long origId = Binder.clearCallingIdentity();
10414
10415 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010416 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010417 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010418 }
10419
10420 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
10421 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010422 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010423
10424 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010425 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
10426 if (clist == null) {
10427 clist = new ArrayList<ConnectionRecord>();
10428 s.connections.put(binder, clist);
10429 }
10430 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010431 b.connections.add(c);
10432 if (activity != null) {
10433 if (activity.connections == null) {
10434 activity.connections = new HashSet<ConnectionRecord>();
10435 }
10436 activity.connections.add(c);
10437 }
10438 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010439 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
10440 b.client.hasAboveClient = true;
10441 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010442 clist = mServiceConnections.get(binder);
10443 if (clist == null) {
10444 clist = new ArrayList<ConnectionRecord>();
10445 mServiceConnections.put(binder, clist);
10446 }
10447 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010448
10449 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
10450 s.lastActivity = SystemClock.uptimeMillis();
10451 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
10452 return 0;
10453 }
10454 }
10455
10456 if (s.app != null) {
10457 // This could have made the service more important.
10458 updateOomAdjLocked(s.app);
10459 }
10460
Joe Onorato8a9b2202010-02-26 18:56:32 -080010461 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010462 + ": received=" + b.intent.received
10463 + " apps=" + b.intent.apps.size()
10464 + " doRebind=" + b.intent.doRebind);
10465
10466 if (s.app != null && b.intent.received) {
10467 // Service is already running, so we can immediately
10468 // publish the connection.
10469 try {
10470 c.conn.connected(s.name, b.intent.binder);
10471 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010472 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010473 + " to connection " + c.conn.asBinder()
10474 + " (in " + c.binding.client.processName + ")", e);
10475 }
10476
10477 // If this is the first app connected back to this binding,
10478 // and the service had previously asked to be told when
10479 // rebound, then do so.
10480 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
10481 requestServiceBindingLocked(s, b.intent, true);
10482 }
10483 } else if (!b.intent.requested) {
10484 requestServiceBindingLocked(s, b.intent, false);
10485 }
10486
10487 Binder.restoreCallingIdentity(origId);
10488 }
10489
10490 return 1;
10491 }
10492
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070010493 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010494 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010495 IBinder binder = c.conn.asBinder();
10496 AppBindRecord b = c.binding;
10497 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010498 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
10499 if (clist != null) {
10500 clist.remove(c);
10501 if (clist.size() == 0) {
10502 s.connections.remove(binder);
10503 }
10504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010505 b.connections.remove(c);
10506 if (c.activity != null && c.activity != skipAct) {
10507 if (c.activity.connections != null) {
10508 c.activity.connections.remove(c);
10509 }
10510 }
10511 if (b.client != skipApp) {
10512 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010513 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
10514 b.client.updateHasAboveClientLocked();
10515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010516 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010517 clist = mServiceConnections.get(binder);
10518 if (clist != null) {
10519 clist.remove(c);
10520 if (clist.size() == 0) {
10521 mServiceConnections.remove(binder);
10522 }
10523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010524
10525 if (b.connections.size() == 0) {
10526 b.intent.apps.remove(b.client);
10527 }
10528
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010529 if (!c.serviceDead) {
10530 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
10531 + ": shouldUnbind=" + b.intent.hasBound);
10532 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
10533 && b.intent.hasBound) {
10534 try {
10535 bumpServiceExecutingLocked(s, "unbind");
10536 updateOomAdjLocked(s.app);
10537 b.intent.hasBound = false;
10538 // Assume the client doesn't want to know about a rebind;
10539 // we will deal with that later if it asks for one.
10540 b.intent.doRebind = false;
10541 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
10542 } catch (Exception e) {
10543 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
10544 serviceDoneExecutingLocked(s, true);
10545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010546 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010547
10548 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
10549 bringDownServiceLocked(s, false);
10550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010551 }
10552 }
10553
10554 public boolean unbindService(IServiceConnection connection) {
10555 synchronized (this) {
10556 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010557 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010558 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
10559 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010560 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010561 + connection.asBinder());
10562 return false;
10563 }
10564
10565 final long origId = Binder.clearCallingIdentity();
10566
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010567 while (clist.size() > 0) {
10568 ConnectionRecord r = clist.get(0);
10569 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010570
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010571 if (r.binding.service.app != null) {
10572 // This could have made the service less important.
10573 updateOomAdjLocked(r.binding.service.app);
10574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010575 }
10576
10577 Binder.restoreCallingIdentity(origId);
10578 }
10579
10580 return true;
10581 }
10582
10583 public void publishService(IBinder token, Intent intent, IBinder service) {
10584 // Refuse possible leaked file descriptors
10585 if (intent != null && intent.hasFileDescriptors() == true) {
10586 throw new IllegalArgumentException("File descriptors passed in Intent");
10587 }
10588
10589 synchronized(this) {
10590 if (!(token instanceof ServiceRecord)) {
10591 throw new IllegalArgumentException("Invalid service token");
10592 }
10593 ServiceRecord r = (ServiceRecord)token;
10594
10595 final long origId = Binder.clearCallingIdentity();
10596
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010597 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010598 + " " + intent + ": " + service);
10599 if (r != null) {
10600 Intent.FilterComparison filter
10601 = new Intent.FilterComparison(intent);
10602 IntentBindRecord b = r.bindings.get(filter);
10603 if (b != null && !b.received) {
10604 b.binder = service;
10605 b.requested = true;
10606 b.received = true;
10607 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010608 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010609 = r.connections.values().iterator();
10610 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010611 ArrayList<ConnectionRecord> clist = it.next();
10612 for (int i=0; i<clist.size(); i++) {
10613 ConnectionRecord c = clist.get(i);
10614 if (!filter.equals(c.binding.intent.intent)) {
10615 if (DEBUG_SERVICE) Slog.v(
10616 TAG, "Not publishing to: " + c);
10617 if (DEBUG_SERVICE) Slog.v(
10618 TAG, "Bound intent: " + c.binding.intent.intent);
10619 if (DEBUG_SERVICE) Slog.v(
10620 TAG, "Published intent: " + intent);
10621 continue;
10622 }
10623 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
10624 try {
10625 c.conn.connected(r.name, service);
10626 } catch (Exception e) {
10627 Slog.w(TAG, "Failure sending service " + r.name +
10628 " to connection " + c.conn.asBinder() +
10629 " (in " + c.binding.client.processName + ")", e);
10630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010631 }
10632 }
10633 }
10634 }
10635
10636 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
10637
10638 Binder.restoreCallingIdentity(origId);
10639 }
10640 }
10641 }
10642
10643 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10644 // Refuse possible leaked file descriptors
10645 if (intent != null && intent.hasFileDescriptors() == true) {
10646 throw new IllegalArgumentException("File descriptors passed in Intent");
10647 }
10648
10649 synchronized(this) {
10650 if (!(token instanceof ServiceRecord)) {
10651 throw new IllegalArgumentException("Invalid service token");
10652 }
10653 ServiceRecord r = (ServiceRecord)token;
10654
10655 final long origId = Binder.clearCallingIdentity();
10656
10657 if (r != null) {
10658 Intent.FilterComparison filter
10659 = new Intent.FilterComparison(intent);
10660 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010661 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010662 + " at " + b + ": apps="
10663 + (b != null ? b.apps.size() : 0));
10664 if (b != null) {
10665 if (b.apps.size() > 0) {
10666 // Applications have already bound since the last
10667 // unbind, so just rebind right here.
10668 requestServiceBindingLocked(r, b, true);
10669 } else {
10670 // Note to tell the service the next time there is
10671 // a new client.
10672 b.doRebind = true;
10673 }
10674 }
10675
10676 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
10677
10678 Binder.restoreCallingIdentity(origId);
10679 }
10680 }
10681 }
10682
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010683 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010684 synchronized(this) {
10685 if (!(token instanceof ServiceRecord)) {
10686 throw new IllegalArgumentException("Invalid service token");
10687 }
10688 ServiceRecord r = (ServiceRecord)token;
10689 boolean inStopping = mStoppingServices.contains(token);
10690 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010691 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010692 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010693 + " with incorrect token: given " + token
10694 + ", expected " + r);
10695 return;
10696 }
10697
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010698 if (type == 1) {
10699 // This is a call from a service start... take care of
10700 // book-keeping.
10701 r.callStart = true;
10702 switch (res) {
10703 case Service.START_STICKY_COMPATIBILITY:
10704 case Service.START_STICKY: {
10705 // We are done with the associated start arguments.
10706 r.findDeliveredStart(startId, true);
10707 // Don't stop if killed.
10708 r.stopIfKilled = false;
10709 break;
10710 }
10711 case Service.START_NOT_STICKY: {
10712 // We are done with the associated start arguments.
10713 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010714 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010715 // There is no more work, and this service
10716 // doesn't want to hang around if killed.
10717 r.stopIfKilled = true;
10718 }
10719 break;
10720 }
10721 case Service.START_REDELIVER_INTENT: {
10722 // We'll keep this item until they explicitly
10723 // call stop for it, but keep track of the fact
10724 // that it was delivered.
10725 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
10726 if (si != null) {
10727 si.deliveryCount = 0;
10728 si.doneExecutingCount++;
10729 // Don't stop if killed.
10730 r.stopIfKilled = true;
10731 }
10732 break;
10733 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010734 case Service.START_TASK_REMOVED_COMPLETE: {
10735 // Special processing for onTaskRemoved(). Don't
10736 // impact normal onStartCommand() processing.
10737 r.findDeliveredStart(startId, true);
10738 break;
10739 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010740 default:
10741 throw new IllegalArgumentException(
10742 "Unknown service start result: " + res);
10743 }
10744 if (res == Service.START_STICKY_COMPATIBILITY) {
10745 r.callStart = false;
10746 }
10747 }
10748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010749 final long origId = Binder.clearCallingIdentity();
10750 serviceDoneExecutingLocked(r, inStopping);
10751 Binder.restoreCallingIdentity(origId);
10752 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010753 Slog.w(TAG, "Done executing unknown service from pid "
10754 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010755 }
10756 }
10757 }
10758
10759 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010760 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
10761 + ": nesting=" + r.executeNesting
10762 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010763 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010764 r.executeNesting--;
10765 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010766 if (DEBUG_SERVICE) Slog.v(TAG,
10767 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010768 r.app.executingServices.remove(r);
10769 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010770 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
10771 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010772 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
10773 }
10774 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010775 if (DEBUG_SERVICE) Slog.v(TAG,
10776 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010777 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020010778 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010779 }
10780 updateOomAdjLocked(r.app);
10781 }
10782 }
10783
10784 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010785 String anrMessage = null;
10786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010787 synchronized(this) {
10788 if (proc.executingServices.size() == 0 || proc.thread == null) {
10789 return;
10790 }
10791 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
10792 Iterator<ServiceRecord> it = proc.executingServices.iterator();
10793 ServiceRecord timeout = null;
10794 long nextTime = 0;
10795 while (it.hasNext()) {
10796 ServiceRecord sr = it.next();
10797 if (sr.executingStart < maxTime) {
10798 timeout = sr;
10799 break;
10800 }
10801 if (sr.executingStart > nextTime) {
10802 nextTime = sr.executingStart;
10803 }
10804 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010805 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010806 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010807 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010808 } else {
10809 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10810 msg.obj = proc;
10811 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
10812 }
10813 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010814
10815 if (anrMessage != null) {
10816 appNotResponding(proc, null, null, anrMessage);
10817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010818 }
10819
10820 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010821 // BACKUP AND RESTORE
10822 // =========================================================
10823
10824 // Cause the target app to be launched if necessary and its backup agent
10825 // instantiated. The backup agent will invoke backupAgentCreated() on the
10826 // activity manager to announce its creation.
10827 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010828 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010829 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10830
10831 synchronized(this) {
10832 // !!! TODO: currently no check here that we're already bound
10833 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10834 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10835 synchronized (stats) {
10836 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10837 }
10838
Dianne Hackborne7f97212011-02-24 14:40:20 -080010839 // Backup agent is now in use, its package can't be stopped.
10840 try {
10841 AppGlobals.getPackageManager().setPackageStoppedState(
10842 app.packageName, false);
10843 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010844 } catch (IllegalArgumentException e) {
10845 Slog.w(TAG, "Failed trying to unstop package "
10846 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010847 }
10848
Christopher Tate181fafa2009-05-14 11:12:14 -070010849 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070010850 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
10851 ? new ComponentName(app.packageName, app.backupAgentName)
10852 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070010853 // startProcessLocked() returns existing proc's record if it's already running
10854 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070010855 false, 0, "backup", hostingName, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010856 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010857 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010858 return false;
10859 }
10860
10861 r.app = proc;
10862 mBackupTarget = r;
10863 mBackupAppName = app.packageName;
10864
Christopher Tate6fa95972009-06-05 18:43:55 -070010865 // Try not to kill the process during backup
10866 updateOomAdjLocked(proc);
10867
Christopher Tate181fafa2009-05-14 11:12:14 -070010868 // If the process is already attached, schedule the creation of the backup agent now.
10869 // If it is not yet live, this will be done when it attaches to the framework.
10870 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010871 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010872 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010873 proc.thread.scheduleCreateBackupAgent(app,
10874 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010875 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070010876 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070010877 }
10878 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010879 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070010880 }
10881 // Invariants: at this point, the target app process exists and the application
10882 // is either already running or in the process of coming up. mBackupTarget and
10883 // mBackupAppName describe the app, so that when it binds back to the AM we
10884 // know that it's scheduled for a backup-agent operation.
10885 }
10886
10887 return true;
10888 }
10889
10890 // A backup agent has just come up
10891 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010892 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070010893 + " = " + agent);
10894
10895 synchronized(this) {
10896 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010897 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070010898 return;
10899 }
Dianne Hackborn06740692010-09-22 22:46:21 -070010900 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010901
Dianne Hackborn06740692010-09-22 22:46:21 -070010902 long oldIdent = Binder.clearCallingIdentity();
10903 try {
10904 IBackupManager bm = IBackupManager.Stub.asInterface(
10905 ServiceManager.getService(Context.BACKUP_SERVICE));
10906 bm.agentConnected(agentPackageName, agent);
10907 } catch (RemoteException e) {
10908 // can't happen; the backup manager service is local
10909 } catch (Exception e) {
10910 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
10911 e.printStackTrace();
10912 } finally {
10913 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070010914 }
10915 }
10916
10917 // done with this agent
10918 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010919 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070010920 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010921 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070010922 return;
10923 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010924
10925 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070010926 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010927 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070010928 return;
10929 }
10930
Christopher Tate181fafa2009-05-14 11:12:14 -070010931 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010932 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070010933 return;
10934 }
10935
Christopher Tate6fa95972009-06-05 18:43:55 -070010936 ProcessRecord proc = mBackupTarget.app;
10937 mBackupTarget = null;
10938 mBackupAppName = null;
10939
10940 // Not backing this app up any more; reset its OOM adjustment
10941 updateOomAdjLocked(proc);
10942
Christopher Tatec7b31e32009-06-10 15:49:30 -070010943 // If the app crashed during backup, 'thread' will be null here
10944 if (proc.thread != null) {
10945 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010946 proc.thread.scheduleDestroyBackupAgent(appInfo,
10947 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070010948 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010949 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070010950 e.printStackTrace();
10951 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010952 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010953 }
10954 }
10955 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010956 // BROADCASTS
10957 // =========================================================
10958
Josh Bartel7f208742010-02-25 11:01:44 -060010959 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960 List cur) {
10961 final ContentResolver resolver = mContext.getContentResolver();
10962 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
10963 if (list == null) {
10964 return cur;
10965 }
10966 int N = list.size();
10967 for (int i=0; i<N; i++) {
10968 Intent intent = list.get(i);
10969 if (filter.match(resolver, intent, true, TAG) >= 0) {
10970 if (cur == null) {
10971 cur = new ArrayList<Intent>();
10972 }
10973 cur.add(intent);
10974 }
10975 }
10976 return cur;
10977 }
10978
10979 private final void scheduleBroadcastsLocked() {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010980 if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts: current="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010981 + mBroadcastsScheduled);
10982
10983 if (mBroadcastsScheduled) {
10984 return;
10985 }
10986 mHandler.sendEmptyMessage(BROADCAST_INTENT_MSG);
10987 mBroadcastsScheduled = true;
10988 }
10989
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010990 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010991 IIntentReceiver receiver, IntentFilter filter, String permission) {
10992 synchronized(this) {
10993 ProcessRecord callerApp = null;
10994 if (caller != null) {
10995 callerApp = getRecordForAppLocked(caller);
10996 if (callerApp == null) {
10997 throw new SecurityException(
10998 "Unable to find app for caller " + caller
10999 + " (pid=" + Binder.getCallingPid()
11000 + ") when registering receiver " + receiver);
11001 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011002 if (callerApp.info.uid != Process.SYSTEM_UID &&
11003 !callerApp.pkgList.contains(callerPackage)) {
11004 throw new SecurityException("Given caller package " + callerPackage
11005 + " is not running in process " + callerApp);
11006 }
11007 } else {
11008 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011009 }
11010
11011 List allSticky = null;
11012
11013 // Look for any matching sticky broadcasts...
11014 Iterator actions = filter.actionsIterator();
11015 if (actions != null) {
11016 while (actions.hasNext()) {
11017 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060011018 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011019 }
11020 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060011021 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011022 }
11023
11024 // The first sticky in the list is returned directly back to
11025 // the client.
11026 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11027
Joe Onorato8a9b2202010-02-26 18:56:32 -080011028 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011029 + ": " + sticky);
11030
11031 if (receiver == null) {
11032 return sticky;
11033 }
11034
11035 ReceiverList rl
11036 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11037 if (rl == null) {
11038 rl = new ReceiverList(this, callerApp,
11039 Binder.getCallingPid(),
11040 Binder.getCallingUid(), receiver);
11041 if (rl.app != null) {
11042 rl.app.receivers.add(rl);
11043 } else {
11044 try {
11045 receiver.asBinder().linkToDeath(rl, 0);
11046 } catch (RemoteException e) {
11047 return sticky;
11048 }
11049 rl.linkedToDeath = true;
11050 }
11051 mRegisteredReceivers.put(receiver.asBinder(), rl);
11052 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011053 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011054 rl.add(bf);
11055 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011056 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011057 }
11058 mReceiverResolver.addFilter(bf);
11059
11060 // Enqueue broadcasts for all existing stickies that match
11061 // this filter.
11062 if (allSticky != null) {
11063 ArrayList receivers = new ArrayList();
11064 receivers.add(bf);
11065
11066 int N = allSticky.size();
11067 for (int i=0; i<N; i++) {
11068 Intent intent = (Intent)allSticky.get(i);
11069 BroadcastRecord r = new BroadcastRecord(intent, null,
11070 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011071 false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011072 if (mParallelBroadcasts.size() == 0) {
11073 scheduleBroadcastsLocked();
11074 }
11075 mParallelBroadcasts.add(r);
11076 }
11077 }
11078
11079 return sticky;
11080 }
11081 }
11082
11083 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011084 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011085
11086 boolean doNext = false;
11087
11088 synchronized(this) {
11089 ReceiverList rl
11090 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11091 if (rl != null) {
11092 if (rl.curBroadcast != null) {
11093 BroadcastRecord r = rl.curBroadcast;
11094 doNext = finishReceiverLocked(
11095 receiver.asBinder(), r.resultCode, r.resultData,
11096 r.resultExtras, r.resultAbort, true);
11097 }
11098
11099 if (rl.app != null) {
11100 rl.app.receivers.remove(rl);
11101 }
11102 removeReceiverLocked(rl);
11103 if (rl.linkedToDeath) {
11104 rl.linkedToDeath = false;
11105 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11106 }
11107 }
11108 }
11109
11110 if (!doNext) {
11111 return;
11112 }
11113
11114 final long origId = Binder.clearCallingIdentity();
11115 processNextBroadcast(false);
11116 trimApplications();
11117 Binder.restoreCallingIdentity(origId);
11118 }
11119
11120 void removeReceiverLocked(ReceiverList rl) {
11121 mRegisteredReceivers.remove(rl.receiver.asBinder());
11122 int N = rl.size();
11123 for (int i=0; i<N; i++) {
11124 mReceiverResolver.removeFilter(rl.get(i));
11125 }
11126 }
11127
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011128 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
11129 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11130 ProcessRecord r = mLruProcesses.get(i);
11131 if (r.thread != null) {
11132 try {
11133 r.thread.dispatchPackageBroadcast(cmd, packages);
11134 } catch (RemoteException ex) {
11135 }
11136 }
11137 }
11138 }
11139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011140 private final int broadcastIntentLocked(ProcessRecord callerApp,
11141 String callerPackage, Intent intent, String resolvedType,
11142 IIntentReceiver resultTo, int resultCode, String resultData,
11143 Bundle map, String requiredPermission,
11144 boolean ordered, boolean sticky, int callingPid, int callingUid) {
11145 intent = new Intent(intent);
11146
Dianne Hackborne7f97212011-02-24 14:40:20 -080011147 // By default broadcasts do not go to stopped apps.
11148 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11149
Joe Onorato8a9b2202010-02-26 18:56:32 -080011150 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011151 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
11152 + " ordered=" + ordered);
11153 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011154 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011155 }
11156
11157 // Handle special intents: if this broadcast is from the package
11158 // manager about a package being removed, we need to remove all of
11159 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011160 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011161 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011162 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11163 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011164 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 || uidRemoved) {
11166 if (checkComponentPermission(
11167 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011168 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011169 == PackageManager.PERMISSION_GRANTED) {
11170 if (uidRemoved) {
11171 final Bundle intentExtras = intent.getExtras();
11172 final int uid = intentExtras != null
11173 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11174 if (uid >= 0) {
11175 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11176 synchronized (bs) {
11177 bs.removeUidStatsLocked(uid);
11178 }
11179 }
11180 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011181 // If resources are unvailble just force stop all
11182 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011183 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011184 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11185 if (list != null && (list.length > 0)) {
11186 for (String pkg : list) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080011187 forceStopPackageLocked(pkg, -1, false, true, true);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011188 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011189 sendPackageBroadcastLocked(
11190 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011191 }
11192 } else {
11193 Uri data = intent.getData();
11194 String ssp;
11195 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11196 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11197 forceStopPackageLocked(ssp,
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080011198 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011199 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011200 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011201 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
11202 new String[] {ssp});
11203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204 }
11205 }
11206 }
11207 } else {
11208 String msg = "Permission Denial: " + intent.getAction()
11209 + " broadcast from " + callerPackage + " (pid=" + callingPid
11210 + ", uid=" + callingUid + ")"
11211 + " requires "
11212 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011213 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011214 throw new SecurityException(msg);
11215 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011216
11217 // Special case for adding a package: by default turn on compatibility
11218 // mode.
11219 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011220 Uri data = intent.getData();
11221 String ssp;
11222 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11223 mCompatModePackages.handlePackageAddedLocked(ssp,
11224 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011226 }
11227
11228 /*
11229 * If this is the time zone changed action, queue up a message that will reset the timezone
11230 * of all currently running processes. This message will get queued up before the broadcast
11231 * happens.
11232 */
11233 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11234 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11235 }
11236
Robert Greenwalt03595d02010-11-02 14:08:23 -070011237 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11238 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11239 }
11240
Robert Greenwalt434203a2010-10-11 16:00:27 -070011241 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11242 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11243 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11244 }
11245
Dianne Hackborn854060af2009-07-09 18:14:31 -070011246 /*
11247 * Prevent non-system code (defined here to be non-persistent
11248 * processes) from sending protected broadcasts.
11249 */
11250 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11251 || callingUid == Process.SHELL_UID || callingUid == 0) {
11252 // Always okay.
11253 } else if (callerApp == null || !callerApp.persistent) {
11254 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011255 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070011256 intent.getAction())) {
11257 String msg = "Permission Denial: not allowed to send broadcast "
11258 + intent.getAction() + " from pid="
11259 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011260 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070011261 throw new SecurityException(msg);
11262 }
11263 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011264 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070011265 return BROADCAST_SUCCESS;
11266 }
11267 }
11268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011269 // Add to the sticky list if requested.
11270 if (sticky) {
11271 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11272 callingPid, callingUid)
11273 != PackageManager.PERMISSION_GRANTED) {
11274 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11275 + callingPid + ", uid=" + callingUid
11276 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011277 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011278 throw new SecurityException(msg);
11279 }
11280 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011281 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282 + " and enforce permission " + requiredPermission);
11283 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
11284 }
11285 if (intent.getComponent() != null) {
11286 throw new SecurityException(
11287 "Sticky broadcasts can't target a specific component");
11288 }
11289 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11290 if (list == null) {
11291 list = new ArrayList<Intent>();
11292 mStickyBroadcasts.put(intent.getAction(), list);
11293 }
11294 int N = list.size();
11295 int i;
11296 for (i=0; i<N; i++) {
11297 if (intent.filterEquals(list.get(i))) {
11298 // This sticky already exists, replace it.
11299 list.set(i, new Intent(intent));
11300 break;
11301 }
11302 }
11303 if (i >= N) {
11304 list.add(new Intent(intent));
11305 }
11306 }
11307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011308 // Figure out who all will receive this broadcast.
11309 List receivers = null;
11310 List<BroadcastFilter> registeredReceivers = null;
11311 try {
11312 if (intent.getComponent() != null) {
11313 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011314 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070011315 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011316 if (ai != null) {
11317 receivers = new ArrayList();
11318 ResolveInfo ri = new ResolveInfo();
11319 ri.activityInfo = ai;
11320 receivers.add(ri);
11321 }
11322 } else {
11323 // Need to resolve the intent to interested receivers...
11324 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11325 == 0) {
11326 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011327 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011328 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011329 }
Mihai Preda074edef2009-05-18 17:13:31 +020011330 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 }
11332 } catch (RemoteException ex) {
11333 // pm is in same process, this will never happen.
11334 }
11335
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011336 final boolean replacePending =
11337 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11338
Joe Onorato8a9b2202010-02-26 18:56:32 -080011339 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011340 + " replacePending=" + replacePending);
11341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011342 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11343 if (!ordered && NR > 0) {
11344 // If we are not serializing this broadcast, then send the
11345 // registered receivers separately so they don't wait for the
11346 // components to be launched.
11347 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
11348 callerPackage, callingPid, callingUid, requiredPermission,
11349 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011350 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011351 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011352 TAG, "Enqueueing parallel broadcast " + r
11353 + ": prev had " + mParallelBroadcasts.size());
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011354 boolean replaced = false;
11355 if (replacePending) {
11356 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
11357 if (intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011358 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011359 "***** DROPPING PARALLEL: " + intent);
11360 mParallelBroadcasts.set(i, r);
11361 replaced = true;
11362 break;
11363 }
11364 }
11365 }
11366 if (!replaced) {
11367 mParallelBroadcasts.add(r);
11368 scheduleBroadcastsLocked();
11369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011370 registeredReceivers = null;
11371 NR = 0;
11372 }
11373
11374 // Merge into one list.
11375 int ir = 0;
11376 if (receivers != null) {
11377 // A special case for PACKAGE_ADDED: do not allow the package
11378 // being added to see this broadcast. This prevents them from
11379 // using this as a back door to get run as soon as they are
11380 // installed. Maybe in the future we want to have a special install
11381 // broadcast or such for apps, but we'd like to deliberately make
11382 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011383 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011384 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11385 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11386 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011387 Uri data = intent.getData();
11388 if (data != null) {
11389 String pkgName = data.getSchemeSpecificPart();
11390 if (pkgName != null) {
11391 skipPackages = new String[] { pkgName };
11392 }
11393 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011394 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011395 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011396 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011397 if (skipPackages != null && (skipPackages.length > 0)) {
11398 for (String skipPackage : skipPackages) {
11399 if (skipPackage != null) {
11400 int NT = receivers.size();
11401 for (int it=0; it<NT; it++) {
11402 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11403 if (curt.activityInfo.packageName.equals(skipPackage)) {
11404 receivers.remove(it);
11405 it--;
11406 NT--;
11407 }
11408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011409 }
11410 }
11411 }
11412
11413 int NT = receivers != null ? receivers.size() : 0;
11414 int it = 0;
11415 ResolveInfo curt = null;
11416 BroadcastFilter curr = null;
11417 while (it < NT && ir < NR) {
11418 if (curt == null) {
11419 curt = (ResolveInfo)receivers.get(it);
11420 }
11421 if (curr == null) {
11422 curr = registeredReceivers.get(ir);
11423 }
11424 if (curr.getPriority() >= curt.priority) {
11425 // Insert this broadcast record into the final list.
11426 receivers.add(it, curr);
11427 ir++;
11428 curr = null;
11429 it++;
11430 NT++;
11431 } else {
11432 // Skip to the next ResolveInfo in the final list.
11433 it++;
11434 curt = null;
11435 }
11436 }
11437 }
11438 while (ir < NR) {
11439 if (receivers == null) {
11440 receivers = new ArrayList();
11441 }
11442 receivers.add(registeredReceivers.get(ir));
11443 ir++;
11444 }
11445
11446 if ((receivers != null && receivers.size() > 0)
11447 || resultTo != null) {
11448 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
11449 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011450 receivers, resultTo, resultCode, resultData, map, ordered,
11451 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011452 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 TAG, "Enqueueing ordered broadcast " + r
11454 + ": prev had " + mOrderedBroadcasts.size());
11455 if (DEBUG_BROADCAST) {
11456 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011457 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011458 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011459 boolean replaced = false;
11460 if (replacePending) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011461 for (int i=mOrderedBroadcasts.size()-1; i>0; i--) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011462 if (intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011463 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011464 "***** DROPPING ORDERED: " + intent);
11465 mOrderedBroadcasts.set(i, r);
11466 replaced = true;
11467 break;
11468 }
11469 }
11470 }
11471 if (!replaced) {
11472 mOrderedBroadcasts.add(r);
11473 scheduleBroadcastsLocked();
11474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011475 }
11476
11477 return BROADCAST_SUCCESS;
11478 }
11479
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011480 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011481 // Refuse possible leaked file descriptors
11482 if (intent != null && intent.hasFileDescriptors() == true) {
11483 throw new IllegalArgumentException("File descriptors passed in Intent");
11484 }
11485
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011486 int flags = intent.getFlags();
11487
11488 if (!mProcessesReady) {
11489 // if the caller really truly claims to know what they're doing, go
11490 // ahead and allow the broadcast without launching any receivers
11491 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11492 intent = new Intent(intent);
11493 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11494 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11495 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11496 + " before boot completion");
11497 throw new IllegalStateException("Cannot broadcast before boot completed");
11498 }
11499 }
11500
11501 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11502 throw new IllegalArgumentException(
11503 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11504 }
11505
11506 return intent;
11507 }
11508
11509 public final int broadcastIntent(IApplicationThread caller,
11510 Intent intent, String resolvedType, IIntentReceiver resultTo,
11511 int resultCode, String resultData, Bundle map,
11512 String requiredPermission, boolean serialized, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011513 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011514 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011516 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11517 final int callingPid = Binder.getCallingPid();
11518 final int callingUid = Binder.getCallingUid();
11519 final long origId = Binder.clearCallingIdentity();
11520 int res = broadcastIntentLocked(callerApp,
11521 callerApp != null ? callerApp.info.packageName : null,
11522 intent, resolvedType, resultTo,
11523 resultCode, resultData, map, requiredPermission, serialized,
11524 sticky, callingPid, callingUid);
11525 Binder.restoreCallingIdentity(origId);
11526 return res;
11527 }
11528 }
11529
11530 int broadcastIntentInPackage(String packageName, int uid,
11531 Intent intent, String resolvedType, IIntentReceiver resultTo,
11532 int resultCode, String resultData, Bundle map,
11533 String requiredPermission, boolean serialized, boolean sticky) {
11534 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011535 intent = verifyBroadcastLocked(intent);
11536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011537 final long origId = Binder.clearCallingIdentity();
11538 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11539 resultTo, resultCode, resultData, map, requiredPermission,
11540 serialized, sticky, -1, uid);
11541 Binder.restoreCallingIdentity(origId);
11542 return res;
11543 }
11544 }
11545
11546 public final void unbroadcastIntent(IApplicationThread caller,
11547 Intent intent) {
11548 // Refuse possible leaked file descriptors
11549 if (intent != null && intent.hasFileDescriptors() == true) {
11550 throw new IllegalArgumentException("File descriptors passed in Intent");
11551 }
11552
11553 synchronized(this) {
11554 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11555 != PackageManager.PERMISSION_GRANTED) {
11556 String msg = "Permission Denial: unbroadcastIntent() from pid="
11557 + Binder.getCallingPid()
11558 + ", uid=" + Binder.getCallingUid()
11559 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011560 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011561 throw new SecurityException(msg);
11562 }
11563 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11564 if (list != null) {
11565 int N = list.size();
11566 int i;
11567 for (i=0; i<N; i++) {
11568 if (intent.filterEquals(list.get(i))) {
11569 list.remove(i);
11570 break;
11571 }
11572 }
11573 }
11574 }
11575 }
11576
11577 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11578 String resultData, Bundle resultExtras, boolean resultAbort,
11579 boolean explicit) {
11580 if (mOrderedBroadcasts.size() == 0) {
11581 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011582 Slog.w(TAG, "finishReceiver called but no pending broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011583 }
11584 return false;
11585 }
11586 BroadcastRecord r = mOrderedBroadcasts.get(0);
11587 if (r.receiver == null) {
11588 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011589 Slog.w(TAG, "finishReceiver called but none active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011590 }
11591 return false;
11592 }
11593 if (r.receiver != receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011594 Slog.w(TAG, "finishReceiver called but active receiver is different");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011595 return false;
11596 }
11597 int state = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011598 r.state = BroadcastRecord.IDLE;
11599 if (state == BroadcastRecord.IDLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011600 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011601 Slog.w(TAG, "finishReceiver called but state is IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011602 }
11603 }
11604 r.receiver = null;
11605 r.intent.setComponent(null);
11606 if (r.curApp != null) {
11607 r.curApp.curReceiver = null;
11608 }
11609 if (r.curFilter != null) {
11610 r.curFilter.receiverList.curBroadcast = null;
11611 }
11612 r.curFilter = null;
11613 r.curApp = null;
11614 r.curComponent = null;
11615 r.curReceiver = null;
11616 mPendingBroadcast = null;
11617
11618 r.resultCode = resultCode;
11619 r.resultData = resultData;
11620 r.resultExtras = resultExtras;
11621 r.resultAbort = resultAbort;
11622
11623 // We will process the next receiver right now if this is finishing
11624 // an app receiver (which is always asynchronous) or after we have
11625 // come back from calling a receiver.
11626 return state == BroadcastRecord.APP_RECEIVE
11627 || state == BroadcastRecord.CALL_DONE_RECEIVE;
11628 }
11629
11630 public void finishReceiver(IBinder who, int resultCode, String resultData,
11631 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011632 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011633
11634 // Refuse possible leaked file descriptors
11635 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11636 throw new IllegalArgumentException("File descriptors passed in Bundle");
11637 }
11638
11639 boolean doNext;
11640
11641 final long origId = Binder.clearCallingIdentity();
11642
11643 synchronized(this) {
11644 doNext = finishReceiverLocked(
11645 who, resultCode, resultData, resultExtras, resultAbort, true);
11646 }
11647
11648 if (doNext) {
11649 processNextBroadcast(false);
11650 }
11651 trimApplications();
11652
11653 Binder.restoreCallingIdentity(origId);
11654 }
11655
Jeff Brown4d94a762010-09-23 11:33:28 -070011656 private final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011657 if (r.nextReceiver > 0) {
11658 Object curReceiver = r.receivers.get(r.nextReceiver-1);
11659 if (curReceiver instanceof BroadcastFilter) {
11660 BroadcastFilter bf = (BroadcastFilter) curReceiver;
Doug Zongker2bec3d42009-12-04 12:52:44 -080011661 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011662 System.identityHashCode(r),
11663 r.intent.getAction(),
11664 r.nextReceiver - 1,
11665 System.identityHashCode(bf));
11666 } else {
Doug Zongker2bec3d42009-12-04 12:52:44 -080011667 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011668 System.identityHashCode(r),
11669 r.intent.getAction(),
11670 r.nextReceiver - 1,
11671 ((ResolveInfo)curReceiver).toString());
11672 }
11673 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011674 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011675 + r);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011676 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011677 System.identityHashCode(r),
11678 r.intent.getAction(),
11679 r.nextReceiver,
11680 "NONE");
11681 }
11682 }
11683
Jeff Brown4d94a762010-09-23 11:33:28 -070011684 private final void setBroadcastTimeoutLocked(long timeoutTime) {
11685 if (! mPendingBroadcastTimeoutMessage) {
11686 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
11687 mHandler.sendMessageAtTime(msg, timeoutTime);
11688 mPendingBroadcastTimeoutMessage = true;
11689 }
11690 }
11691
11692 private final void cancelBroadcastTimeoutLocked() {
11693 if (mPendingBroadcastTimeoutMessage) {
11694 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG);
11695 mPendingBroadcastTimeoutMessage = false;
11696 }
11697 }
11698
11699 private final void broadcastTimeoutLocked(boolean fromMsg) {
11700 if (fromMsg) {
11701 mPendingBroadcastTimeoutMessage = false;
11702 }
11703
11704 if (mOrderedBroadcasts.size() == 0) {
11705 return;
11706 }
11707
11708 long now = SystemClock.uptimeMillis();
11709 BroadcastRecord r = mOrderedBroadcasts.get(0);
11710 if (fromMsg) {
11711 if (mDidDexOpt) {
11712 // Delay timeouts until dexopt finishes.
11713 mDidDexOpt = false;
11714 long timeoutTime = SystemClock.uptimeMillis() + BROADCAST_TIMEOUT;
11715 setBroadcastTimeoutLocked(timeoutTime);
11716 return;
11717 }
11718 if (! mProcessesReady) {
11719 // Only process broadcast timeouts if the system is ready. That way
11720 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
11721 // to do heavy lifting for system up.
11722 return;
11723 }
11724
11725 long timeoutTime = r.receiverTime + BROADCAST_TIMEOUT;
11726 if (timeoutTime > now) {
11727 // We can observe premature timeouts because we do not cancel and reset the
11728 // broadcast timeout message after each receiver finishes. Instead, we set up
11729 // an initial timeout then kick it down the road a little further as needed
11730 // when it expires.
11731 if (DEBUG_BROADCAST) Slog.v(TAG,
11732 "Premature timeout @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
11733 + timeoutTime);
11734 setBroadcastTimeoutLocked(timeoutTime);
11735 return;
11736 }
11737 }
11738
11739 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
11740 + ", started " + (now - r.receiverTime) + "ms ago");
11741 r.receiverTime = now;
11742 r.anrCount++;
11743
11744 // Current receiver has passed its expiration date.
11745 if (r.nextReceiver <= 0) {
11746 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
11747 return;
11748 }
11749
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011750 ProcessRecord app = null;
11751 String anrMessage = null;
11752
Jeff Brown4d94a762010-09-23 11:33:28 -070011753 Object curReceiver = r.receivers.get(r.nextReceiver-1);
11754 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
11755 logBroadcastReceiverDiscardLocked(r);
11756 if (curReceiver instanceof BroadcastFilter) {
11757 BroadcastFilter bf = (BroadcastFilter)curReceiver;
11758 if (bf.receiverList.pid != 0
11759 && bf.receiverList.pid != MY_PID) {
11760 synchronized (this.mPidsSelfLocked) {
11761 app = this.mPidsSelfLocked.get(
11762 bf.receiverList.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011764 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011765 } else {
11766 app = r.curApp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011767 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011768
Jeff Brown4d94a762010-09-23 11:33:28 -070011769 if (app != null) {
11770 anrMessage = "Broadcast of " + r.intent.toString();
11771 }
11772
11773 if (mPendingBroadcast == r) {
11774 mPendingBroadcast = null;
11775 }
11776
11777 // Move on to the next receiver.
11778 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
11779 r.resultExtras, r.resultAbort, true);
11780 scheduleBroadcastsLocked();
11781
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011782 if (anrMessage != null) {
Jeff Brown4d94a762010-09-23 11:33:28 -070011783 // Post the ANR to the handler since we do not want to process ANRs while
11784 // potentially holding our lock.
11785 mHandler.post(new AppNotResponding(app, anrMessage));
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011787 }
11788
11789 private final void processCurBroadcastLocked(BroadcastRecord r,
11790 ProcessRecord app) throws RemoteException {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011791 if (DEBUG_BROADCAST) Slog.v(TAG,
11792 "Process cur broadcast " + r + " for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011793 if (app.thread == null) {
11794 throw new RemoteException();
11795 }
11796 r.receiver = app.thread.asBinder();
11797 r.curApp = app;
11798 app.curReceiver = r;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011799 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011800
11801 // Tell the application to launch this receiver.
11802 r.intent.setComponent(r.curComponent);
11803
11804 boolean started = false;
11805 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011806 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011807 "Delivering to component " + r.curComponent
11808 + ": " + r);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011809 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011810 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011811 compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011812 r.resultCode, r.resultData, r.resultExtras, r.ordered);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011813 if (DEBUG_BROADCAST) Slog.v(TAG,
11814 "Process cur broadcast " + r + " DELIVERED for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011815 started = true;
11816 } finally {
11817 if (!started) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011818 if (DEBUG_BROADCAST) Slog.v(TAG,
11819 "Process cur broadcast " + r + ": NOT STARTED!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011820 r.receiver = null;
11821 r.curApp = null;
11822 app.curReceiver = null;
11823 }
11824 }
11825
11826 }
11827
Jeff Brown4d94a762010-09-23 11:33:28 -070011828 static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011829 Intent intent, int resultCode, String data, Bundle extras,
11830 boolean ordered, boolean sticky) throws RemoteException {
Jeff Brown4d94a762010-09-23 11:33:28 -070011831 // Send the intent to the receiver asynchronously using one-way binder calls.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832 if (app != null && app.thread != null) {
11833 // If we have an app thread, do the call through that so it is
11834 // correctly ordered with other one-way calls.
11835 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011836 data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011837 } else {
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011838 receiver.performReceive(intent, resultCode, data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011839 }
11840 }
11841
Jeff Brown4d94a762010-09-23 11:33:28 -070011842 private final void deliverToRegisteredReceiverLocked(BroadcastRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011843 BroadcastFilter filter, boolean ordered) {
11844 boolean skip = false;
11845 if (filter.requiredPermission != null) {
11846 int perm = checkComponentPermission(filter.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011847 r.callingPid, r.callingUid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011848 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011849 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011850 + r.intent.toString()
11851 + " from " + r.callerPackage + " (pid="
11852 + r.callingPid + ", uid=" + r.callingUid + ")"
11853 + " requires " + filter.requiredPermission
11854 + " due to registered receiver " + filter);
11855 skip = true;
11856 }
11857 }
11858 if (r.requiredPermission != null) {
11859 int perm = checkComponentPermission(r.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011860 filter.receiverList.pid, filter.receiverList.uid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011861 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011862 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011863 + r.intent.toString()
11864 + " to " + filter.receiverList.app
11865 + " (pid=" + filter.receiverList.pid
11866 + ", uid=" + filter.receiverList.uid + ")"
11867 + " requires " + r.requiredPermission
11868 + " due to sender " + r.callerPackage
11869 + " (uid " + r.callingUid + ")");
11870 skip = true;
11871 }
11872 }
11873
11874 if (!skip) {
11875 // If this is not being sent as an ordered broadcast, then we
11876 // don't want to touch the fields that keep track of the current
11877 // state of ordered broadcasts.
11878 if (ordered) {
11879 r.receiver = filter.receiverList.receiver.asBinder();
11880 r.curFilter = filter;
11881 filter.receiverList.curBroadcast = r;
11882 r.state = BroadcastRecord.CALL_IN_RECEIVE;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011883 if (filter.receiverList.app != null) {
11884 // Bump hosting application to no longer be in background
11885 // scheduling class. Note that we can't do that if there
11886 // isn't an app... but we can only be in that case for
11887 // things that directly call the IActivityManager API, which
11888 // are already core system stuff so don't matter for this.
11889 r.curApp = filter.receiverList.app;
11890 filter.receiverList.app.curReceiver = r;
11891 updateOomAdjLocked();
11892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011893 }
11894 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011895 if (DEBUG_BROADCAST_LIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 int seq = r.intent.getIntExtra("seq", -1);
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011897 Slog.i(TAG, "Delivering to " + filter
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011898 + " (seq=" + seq + "): " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011899 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011900 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011901 new Intent(r.intent), r.resultCode,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011902 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011903 if (ordered) {
11904 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
11905 }
11906 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011907 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011908 if (ordered) {
11909 r.receiver = null;
11910 r.curFilter = null;
11911 filter.receiverList.curBroadcast = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011912 if (filter.receiverList.app != null) {
11913 filter.receiverList.app.curReceiver = null;
11914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011915 }
11916 }
11917 }
11918 }
11919
Dianne Hackborn12527f92009-11-11 17:39:50 -080011920 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
11921 if (r.callingUid < 0) {
11922 // This was from a registerReceiver() call; ignore it.
11923 return;
11924 }
11925 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
11926 MAX_BROADCAST_HISTORY-1);
11927 r.finishTime = SystemClock.uptimeMillis();
11928 mBroadcastHistory[0] = r;
11929 }
11930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011931 private final void processNextBroadcast(boolean fromMsg) {
11932 synchronized(this) {
11933 BroadcastRecord r;
11934
Joe Onorato8a9b2202010-02-26 18:56:32 -080011935 if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011936 + mParallelBroadcasts.size() + " broadcasts, "
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011937 + mOrderedBroadcasts.size() + " ordered broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011938
11939 updateCpuStats();
11940
11941 if (fromMsg) {
11942 mBroadcastsScheduled = false;
11943 }
11944
11945 // First, deliver any non-serialized broadcasts right away.
11946 while (mParallelBroadcasts.size() > 0) {
11947 r = mParallelBroadcasts.remove(0);
Dianne Hackborn12527f92009-11-11 17:39:50 -080011948 r.dispatchTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011949 final int N = r.receivers.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011950 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011951 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011952 for (int i=0; i<N; i++) {
11953 Object target = r.receivers.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011954 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011955 "Delivering non-ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011956 + target + ": " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070011957 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011958 }
Dianne Hackborn12527f92009-11-11 17:39:50 -080011959 addBroadcastToHistoryLocked(r);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011960 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011961 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011962 }
11963
11964 // Now take care of the next serialized one...
11965
11966 // If we are waiting for a process to come up to handle the next
11967 // broadcast, then do nothing at this point. Just in case, we
11968 // check that the process we're waiting for still exists.
11969 if (mPendingBroadcast != null) {
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070011970 if (DEBUG_BROADCAST_LIGHT) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011971 Slog.v(TAG, "processNextBroadcast: waiting for "
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070011972 + mPendingBroadcast.curApp);
11973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011974
11975 boolean isDead;
11976 synchronized (mPidsSelfLocked) {
11977 isDead = (mPidsSelfLocked.get(mPendingBroadcast.curApp.pid) == null);
11978 }
11979 if (!isDead) {
11980 // It's still alive, so keep waiting
11981 return;
11982 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011983 Slog.w(TAG, "pending app " + mPendingBroadcast.curApp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984 + " died before responding to broadcast");
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011985 mPendingBroadcast.state = BroadcastRecord.IDLE;
11986 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011987 mPendingBroadcast = null;
11988 }
11989 }
11990
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011991 boolean looped = false;
11992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011993 do {
11994 if (mOrderedBroadcasts.size() == 0) {
11995 // No more broadcasts pending, so all done!
11996 scheduleAppGcsLocked();
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011997 if (looped) {
11998 // If we had finished the last ordered broadcast, then
11999 // make sure all processes have correct oom and sched
12000 // adjustments.
12001 updateOomAdjLocked();
12002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012003 return;
12004 }
12005 r = mOrderedBroadcasts.get(0);
12006 boolean forceReceive = false;
12007
12008 // Ensure that even if something goes awry with the timeout
12009 // detection, we catch "hung" broadcasts here, discard them,
Jeff Hamiltonacf84742010-05-25 22:10:18 -050012010 // and continue to make progress.
12011 //
12012 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
Jeff Brown4d94a762010-09-23 11:33:28 -070012013 // receivers don't get executed with timeouts. They're intended for
Jeff Hamiltonacf84742010-05-25 22:10:18 -050012014 // one time heavy lifting after system upgrades and can take
12015 // significant amounts of time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012016 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012017 if (mProcessesReady && r.dispatchTime > 0) {
Jeff Hamiltonacf84742010-05-25 22:10:18 -050012018 long now = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012019 if ((numReceivers > 0) &&
12020 (now > r.dispatchTime + (2*BROADCAST_TIMEOUT*numReceivers))) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012021 Slog.w(TAG, "Hung broadcast discarded after timeout failure:"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012022 + " now=" + now
12023 + " dispatchTime=" + r.dispatchTime
Dianne Hackborn12527f92009-11-11 17:39:50 -080012024 + " startTime=" + r.receiverTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012025 + " intent=" + r.intent
12026 + " numReceivers=" + numReceivers
12027 + " nextReceiver=" + r.nextReceiver
12028 + " state=" + r.state);
Jeff Brown4d94a762010-09-23 11:33:28 -070012029 broadcastTimeoutLocked(false); // forcibly finish this broadcast
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012030 forceReceive = true;
12031 r.state = BroadcastRecord.IDLE;
12032 }
12033 }
12034
12035 if (r.state != BroadcastRecord.IDLE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012036 if (DEBUG_BROADCAST) Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012037 "processNextBroadcast() called when not idle (state="
12038 + r.state + ")");
12039 return;
12040 }
12041
12042 if (r.receivers == null || r.nextReceiver >= numReceivers
12043 || r.resultAbort || forceReceive) {
12044 // No more receivers for this broadcast! Send the final
12045 // result if requested...
12046 if (r.resultTo != null) {
12047 try {
12048 if (DEBUG_BROADCAST) {
12049 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012050 Slog.i(TAG, "Finishing broadcast " + r.intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012051 + " seq=" + seq + " app=" + r.callerApp);
12052 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012053 performReceiveLocked(r.callerApp, r.resultTo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012054 new Intent(r.intent), r.resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070012055 r.resultData, r.resultExtras, false, false);
Johannes Carlssonb5a86542010-10-27 10:08:10 +020012056 // Set this to null so that the reference
12057 // (local and remote) isnt kept in the mBroadcastHistory.
12058 r.resultTo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012059 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012060 Slog.w(TAG, "Failure sending broadcast result of " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012061 }
12062 }
12063
Joe Onorato8a9b2202010-02-26 18:56:32 -080012064 if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
Jeff Brown4d94a762010-09-23 11:33:28 -070012065 cancelBroadcastTimeoutLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012066
Joe Onorato8a9b2202010-02-26 18:56:32 -080012067 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012068 + r);
12069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012070 // ... and on to the next...
Dianne Hackborn12527f92009-11-11 17:39:50 -080012071 addBroadcastToHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012072 mOrderedBroadcasts.remove(0);
12073 r = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012074 looped = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075 continue;
12076 }
12077 } while (r == null);
12078
12079 // Get the next receiver...
12080 int recIdx = r.nextReceiver++;
12081
12082 // Keep track of when this receiver started, and make sure there
12083 // is a timeout message pending to kill it if need be.
Dianne Hackborn12527f92009-11-11 17:39:50 -080012084 r.receiverTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012085 if (recIdx == 0) {
Dianne Hackborn12527f92009-11-11 17:39:50 -080012086 r.dispatchTime = r.receiverTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012087
Joe Onorato8a9b2202010-02-26 18:56:32 -080012088 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012089 + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070012090 }
12091 if (! mPendingBroadcastTimeoutMessage) {
12092 long timeoutTime = r.receiverTime + BROADCAST_TIMEOUT;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012093 if (DEBUG_BROADCAST) Slog.v(TAG,
Jeff Brown4d94a762010-09-23 11:33:28 -070012094 "Submitting BROADCAST_TIMEOUT_MSG for " + r + " at " + timeoutTime);
12095 setBroadcastTimeoutLocked(timeoutTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012096 }
12097
12098 Object nextReceiver = r.receivers.get(recIdx);
12099 if (nextReceiver instanceof BroadcastFilter) {
12100 // Simple case: this is a registered receiver who gets
12101 // a direct call.
12102 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012103 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070012104 "Delivering ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012105 + filter + ": " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070012106 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012107 if (r.receiver == null || !r.ordered) {
12108 // The receiver has already finished, so schedule to
12109 // process the next one.
Dianne Hackborn399cccb2010-04-13 22:57:49 -070012110 if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing: ordered="
12111 + r.ordered + " receiver=" + r.receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012112 r.state = BroadcastRecord.IDLE;
12113 scheduleBroadcastsLocked();
12114 }
12115 return;
12116 }
12117
12118 // Hard case: need to instantiate the receiver, possibly
12119 // starting its application process to host it.
12120
12121 ResolveInfo info =
12122 (ResolveInfo)nextReceiver;
12123
12124 boolean skip = false;
12125 int perm = checkComponentPermission(info.activityInfo.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012126 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
12127 info.activityInfo.exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012128 if (perm != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012129 if (!info.activityInfo.exported) {
12130 Slog.w(TAG, "Permission Denial: broadcasting "
12131 + r.intent.toString()
12132 + " from " + r.callerPackage + " (pid=" + r.callingPid
12133 + ", uid=" + r.callingUid + ")"
12134 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
12135 + " due to receiver " + info.activityInfo.packageName
12136 + "/" + info.activityInfo.name);
12137 } else {
12138 Slog.w(TAG, "Permission Denial: broadcasting "
12139 + r.intent.toString()
12140 + " from " + r.callerPackage + " (pid=" + r.callingPid
12141 + ", uid=" + r.callingUid + ")"
12142 + " requires " + info.activityInfo.permission
12143 + " due to receiver " + info.activityInfo.packageName
12144 + "/" + info.activityInfo.name);
12145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012146 skip = true;
12147 }
12148 if (r.callingUid != Process.SYSTEM_UID &&
12149 r.requiredPermission != null) {
12150 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012151 perm = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012152 checkPermission(r.requiredPermission,
12153 info.activityInfo.applicationInfo.packageName);
12154 } catch (RemoteException e) {
12155 perm = PackageManager.PERMISSION_DENIED;
12156 }
12157 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012158 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012159 + r.intent + " to "
12160 + info.activityInfo.applicationInfo.packageName
12161 + " requires " + r.requiredPermission
12162 + " due to sender " + r.callerPackage
12163 + " (uid " + r.callingUid + ")");
12164 skip = true;
12165 }
12166 }
12167 if (r.curApp != null && r.curApp.crashing) {
12168 // If the target process is crashing, just skip it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012169 if (DEBUG_BROADCAST) Slog.v(TAG,
12170 "Skipping deliver ordered " + r + " to " + r.curApp
12171 + ": process crashing");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012172 skip = true;
12173 }
12174
12175 if (skip) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012176 if (DEBUG_BROADCAST) Slog.v(TAG,
12177 "Skipping delivery of ordered " + r + " for whatever reason");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012178 r.receiver = null;
12179 r.curFilter = null;
12180 r.state = BroadcastRecord.IDLE;
12181 scheduleBroadcastsLocked();
12182 return;
12183 }
12184
12185 r.state = BroadcastRecord.APP_RECEIVE;
12186 String targetProcess = info.activityInfo.processName;
12187 r.curComponent = new ComponentName(
12188 info.activityInfo.applicationInfo.packageName,
12189 info.activityInfo.name);
12190 r.curReceiver = info.activityInfo;
12191
Dianne Hackborne7f97212011-02-24 14:40:20 -080012192 // Broadcast is being executed, its package can't be stopped.
12193 try {
12194 AppGlobals.getPackageManager().setPackageStoppedState(
12195 r.curComponent.getPackageName(), false);
12196 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012197 } catch (IllegalArgumentException e) {
12198 Slog.w(TAG, "Failed trying to unstop package "
12199 + r.curComponent.getPackageName() + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012200 }
12201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012202 // Is this receiver's application already running?
12203 ProcessRecord app = getProcessRecordLocked(targetProcess,
12204 info.activityInfo.applicationInfo.uid);
12205 if (app != null && app.thread != null) {
12206 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012207 app.addPackage(info.activityInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012208 processCurBroadcastLocked(r, app);
12209 return;
12210 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012211 Slog.w(TAG, "Exception when sending broadcast to "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012212 + r.curComponent, e);
12213 }
12214
12215 // If a dead object exception was thrown -- fall through to
12216 // restart the application.
12217 }
12218
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012219 // Not running -- get it started, to be executed when the app comes up.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012220 if (DEBUG_BROADCAST) Slog.v(TAG,
12221 "Need to start app " + targetProcess + " for broadcast " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012222 if ((r.curApp=startProcessLocked(targetProcess,
12223 info.activityInfo.applicationInfo, true,
12224 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012225 "broadcast", r.curComponent,
12226 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0))
12227 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012228 // Ah, this recipient is unavailable. Finish it if necessary,
12229 // and mark the broadcast record as ready for the next.
Joe Onorato8a9b2202010-02-26 18:56:32 -080012230 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012231 + info.activityInfo.applicationInfo.packageName + "/"
12232 + info.activityInfo.applicationInfo.uid + " for broadcast "
12233 + r.intent + ": process is bad");
Jeff Brown4d94a762010-09-23 11:33:28 -070012234 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012235 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
12236 r.resultExtras, r.resultAbort, true);
12237 scheduleBroadcastsLocked();
12238 r.state = BroadcastRecord.IDLE;
12239 return;
12240 }
12241
12242 mPendingBroadcast = r;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012243 mPendingBroadcastRecvIndex = recIdx;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012244 }
12245 }
12246
12247 // =========================================================
12248 // INSTRUMENTATION
12249 // =========================================================
12250
12251 public boolean startInstrumentation(ComponentName className,
12252 String profileFile, int flags, Bundle arguments,
12253 IInstrumentationWatcher watcher) {
12254 // Refuse possible leaked file descriptors
12255 if (arguments != null && arguments.hasFileDescriptors()) {
12256 throw new IllegalArgumentException("File descriptors passed in Bundle");
12257 }
12258
12259 synchronized(this) {
12260 InstrumentationInfo ii = null;
12261 ApplicationInfo ai = null;
12262 try {
12263 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012264 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012265 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012266 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012267 } catch (PackageManager.NameNotFoundException e) {
12268 }
12269 if (ii == null) {
12270 reportStartInstrumentationFailure(watcher, className,
12271 "Unable to find instrumentation info for: " + className);
12272 return false;
12273 }
12274 if (ai == null) {
12275 reportStartInstrumentationFailure(watcher, className,
12276 "Unable to find instrumentation target package: " + ii.targetPackage);
12277 return false;
12278 }
12279
12280 int match = mContext.getPackageManager().checkSignatures(
12281 ii.targetPackage, ii.packageName);
12282 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12283 String msg = "Permission Denial: starting instrumentation "
12284 + className + " from pid="
12285 + Binder.getCallingPid()
12286 + ", uid=" + Binder.getCallingPid()
12287 + " not allowed because package " + ii.packageName
12288 + " does not have a signature matching the target "
12289 + ii.targetPackage;
12290 reportStartInstrumentationFailure(watcher, className, msg);
12291 throw new SecurityException(msg);
12292 }
12293
12294 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080012295 forceStopPackageLocked(ii.targetPackage, -1, true, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012296 ProcessRecord app = addAppLocked(ai);
12297 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012298 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012299 app.instrumentationProfileFile = profileFile;
12300 app.instrumentationArguments = arguments;
12301 app.instrumentationWatcher = watcher;
12302 app.instrumentationResultClass = className;
12303 Binder.restoreCallingIdentity(origId);
12304 }
12305
12306 return true;
12307 }
12308
12309 /**
12310 * Report errors that occur while attempting to start Instrumentation. Always writes the
12311 * error to the logs, but if somebody is watching, send the report there too. This enables
12312 * the "am" command to report errors with more information.
12313 *
12314 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12315 * @param cn The component name of the instrumentation.
12316 * @param report The error report.
12317 */
12318 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12319 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012320 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012321 try {
12322 if (watcher != null) {
12323 Bundle results = new Bundle();
12324 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12325 results.putString("Error", report);
12326 watcher.instrumentationStatus(cn, -1, results);
12327 }
12328 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012329 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012330 }
12331 }
12332
12333 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12334 if (app.instrumentationWatcher != null) {
12335 try {
12336 // NOTE: IInstrumentationWatcher *must* be oneway here
12337 app.instrumentationWatcher.instrumentationFinished(
12338 app.instrumentationClass,
12339 resultCode,
12340 results);
12341 } catch (RemoteException e) {
12342 }
12343 }
12344 app.instrumentationWatcher = null;
12345 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012346 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012347 app.instrumentationProfileFile = null;
12348 app.instrumentationArguments = null;
12349
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080012350 forceStopPackageLocked(app.processName, -1, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012351 }
12352
12353 public void finishInstrumentation(IApplicationThread target,
12354 int resultCode, Bundle results) {
12355 // Refuse possible leaked file descriptors
12356 if (results != null && results.hasFileDescriptors()) {
12357 throw new IllegalArgumentException("File descriptors passed in Intent");
12358 }
12359
12360 synchronized(this) {
12361 ProcessRecord app = getRecordForAppLocked(target);
12362 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012363 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012364 return;
12365 }
12366 final long origId = Binder.clearCallingIdentity();
12367 finishInstrumentationLocked(app, resultCode, results);
12368 Binder.restoreCallingIdentity(origId);
12369 }
12370 }
12371
12372 // =========================================================
12373 // CONFIGURATION
12374 // =========================================================
12375
12376 public ConfigurationInfo getDeviceConfigurationInfo() {
12377 ConfigurationInfo config = new ConfigurationInfo();
12378 synchronized (this) {
12379 config.reqTouchScreen = mConfiguration.touchscreen;
12380 config.reqKeyboardType = mConfiguration.keyboard;
12381 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012382 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12383 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012384 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12385 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012386 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12387 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012388 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12389 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012390 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012391 }
12392 return config;
12393 }
12394
12395 public Configuration getConfiguration() {
12396 Configuration ci;
12397 synchronized(this) {
12398 ci = new Configuration(mConfiguration);
12399 }
12400 return ci;
12401 }
12402
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012403 public void updatePersistentConfiguration(Configuration values) {
12404 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12405 "updateConfiguration()");
12406 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12407 "updateConfiguration()");
12408 if (values == null) {
12409 throw new NullPointerException("Configuration must not be null");
12410 }
12411
12412 synchronized(this) {
12413 final long origId = Binder.clearCallingIdentity();
12414 updateConfigurationLocked(values, null, true);
12415 Binder.restoreCallingIdentity(origId);
12416 }
12417 }
12418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419 public void updateConfiguration(Configuration values) {
12420 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12421 "updateConfiguration()");
12422
12423 synchronized(this) {
12424 if (values == null && mWindowManager != null) {
12425 // sentinel: fetch the current configuration from the window manager
12426 values = mWindowManager.computeNewConfiguration();
12427 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012428
12429 if (mWindowManager != null) {
12430 mProcessList.applyDisplaySize(mWindowManager);
12431 }
12432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012433 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012434 if (values != null) {
12435 Settings.System.clearConfiguration(values);
12436 }
12437 updateConfigurationLocked(values, null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012438 Binder.restoreCallingIdentity(origId);
12439 }
12440 }
12441
12442 /**
12443 * Do either or both things: (1) change the current configuration, and (2)
12444 * make sure the given activity is running with the (now) current
12445 * configuration. Returns true if the activity has been left running, or
12446 * false if <var>starting</var> is being destroyed to match the new
12447 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012448 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012449 */
12450 public boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012451 ActivityRecord starting, boolean persistent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012452 int changes = 0;
12453
12454 boolean kept = true;
12455
12456 if (values != null) {
12457 Configuration newConfig = new Configuration(mConfiguration);
12458 changes = newConfig.updateFrom(values);
12459 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012460 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012461 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012462 }
12463
Doug Zongker2bec3d42009-12-04 12:52:44 -080012464 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012465
12466 if (values.locale != null) {
12467 saveLocaleLocked(values.locale,
12468 !values.locale.equals(mConfiguration.locale),
12469 values.userSetLocale);
12470 }
12471
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012472 mConfigurationSeq++;
12473 if (mConfigurationSeq <= 0) {
12474 mConfigurationSeq = 1;
12475 }
12476 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012477 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012478 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012479
12480 AttributeCache ac = AttributeCache.instance();
12481 if (ac != null) {
12482 ac.updateConfiguration(mConfiguration);
12483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012484
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012485 // Make sure all resources in our process are updated
12486 // right now, so that anyone who is going to retrieve
12487 // resource values after we return will be sure to get
12488 // the new ones. This is especially important during
12489 // boot, where the first config change needs to guarantee
12490 // all resources have that config before following boot
12491 // code is executed.
12492 mSystemThread.applyConfigurationToResources(newConfig);
12493
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012494 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012495 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
12496 msg.obj = new Configuration(mConfiguration);
12497 mHandler.sendMessage(msg);
12498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012499
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012500 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12501 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012502 try {
12503 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012504 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012505 + app.processName + " new config " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012506 app.thread.scheduleConfigurationChanged(mConfiguration);
12507 }
12508 } catch (Exception e) {
12509 }
12510 }
12511 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012512 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12513 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012514 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
12515 null, false, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012516 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12517 broadcastIntentLocked(null, null,
12518 new Intent(Intent.ACTION_LOCALE_CHANGED),
12519 null, null, 0, null, null,
12520 null, false, false, MY_PID, Process.SYSTEM_UID);
12521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012522 }
12523 }
12524
12525 if (changes != 0 && starting == null) {
12526 // If the configuration changed, and the caller is not already
12527 // in the process of starting an activity, then find the top
12528 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012529 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012530 }
12531
12532 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012533 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012534 // And we need to make sure at this point that all other activities
12535 // are made visible with the correct configuration.
12536 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012537 }
12538
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012539 if (values != null && mWindowManager != null) {
12540 mWindowManager.setNewConfiguration(mConfiguration);
12541 }
12542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012543 return kept;
12544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012545
12546 /**
12547 * Save the locale. You must be inside a synchronized (this) block.
12548 */
12549 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12550 if(isDiff) {
12551 SystemProperties.set("user.language", l.getLanguage());
12552 SystemProperties.set("user.region", l.getCountry());
12553 }
12554
12555 if(isPersist) {
12556 SystemProperties.set("persist.sys.language", l.getLanguage());
12557 SystemProperties.set("persist.sys.country", l.getCountry());
12558 SystemProperties.set("persist.sys.localevar", l.getVariant());
12559 }
12560 }
12561
12562 // =========================================================
12563 // LIFETIME MANAGEMENT
12564 // =========================================================
12565
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012566 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
12567 ProcessRecord TOP_APP, boolean recursed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012568 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012569 // This adjustment has already been computed. If we are calling
12570 // from the top, we may have already computed our adjustment with
12571 // an earlier hidden adjustment that isn't really for us... if
12572 // so, use the new hidden adjustment.
12573 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012574 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012575 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012576 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012577 }
12578
12579 if (app.thread == null) {
12580 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012581 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012582 return (app.curAdj=ProcessList.EMPTY_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012583 }
12584
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012585 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12586 app.adjSource = null;
12587 app.adjTarget = null;
12588 app.empty = false;
12589 app.hidden = false;
12590
12591 final int activitiesSize = app.activities.size();
12592
Dianne Hackborn7d608422011-08-07 16:24:18 -070012593 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012594 // The max adjustment doesn't allow this app to be anything
12595 // below foreground, so it is not worth doing work for it.
12596 app.adjType = "fixed";
12597 app.adjSeq = mAdjSeq;
12598 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012599 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012600 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012601 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012602 // System process can do UI, and when they do we want to have
12603 // them trim their memory after the user leaves the UI. To
12604 // facilitate this, here we need to determine whether or not it
12605 // is currently showing UI.
12606 app.systemNoUi = true;
12607 if (app == TOP_APP) {
12608 app.systemNoUi = false;
12609 } else if (activitiesSize > 0) {
12610 for (int j = 0; j < activitiesSize; j++) {
12611 final ActivityRecord r = app.activities.get(j);
12612 if (r.visible) {
12613 app.systemNoUi = false;
12614 break;
12615 }
12616 }
12617 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012618 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012619 }
12620
12621 final boolean hadForegroundActivities = app.foregroundActivities;
12622
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012623 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012624 app.keeping = false;
12625 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012626
The Android Open Source Project4df24232009-03-05 14:34:35 -080012627 // Determine the importance of the process, starting with most
12628 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012630 int schedGroup;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012631 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012632 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012633 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012634 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012635 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012636 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012637 } else if (app.instrumentationClass != null) {
12638 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012639 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012640 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012641 app.adjType = "instrumentation";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012642 } else if (app.curReceiver != null ||
12643 (mPendingBroadcast != null && mPendingBroadcast.curApp == app)) {
12644 // An app that is currently receiving a broadcast also
12645 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012646 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012647 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012648 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012649 } else if (app.executingServices.size() > 0) {
12650 // An app that is currently executing a service callback also
12651 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012652 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012653 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012654 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012655 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012656 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012657 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012658 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012659 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012660 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012661 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012662 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012663 // A very not-needed process. If this is lower in the lru list,
12664 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012665 adj = hiddenAdj;
12666 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012667 app.hidden = true;
12668 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012669 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012670 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012671
12672 // Examine all activities if not already foreground.
12673 if (!app.foregroundActivities && activitiesSize > 0) {
12674 for (int j = 0; j < activitiesSize; j++) {
12675 final ActivityRecord r = app.activities.get(j);
12676 if (r.visible) {
12677 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012678 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12679 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012680 app.adjType = "visible";
12681 }
12682 schedGroup = Process.THREAD_GROUP_DEFAULT;
12683 app.hidden = false;
12684 app.foregroundActivities = true;
12685 break;
12686 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
12687 || r.state == ActivityState.STOPPING) {
12688 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012689 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12690 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012691 app.adjType = "stopping";
12692 }
12693 app.foregroundActivities = true;
12694 }
12695 }
12696 }
12697
Dianne Hackborn7d608422011-08-07 16:24:18 -070012698 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012699 if (app.foregroundServices) {
12700 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012701 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012702 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012703 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012704 } else if (app.forcingToForeground != null) {
12705 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012706 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012707 app.adjType = "force-foreground";
12708 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012709 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012710 }
12711 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012712
Dianne Hackborn7d608422011-08-07 16:24:18 -070012713 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012714 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012715 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012716 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12717 app.adjType = "heavy";
12718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012719
Dianne Hackborn7d608422011-08-07 16:24:18 -070012720 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012721 // This process is hosting what we currently consider to be the
12722 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012723 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012724 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12725 app.adjType = "home";
12726 }
12727
Joe Onorato8a9b2202010-02-26 18:56:32 -080012728 //Slog.i(TAG, "OOM " + app + ": initial adj=" + adj);
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012729
The Android Open Source Project4df24232009-03-05 14:34:35 -080012730 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012731 // there are applications dependent on our services or providers, but
12732 // this gives us a baseline and makes sure we don't get into an
12733 // infinite recursion.
12734 app.adjSeq = mAdjSeq;
12735 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012736
Christopher Tate6fa95972009-06-05 18:43:55 -070012737 if (mBackupTarget != null && app == mBackupTarget.app) {
12738 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012739 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012740 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012741 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012742 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012743 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012744 }
12745 }
12746
Dianne Hackborn7d608422011-08-07 16:24:18 -070012747 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012748 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012749 final long now = SystemClock.uptimeMillis();
12750 // This process is more important if the top activity is
12751 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012752 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012753 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012754 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012755 if (s.startRequested) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012756 if (app.hasShownUi) {
12757 // If this process has shown some UI, let it immediately
12758 // go to the LRU list because it may be pretty heavy with
12759 // UI stuff. We'll tag it with a label just to help
12760 // debug and understand what is going on.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012761 if (adj > ProcessList.SECONDARY_SERVER_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012762 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012763 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012764 } else {
12765 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
12766 // This service has seen some activity within
12767 // recent memory, so we will keep its process ahead
12768 // of the background processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012769 if (adj > ProcessList.SECONDARY_SERVER_ADJ) {
12770 adj = ProcessList.SECONDARY_SERVER_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012771 app.adjType = "started-services";
12772 app.hidden = false;
12773 }
12774 }
12775 // If we have let the service slide into the background
12776 // state, still have some text describing what it is doing
12777 // even though the service no longer has an impact.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012778 if (adj > ProcessList.SECONDARY_SERVER_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012779 app.adjType = "started-bg-services";
12780 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012781 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012782 // Don't kill this process because it is doing work; it
12783 // has said it is doing work.
12784 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012785 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012786 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012787 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012788 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012789 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012790 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012791 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012792 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012793 // XXX should compute this based on the max of
12794 // all connected clients.
12795 ConnectionRecord cr = clist.get(i);
12796 if (cr.binding.client == app) {
12797 // Binding to ourself is not interesting.
12798 continue;
12799 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012800 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012801 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012802 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012803 int myHiddenAdj = hiddenAdj;
12804 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012805 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012806 myHiddenAdj = client.hiddenAdj;
12807 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012808 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012809 }
12810 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012811 clientAdj = computeOomAdjLocked(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012812 client, myHiddenAdj, TOP_APP, true);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012813 String adjType = null;
12814 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12815 // Not doing bind OOM management, so treat
12816 // this guy more like a started service.
12817 if (app.hasShownUi) {
12818 // If this process has shown some UI, let it immediately
12819 // go to the LRU list because it may be pretty heavy with
12820 // UI stuff. We'll tag it with a label just to help
12821 // debug and understand what is going on.
12822 if (adj > clientAdj) {
12823 adjType = "bound-bg-ui-services";
12824 }
12825 clientAdj = adj;
12826 } else {
12827 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
12828 // This service has not seen activity within
12829 // recent memory, so allow it to drop to the
12830 // LRU list if there is no other reason to keep
12831 // it around. We'll also tag it with a label just
12832 // to help debug and undertand what is going on.
12833 if (adj > clientAdj) {
12834 adjType = "bound-bg-services";
12835 }
12836 clientAdj = adj;
12837 }
12838 }
12839 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012840 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012841 // If this process has recently shown UI, and
12842 // the process that is binding to it is less
12843 // important than being visible, then we don't
12844 // care about the binding as much as we care
12845 // about letting this process get into the LRU
12846 // list to be killed and restarted if needed for
12847 // memory.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012848 if (app.hasShownUi && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012849 adjType = "bound-bg-ui-services";
12850 } else {
12851 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12852 |Context.BIND_IMPORTANT)) != 0) {
12853 adj = clientAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012854 } else if (clientAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012855 adj = clientAdj;
12856 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012857 adj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012858 }
12859 if (!client.hidden) {
12860 app.hidden = false;
12861 }
12862 if (client.keeping) {
12863 app.keeping = true;
12864 }
12865 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012866 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012867 }
12868 if (adjType != null) {
12869 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012870 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12871 .REASON_SERVICE_IN_USE;
12872 app.adjSource = cr.binding.client;
12873 app.adjTarget = s.name;
12874 }
12875 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12876 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12877 schedGroup = Process.THREAD_GROUP_DEFAULT;
12878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012879 }
12880 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012881 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12882 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012883 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012884 (a.visible || a.state == ActivityState.RESUMED
12885 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012886 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012887 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12888 schedGroup = Process.THREAD_GROUP_DEFAULT;
12889 }
12890 app.hidden = false;
12891 app.adjType = "service";
12892 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12893 .REASON_SERVICE_IN_USE;
12894 app.adjSource = a;
12895 app.adjTarget = s.name;
12896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012898 }
12899 }
12900 }
12901 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012902
Dianne Hackborn287952c2010-09-22 22:34:31 -070012903 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012904 // would like to avoid killing it unless it would prevent the current
12905 // application from running. By default we put the process in
12906 // with the rest of the background processes; as we scan through
12907 // its services we may bump it up from there.
12908 if (adj > hiddenAdj) {
12909 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012910 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012911 app.adjType = "bg-services";
12912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012913 }
12914
Dianne Hackborn7d608422011-08-07 16:24:18 -070012915 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012916 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012917 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012918 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012919 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012920 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012921 if (cpr.clients.size() != 0) {
12922 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012923 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012924 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070012925 if (client == app) {
12926 // Being our own client is not interesting.
12927 continue;
12928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012929 int myHiddenAdj = hiddenAdj;
12930 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012931 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012932 myHiddenAdj = client.hiddenAdj;
12933 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012934 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012935 }
12936 }
12937 int clientAdj = computeOomAdjLocked(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012938 client, myHiddenAdj, TOP_APP, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012939 if (adj > clientAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012940 if (app.hasShownUi && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012941 app.adjType = "bg-ui-provider";
12942 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012943 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12944 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012945 app.adjType = "provider";
12946 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012947 if (!client.hidden) {
12948 app.hidden = false;
12949 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012950 if (client.keeping) {
12951 app.keeping = true;
12952 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012953 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12954 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012955 app.adjSource = client;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012956 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012957 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012958 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12959 schedGroup = Process.THREAD_GROUP_DEFAULT;
12960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012961 }
12962 }
12963 // If the provider has external (non-framework) process
12964 // dependencies, ensure that its adjustment is at least
12965 // FOREGROUND_APP_ADJ.
12966 if (cpr.externals != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012967 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12968 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012969 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012970 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012971 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012972 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012973 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012974 }
12975 }
12976 }
12977 }
12978
12979 app.curRawAdj = adj;
12980
Joe Onorato8a9b2202010-02-26 18:56:32 -080012981 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012982 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12983 if (adj > app.maxAdj) {
12984 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012985 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012986 schedGroup = Process.THREAD_GROUP_DEFAULT;
12987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012988 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012989 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012990 app.keeping = true;
12991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012992
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012993 if (app.hasAboveClient) {
12994 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12995 // then we need to drop its adjustment to be lower than the service's
12996 // in order to honor the request. We want to drop it by one adjustment
12997 // level... but there is special meaning applied to various levels so
12998 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012999 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013000 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013001 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13002 adj = ProcessList.VISIBLE_APP_ADJ;
13003 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13004 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13005 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13006 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
13007 } else if (adj < ProcessList.EMPTY_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013008 adj++;
13009 }
13010 }
13011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013012 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013013 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013014
13015 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013016 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13017 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013018 }
13019
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013020 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013021 }
13022
13023 /**
13024 * Ask a given process to GC right now.
13025 */
13026 final void performAppGcLocked(ProcessRecord app) {
13027 try {
13028 app.lastRequestedGc = SystemClock.uptimeMillis();
13029 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013030 if (app.reportLowMemory) {
13031 app.reportLowMemory = false;
13032 app.thread.scheduleLowMemory();
13033 } else {
13034 app.thread.processInBackground();
13035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013036 }
13037 } catch (Exception e) {
13038 // whatever.
13039 }
13040 }
13041
13042 /**
13043 * Returns true if things are idle enough to perform GCs.
13044 */
Josh Bartel7f208742010-02-25 11:01:44 -060013045 private final boolean canGcNowLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013046 return mParallelBroadcasts.size() == 0
13047 && mOrderedBroadcasts.size() == 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013048 && (mSleeping || (mMainStack.mResumedActivity != null &&
13049 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013050 }
13051
13052 /**
13053 * Perform GCs on all processes that are waiting for it, but only
13054 * if things are idle.
13055 */
13056 final void performAppGcsLocked() {
13057 final int N = mProcessesToGc.size();
13058 if (N <= 0) {
13059 return;
13060 }
Josh Bartel7f208742010-02-25 11:01:44 -060013061 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013062 while (mProcessesToGc.size() > 0) {
13063 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013064 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013065 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13066 <= SystemClock.uptimeMillis()) {
13067 // To avoid spamming the system, we will GC processes one
13068 // at a time, waiting a few seconds between each.
13069 performAppGcLocked(proc);
13070 scheduleAppGcsLocked();
13071 return;
13072 } else {
13073 // It hasn't been long enough since we last GCed this
13074 // process... put it in the list to wait for its time.
13075 addProcessToGcListLocked(proc);
13076 break;
13077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013078 }
13079 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013080
13081 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013082 }
13083 }
13084
13085 /**
13086 * If all looks good, perform GCs on all processes waiting for them.
13087 */
13088 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013089 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013090 performAppGcsLocked();
13091 return;
13092 }
13093 // Still not idle, wait some more.
13094 scheduleAppGcsLocked();
13095 }
13096
13097 /**
13098 * Schedule the execution of all pending app GCs.
13099 */
13100 final void scheduleAppGcsLocked() {
13101 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013102
13103 if (mProcessesToGc.size() > 0) {
13104 // Schedule a GC for the time to the next process.
13105 ProcessRecord proc = mProcessesToGc.get(0);
13106 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13107
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013108 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013109 long now = SystemClock.uptimeMillis();
13110 if (when < (now+GC_TIMEOUT)) {
13111 when = now + GC_TIMEOUT;
13112 }
13113 mHandler.sendMessageAtTime(msg, when);
13114 }
13115 }
13116
13117 /**
13118 * Add a process to the array of processes waiting to be GCed. Keeps the
13119 * list in sorted order by the last GC time. The process can't already be
13120 * on the list.
13121 */
13122 final void addProcessToGcListLocked(ProcessRecord proc) {
13123 boolean added = false;
13124 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13125 if (mProcessesToGc.get(i).lastRequestedGc <
13126 proc.lastRequestedGc) {
13127 added = true;
13128 mProcessesToGc.add(i+1, proc);
13129 break;
13130 }
13131 }
13132 if (!added) {
13133 mProcessesToGc.add(0, proc);
13134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013135 }
13136
13137 /**
13138 * Set up to ask a process to GC itself. This will either do it
13139 * immediately, or put it on the list of processes to gc the next
13140 * time things are idle.
13141 */
13142 final void scheduleAppGcLocked(ProcessRecord app) {
13143 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013144 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013145 return;
13146 }
13147 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013148 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013149 scheduleAppGcsLocked();
13150 }
13151 }
13152
Dianne Hackborn287952c2010-09-22 22:34:31 -070013153 final void checkExcessivePowerUsageLocked(boolean doKills) {
13154 updateCpuStatsNow();
13155
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013156 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013157 boolean doWakeKills = doKills;
13158 boolean doCpuKills = doKills;
13159 if (mLastPowerCheckRealtime == 0) {
13160 doWakeKills = false;
13161 }
13162 if (mLastPowerCheckUptime == 0) {
13163 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013164 }
13165 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013166 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013167 }
13168 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013169 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13170 final long curUptime = SystemClock.uptimeMillis();
13171 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13172 mLastPowerCheckRealtime = curRealtime;
13173 mLastPowerCheckUptime = curUptime;
13174 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13175 doWakeKills = false;
13176 }
13177 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13178 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013179 }
13180 int i = mLruProcesses.size();
13181 while (i > 0) {
13182 i--;
13183 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013184 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013185 long wtime;
13186 synchronized (stats) {
13187 wtime = stats.getProcessWakeTime(app.info.uid,
13188 app.pid, curRealtime);
13189 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013190 long wtimeUsed = wtime - app.lastWakeTime;
13191 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13192 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013193 StringBuilder sb = new StringBuilder(128);
13194 sb.append("Wake for ");
13195 app.toShortString(sb);
13196 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013197 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013198 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013199 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013200 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013201 sb.append((wtimeUsed*100)/realtimeSince);
13202 sb.append("%)");
13203 Slog.i(TAG, sb.toString());
13204 sb.setLength(0);
13205 sb.append("CPU for ");
13206 app.toShortString(sb);
13207 sb.append(": over ");
13208 TimeUtils.formatDuration(uptimeSince, sb);
13209 sb.append(" used ");
13210 TimeUtils.formatDuration(cputimeUsed, sb);
13211 sb.append(" (");
13212 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013213 sb.append("%)");
13214 Slog.i(TAG, sb.toString());
13215 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013216 // If a process has held a wake lock for more
13217 // than 50% of the time during this period,
13218 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013219 if (doWakeKills && realtimeSince > 0
13220 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13221 synchronized (stats) {
13222 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13223 realtimeSince, wtimeUsed);
13224 }
13225 Slog.w(TAG, "Excessive wake lock in " + app.processName
13226 + " (pid " + app.pid + "): held " + wtimeUsed
13227 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013228 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13229 app.processName, app.setAdj, "excessive wake lock");
13230 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013231 } else if (doCpuKills && uptimeSince > 0
13232 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13233 synchronized (stats) {
13234 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13235 uptimeSince, cputimeUsed);
13236 }
13237 Slog.w(TAG, "Excessive CPU in " + app.processName
13238 + " (pid " + app.pid + "): used " + cputimeUsed
13239 + " during " + uptimeSince);
13240 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13241 app.processName, app.setAdj, "excessive cpu");
13242 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013243 } else {
13244 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013245 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013246 }
13247 }
13248 }
13249 }
13250
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013251 private final void updateOomAdjLocked(
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013252 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013253 app.hiddenAdj = hiddenAdj;
13254
13255 if (app.thread == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013256 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013257 }
13258
Dianne Hackborn287952c2010-09-22 22:34:31 -070013259 final boolean wasKeeping = app.keeping;
13260
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013261 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013262
Jeff Brown10e89712011-07-08 18:52:57 -070013263 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013264 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
13265 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Jeff Brown10e89712011-07-08 18:52:57 -070013266 // If this app is transitioning from foreground to
13267 // non-foreground, have it do a gc.
13268 scheduleAppGcLocked(app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013269 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13270 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Jeff Brown10e89712011-07-08 18:52:57 -070013271 // Likewise do a gc when an app is moving in to the
13272 // background (such as a service stopping).
13273 scheduleAppGcLocked(app);
13274 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013275
Jeff Brown10e89712011-07-08 18:52:57 -070013276 if (wasKeeping && !app.keeping) {
13277 // This app is no longer something we want to keep. Note
13278 // its current wake lock time to later know to kill it if
13279 // it is not behaving well.
13280 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13281 synchronized (stats) {
13282 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13283 app.pid, SystemClock.elapsedRealtime());
13284 }
13285 app.lastCpuTime = app.curCpuTime;
13286 }
13287
13288 app.setRawAdj = app.curRawAdj;
13289 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013290 if (app.curAdj != app.setAdj) {
13291 if (Process.setOomAdj(app.pid, app.curAdj)) {
Jeff Brown10e89712011-07-08 18:52:57 -070013292 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
13293 TAG, "Set app " + app.processName +
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013294 " oom adj to " + app.curAdj + " because " + app.adjType);
13295 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013296 } else {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013297 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013298 }
13299 }
13300 if (app.setSchedGroup != app.curSchedGroup) {
13301 app.setSchedGroup = app.curSchedGroup;
13302 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13303 "Setting process group of " + app.processName
13304 + " to " + app.curSchedGroup);
13305 if (app.waitingToKill != null &&
13306 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13307 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13308 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13309 app.processName, app.setAdj, app.waitingToKill);
13310 Process.killProcessQuiet(app.pid);
13311 } else {
13312 if (true) {
13313 long oldId = Binder.clearCallingIdentity();
13314 try {
13315 Process.setProcessGroup(app.pid, app.curSchedGroup);
13316 } catch (Exception e) {
13317 Slog.w(TAG, "Failed setting process group of " + app.pid
13318 + " to " + app.curSchedGroup);
13319 e.printStackTrace();
13320 } finally {
13321 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013322 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013323 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013324 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013325 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013326 app.thread.setSchedulingGroup(app.curSchedGroup);
13327 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013328 }
13329 }
13330 }
13331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013333 }
13334
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013335 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013336 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013337 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013338 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013339 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013340 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013341 }
13342 }
13343 return resumedActivity;
13344 }
13345
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013346 private final void updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013347 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013348 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13349 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013350 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13351 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013352
13353 mAdjSeq++;
13354
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013355 updateOomAdjLocked(app, app.hiddenAdj, TOP_APP);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013356 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13357 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013358 if (nowHidden != wasHidden) {
13359 // Changed to/from hidden state, so apps after it in the LRU
13360 // list may also be changed.
13361 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013363 }
13364
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013365 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013366 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013367 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13368
13369 if (false) {
13370 RuntimeException e = new RuntimeException();
13371 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013372 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013373 }
13374
13375 mAdjSeq++;
13376
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013377 // Let's determine how many processes we have running vs.
13378 // how many slots we have for background processes; we may want
13379 // to put multiple processes in a slot of there are enough of
13380 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013381 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013382 int factor = (mLruProcesses.size()-4)/numSlots;
13383 if (factor < 1) factor = 1;
13384 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013385 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013386
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013387 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013388 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013389 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013390 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013391 int numBg = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013392 while (i > 0) {
13393 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013394 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013395 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013396 updateOomAdjLocked(app, curHiddenAdj, TOP_APP);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013397 if (curHiddenAdj < ProcessList.EMPTY_APP_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013398 && app.curAdj == curHiddenAdj) {
13399 step++;
13400 if (step >= factor) {
13401 step = 0;
13402 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013403 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013404 }
13405 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013406 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013407 numHidden++;
13408 if (numHidden > mProcessLimit) {
13409 Slog.i(TAG, "No longer want " + app.processName
13410 + " (pid " + app.pid + "): hidden #" + numHidden);
13411 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13412 app.processName, app.setAdj, "too many background");
13413 app.killedBackground = true;
13414 Process.killProcessQuiet(app.pid);
13415 } else {
13416 numBg++;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013417 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013418 } else if (app.curAdj >= ProcessList.HOME_APP_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013419 numBg++;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013421 }
13422 }
13423
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013424 // Now determine the memory trimming level of background processes.
13425 // Unfortunately we need to start at the back of the list to do this
13426 // properly. We only do this if the number of background apps we
13427 // are managing to keep around is less than half the maximum we desire;
13428 // if we are keeping a good number around, we'll let them use whatever
13429 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013430 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013431 final int N = mLruProcesses.size();
13432 factor = numBg/3;
13433 step = 0;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013434 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013435 for (i=0; i<N; i++) {
13436 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013437 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013438 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13439 try {
13440 app.thread.scheduleTrimMemory(curLevel);
13441 } catch (RemoteException e) {
13442 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013443 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013444 // For these apps we will also finish their activities
13445 // to help them free memory.
13446 mMainStack.destroyActivitiesLocked(app, false);
13447 }
13448 }
13449 app.trimMemoryLevel = curLevel;
13450 step++;
13451 if (step >= factor) {
13452 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013453 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13454 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013455 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013456 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13457 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013458 break;
13459 }
13460 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013461 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013462 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013463 && app.thread != null) {
13464 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013465 app.thread.scheduleTrimMemory(
13466 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013467 } catch (RemoteException e) {
13468 }
13469 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013470 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013471 } else if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013472 && app.pendingUiClean) {
13473 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13474 && app.thread != null) {
13475 try {
13476 app.thread.scheduleTrimMemory(
13477 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13478 } catch (RemoteException e) {
13479 }
13480 }
13481 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13482 app.pendingUiClean = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013483 } else {
13484 app.trimMemoryLevel = 0;
13485 }
13486 }
13487 } else {
13488 final int N = mLruProcesses.size();
13489 for (i=0; i<N; i++) {
13490 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013491 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013492 && app.pendingUiClean) {
13493 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13494 && app.thread != null) {
13495 try {
13496 app.thread.scheduleTrimMemory(
13497 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13498 } catch (RemoteException e) {
13499 }
13500 }
13501 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13502 app.pendingUiClean = false;
13503 } else {
13504 app.trimMemoryLevel = 0;
13505 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013506 }
13507 }
13508
13509 if (mAlwaysFinishActivities) {
13510 mMainStack.destroyActivitiesLocked(null, false);
13511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013512 }
13513
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013514 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013515 synchronized (this) {
13516 int i;
13517
13518 // First remove any unused application processes whose package
13519 // has been removed.
13520 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13521 final ProcessRecord app = mRemovedProcesses.get(i);
13522 if (app.activities.size() == 0
13523 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013524 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013525 TAG, "Exiting empty application process "
13526 + app.processName + " ("
13527 + (app.thread != null ? app.thread.asBinder() : null)
13528 + ")\n");
13529 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013530 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13531 app.processName, app.setAdj, "empty");
13532 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013533 } else {
13534 try {
13535 app.thread.scheduleExit();
13536 } catch (Exception e) {
13537 // Ignore exceptions.
13538 }
13539 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013540 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013541 mRemovedProcesses.remove(i);
13542
13543 if (app.persistent) {
13544 if (app.persistent) {
13545 addAppLocked(app.info);
13546 }
13547 }
13548 }
13549 }
13550
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013551 // Now update the oom adj for all processes.
13552 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013553 }
13554 }
13555
13556 /** This method sends the specified signal to each of the persistent apps */
13557 public void signalPersistentProcesses(int sig) throws RemoteException {
13558 if (sig != Process.SIGNAL_USR1) {
13559 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13560 }
13561
13562 synchronized (this) {
13563 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13564 != PackageManager.PERMISSION_GRANTED) {
13565 throw new SecurityException("Requires permission "
13566 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13567 }
13568
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013569 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13570 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013571 if (r.thread != null && r.persistent) {
13572 Process.sendSignal(r.pid, sig);
13573 }
13574 }
13575 }
13576 }
13577
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013578 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013579 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013580
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013581 try {
13582 synchronized (this) {
13583 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13584 // its own permission.
13585 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13586 != PackageManager.PERMISSION_GRANTED) {
13587 throw new SecurityException("Requires permission "
13588 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013589 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013590
13591 if (start && fd == null) {
13592 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013593 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013594
13595 ProcessRecord proc = null;
13596 try {
13597 int pid = Integer.parseInt(process);
13598 synchronized (mPidsSelfLocked) {
13599 proc = mPidsSelfLocked.get(pid);
13600 }
13601 } catch (NumberFormatException e) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013602 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013603
13604 if (proc == null) {
13605 HashMap<String, SparseArray<ProcessRecord>> all
13606 = mProcessNames.getMap();
13607 SparseArray<ProcessRecord> procs = all.get(process);
13608 if (procs != null && procs.size() > 0) {
13609 proc = procs.valueAt(0);
13610 }
13611 }
13612
13613 if (proc == null || proc.thread == null) {
13614 throw new IllegalArgumentException("Unknown process: " + process);
13615 }
13616
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013617 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13618 if (!isDebuggable) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013619 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13620 throw new SecurityException("Process not debuggable: " + proc);
13621 }
13622 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013623
Romain Guy7eabe552011-07-21 14:56:34 -070013624 proc.thread.profilerControl(start, path, fd, profileType);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013625 fd = null;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013626 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013627 }
13628 } catch (RemoteException e) {
13629 throw new IllegalStateException("Process disappeared");
13630 } finally {
13631 if (fd != null) {
13632 try {
13633 fd.close();
13634 } catch (IOException e) {
13635 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013636 }
13637 }
13638 }
Andy McFadden824c5102010-07-09 16:26:57 -070013639
13640 public boolean dumpHeap(String process, boolean managed,
13641 String path, ParcelFileDescriptor fd) throws RemoteException {
13642
13643 try {
13644 synchronized (this) {
13645 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13646 // its own permission (same as profileControl).
13647 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13648 != PackageManager.PERMISSION_GRANTED) {
13649 throw new SecurityException("Requires permission "
13650 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13651 }
13652
13653 if (fd == null) {
13654 throw new IllegalArgumentException("null fd");
13655 }
13656
13657 ProcessRecord proc = null;
13658 try {
13659 int pid = Integer.parseInt(process);
13660 synchronized (mPidsSelfLocked) {
13661 proc = mPidsSelfLocked.get(pid);
13662 }
13663 } catch (NumberFormatException e) {
13664 }
13665
13666 if (proc == null) {
13667 HashMap<String, SparseArray<ProcessRecord>> all
13668 = mProcessNames.getMap();
13669 SparseArray<ProcessRecord> procs = all.get(process);
13670 if (procs != null && procs.size() > 0) {
13671 proc = procs.valueAt(0);
13672 }
13673 }
13674
13675 if (proc == null || proc.thread == null) {
13676 throw new IllegalArgumentException("Unknown process: " + process);
13677 }
13678
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013679 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13680 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013681 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13682 throw new SecurityException("Process not debuggable: " + proc);
13683 }
13684 }
13685
13686 proc.thread.dumpHeap(managed, path, fd);
13687 fd = null;
13688 return true;
13689 }
13690 } catch (RemoteException e) {
13691 throw new IllegalStateException("Process disappeared");
13692 } finally {
13693 if (fd != null) {
13694 try {
13695 fd.close();
13696 } catch (IOException e) {
13697 }
13698 }
13699 }
13700 }
13701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013702 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13703 public void monitor() {
13704 synchronized (this) { }
13705 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013706
13707 public void onCoreSettingsChange(Bundle settings) {
13708 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13709 ProcessRecord processRecord = mLruProcesses.get(i);
13710 try {
13711 if (processRecord.thread != null) {
13712 processRecord.thread.setCoreSettings(settings);
13713 }
13714 } catch (RemoteException re) {
13715 /* ignore */
13716 }
13717 }
13718 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013719
13720 // Multi-user methods
13721
13722 public boolean switchUser(int userid) {
13723 // TODO
13724 return true;
13725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013726}