blob: e6dfb7f765e4c2db33b0dfb701b31e4fe904a080 [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 Hackbornde7faf62009-06-30 13:27:30 -070021import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.server.IntentResolver;
23import com.android.server.ProcessMap;
24import com.android.server.ProcessStats;
25import 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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.app.IServiceConnection;
46import android.app.IThumbnailReceiver;
47import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070048import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070049import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070051import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080052import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020053import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080054import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.ComponentName;
56import android.content.ContentResolver;
57import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020058import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.Intent;
60import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070061import android.content.IIntentReceiver;
62import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070063import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.content.pm.ActivityInfo;
65import android.content.pm.ApplicationInfo;
66import android.content.pm.ConfigurationInfo;
67import android.content.pm.IPackageDataObserver;
68import android.content.pm.IPackageManager;
69import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080070import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070072import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.content.pm.ProviderInfo;
74import android.content.pm.ResolveInfo;
75import android.content.pm.ServiceInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070076import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.res.Configuration;
78import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070079import android.net.Proxy;
80import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.net.Uri;
82import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080083import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080084import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070085import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080086import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080088import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.FileUtils;
90import android.os.Handler;
91import android.os.IBinder;
92import android.os.IPermissionController;
93import android.os.Looper;
94import android.os.Message;
95import android.os.Parcel;
96import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070098import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.RemoteException;
100import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700101import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.os.SystemClock;
103import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.util.Config;
106import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800107import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800108import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.util.PrintWriterPrinter;
110import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700111import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.view.Gravity;
113import android.view.LayoutInflater;
114import android.view.View;
115import android.view.WindowManager;
116import android.view.WindowManagerPolicy;
117
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700118import java.io.BufferedInputStream;
119import java.io.BufferedOutputStream;
120import java.io.DataInputStream;
121import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import java.io.File;
123import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700124import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700126import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200127import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800128import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import java.io.PrintWriter;
130import java.lang.IllegalStateException;
131import java.lang.ref.WeakReference;
132import java.util.ArrayList;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700133import java.util.Collections;
134import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.util.HashMap;
136import java.util.HashSet;
137import java.util.Iterator;
138import java.util.List;
139import java.util.Locale;
140import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700141import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700142import java.util.concurrent.atomic.AtomicBoolean;
143import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700145public final class ActivityManagerService extends ActivityManagerNative
146 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 static final String TAG = "ActivityManager";
148 static final boolean DEBUG = false;
149 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
150 static final boolean DEBUG_SWITCH = localLOGV || false;
151 static final boolean DEBUG_TASKS = localLOGV || false;
152 static final boolean DEBUG_PAUSE = localLOGV || false;
153 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
154 static final boolean DEBUG_TRANSITION = localLOGV || false;
155 static final boolean DEBUG_BROADCAST = localLOGV || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700156 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700158 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 static final boolean DEBUG_VISBILITY = localLOGV || false;
160 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700161 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800162 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700164 static final boolean DEBUG_RESULTS = localLOGV || false;
Christopher Tate436344a2009-09-30 16:17:37 -0700165 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700166 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700167 static final boolean DEBUG_POWER = localLOGV || false;
168 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 static final boolean VALIDATE_TOKENS = false;
170 static final boolean SHOW_ACTIVITY_START_TIME = true;
171
172 // Control over CPU and battery monitoring.
173 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
174 static final boolean MONITOR_CPU_USAGE = true;
175 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
176 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
177 static final boolean MONITOR_THREAD_CPU_USAGE = false;
178
Dianne Hackborn1655be42009-05-08 14:29:01 -0700179 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700180 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 private static final String SYSTEM_SECURE = "ro.secure";
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800183 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
185 // This is the maximum number of application processes we would like
186 // to have running. Due to the asynchronous nature of things, we can
187 // temporarily go beyond this limit.
188 static final int MAX_PROCESSES = 2;
189
190 // Set to false to leave processes running indefinitely, relying on
191 // the kernel killing them as resources are required.
192 static final boolean ENFORCE_PROCESS_LIMIT = false;
193
194 // This is the maximum number of activities that we would like to have
195 // running at a given time.
196 static final int MAX_ACTIVITIES = 20;
197
198 // Maximum number of recent tasks that we can remember.
199 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700200
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700201 // Amount of time after a call to stopAppSwitches() during which we will
202 // prevent further untrusted switches from happening.
203 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
205 // How long we wait for a launched process to attach to the activity manager
206 // before we decide it's never going to come up for real.
207 static final int PROC_START_TIMEOUT = 10*1000;
208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 // How long to wait after going idle before forcing apps to GC.
210 static final int GC_TIMEOUT = 5*1000;
211
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700212 // The minimum amount of time between successive GC requests for a process.
213 static final int GC_MIN_INTERVAL = 60*1000;
214
Dianne Hackborn287952c2010-09-22 22:34:31 -0700215 // The rate at which we check for apps using excessive power -- 15 mins.
216 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
217
218 // The minimum sample duration we will allow before deciding we have
219 // enough data on wake locks to start killing things.
220 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
221
222 // The minimum sample duration we will allow before deciding we have
223 // enough data on CPU usage to start killing things.
224 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 // How long we allow a receiver to run before giving up on it.
227 static final int BROADCAST_TIMEOUT = 10*1000;
228
229 // How long we wait for a service to finish executing.
230 static final int SERVICE_TIMEOUT = 20*1000;
231
232 // How long a service needs to be running until restarting its process
233 // is no longer considered to be a relaunch of the service.
234 static final int SERVICE_RESTART_DURATION = 5*1000;
235
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700236 // How long a service needs to be running until it will start back at
237 // SERVICE_RESTART_DURATION after being killed.
238 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
239
240 // Multiplying factor to increase restart duration time by, for each time
241 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
242 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
243
244 // The minimum amount of time between restarting services that we allow.
245 // That is, when multiple services are restarting, we won't allow each
246 // to restart less than this amount of time from the last one.
247 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 // Maximum amount of time for there to be no activity on a service before
250 // we consider it non-essential and allow its process to go on the
251 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700252 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253
254 // How long we wait until we timeout on key dispatching.
255 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
256
257 // The minimum time we allow between crashes, for us to consider this
258 // application to be bad and stop and its services and reject broadcasts.
259 static final int MIN_CRASH_INTERVAL = 60*1000;
260
261 // How long we wait until we timeout on key dispatching during instrumentation.
262 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
263
264 // OOM adjustments for processes in various states:
265
266 // This is a process without anything currently running in it. Definitely
267 // the first to go! Value set in system/rootdir/init.rc on startup.
268 // This value is initalized in the constructor, careful when refering to
269 // this static variable externally.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800270 static final int EMPTY_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271
272 // This is a process only hosting activities that are not visible,
273 // so it can be killed without any disruption. Value set in
274 // system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800275 static final int HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 static int HIDDEN_APP_MIN_ADJ;
277
The Android Open Source Project4df24232009-03-05 14:34:35 -0800278 // This is a process holding the home application -- we want to try
279 // avoiding killing it, even if it would normally be in the background,
280 // because the user interacts with it so much.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800281 static final int HOME_APP_ADJ;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800282
Christopher Tate6fa95972009-06-05 18:43:55 -0700283 // This is a process currently hosting a backup operation. Killing it
284 // is not entirely fatal but is generally a bad idea.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800285 static final int BACKUP_APP_ADJ;
Christopher Tate6fa95972009-06-05 18:43:55 -0700286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 // This is a process holding a secondary server -- killing it will not
288 // have much of an impact as far as the user is concerned. Value set in
289 // system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800290 static final int SECONDARY_SERVER_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700292 // This is a process with a heavy-weight application. It is in the
293 // background, but we want to try to avoid killing it. Value set in
294 // system/rootdir/init.rc on startup.
295 static final int HEAVY_WEIGHT_APP_ADJ;
296
297 // This is a process only hosting components that are perceptible to the
298 // user, and we really want to avoid killing them, but they are not
299 // immediately visible. An example is background music playback. Value set in
300 // system/rootdir/init.rc on startup.
301 static final int PERCEPTIBLE_APP_ADJ;
302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 // This is a process only hosting activities that are visible to the
304 // user, so we'd prefer they don't disappear. Value set in
305 // system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800306 static final int VISIBLE_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307
308 // This is the process running the current foreground app. We'd really
309 // rather not kill it! Value set in system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800310 static final int FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311
312 // This is a process running a core server, such as telephony. Definitely
313 // don't want to kill it, but doing so is not completely fatal.
314 static final int CORE_SERVER_ADJ = -12;
315
316 // The system process runs at the default adjustment.
317 static final int SYSTEM_ADJ = -16;
318
319 // Memory pages are 4K.
320 static final int PAGE_SIZE = 4*1024;
321
322 // Corresponding memory levels for above adjustments.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800323 static final int EMPTY_APP_MEM;
324 static final int HIDDEN_APP_MEM;
325 static final int HOME_APP_MEM;
326 static final int BACKUP_APP_MEM;
327 static final int SECONDARY_SERVER_MEM;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700328 static final int HEAVY_WEIGHT_APP_MEM;
329 static final int PERCEPTIBLE_APP_MEM;
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800330 static final int VISIBLE_APP_MEM;
331 static final int FOREGROUND_APP_MEM;
332
333 // The minimum number of hidden apps we want to be able to keep around,
334 // without empty apps being able to push them out of memory.
335 static final int MIN_HIDDEN_APPS = 2;
336
Dianne Hackborn8633e682010-04-22 16:03:41 -0700337 // The maximum number of hidden processes we will keep around before
338 // killing them; this is just a control to not let us go too crazy with
339 // keeping around processes on devices with large amounts of RAM.
340 static final int MAX_HIDDEN_APPS = 15;
341
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800342 // We put empty content processes after any hidden processes that have
Dianne Hackborn906497c2010-05-10 15:57:38 -0700343 // been idle for less than 15 seconds.
344 static final long CONTENT_APP_IDLE_OFFSET = 15*1000;
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800345
346 // We put empty content processes after any hidden processes that have
Dianne Hackborn906497c2010-05-10 15:57:38 -0700347 // been idle for less than 120 seconds.
348 static final long EMPTY_APP_IDLE_OFFSET = 120*1000;
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800349
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700350 static int getIntProp(String name, boolean allowZero) {
351 String str = SystemProperties.get(name);
352 if (str == null) {
353 throw new IllegalArgumentException("Property not defined: " + name);
354 }
355 int val = Integer.valueOf(str);
356 if (val == 0 && !allowZero) {
357 throw new IllegalArgumentException("Property must not be zero: " + name);
358 }
359 return val;
360 }
361
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800362 static {
363 // These values are set in system/rootdir/init.rc on startup.
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700364 FOREGROUND_APP_ADJ = getIntProp("ro.FOREGROUND_APP_ADJ", true);
365 VISIBLE_APP_ADJ = getIntProp("ro.VISIBLE_APP_ADJ", true);
366 PERCEPTIBLE_APP_ADJ = getIntProp("ro.PERCEPTIBLE_APP_ADJ", true);
367 HEAVY_WEIGHT_APP_ADJ = getIntProp("ro.HEAVY_WEIGHT_APP_ADJ", true);
368 SECONDARY_SERVER_ADJ = getIntProp("ro.SECONDARY_SERVER_ADJ", true);
369 BACKUP_APP_ADJ = getIntProp("ro.BACKUP_APP_ADJ", true);
370 HOME_APP_ADJ = getIntProp("ro.HOME_APP_ADJ", true);
371 HIDDEN_APP_MIN_ADJ = getIntProp("ro.HIDDEN_APP_MIN_ADJ", true);
372 EMPTY_APP_ADJ = getIntProp("ro.EMPTY_APP_ADJ", true);
373 // These days we use the last empty slot for hidden apps as well.
374 HIDDEN_APP_MAX_ADJ = EMPTY_APP_ADJ;
375 FOREGROUND_APP_MEM = getIntProp("ro.FOREGROUND_APP_MEM", false)*PAGE_SIZE;
376 VISIBLE_APP_MEM = getIntProp("ro.VISIBLE_APP_MEM", false)*PAGE_SIZE;
377 PERCEPTIBLE_APP_MEM = getIntProp("ro.PERCEPTIBLE_APP_MEM", false)*PAGE_SIZE;
378 HEAVY_WEIGHT_APP_MEM = getIntProp("ro.HEAVY_WEIGHT_APP_MEM", false)*PAGE_SIZE;
379 SECONDARY_SERVER_MEM = getIntProp("ro.SECONDARY_SERVER_MEM", false)*PAGE_SIZE;
380 BACKUP_APP_MEM = getIntProp("ro.BACKUP_APP_MEM", false)*PAGE_SIZE;
381 HOME_APP_MEM = getIntProp("ro.HOME_APP_MEM", false)*PAGE_SIZE;
382 HIDDEN_APP_MEM = getIntProp("ro.HIDDEN_APP_MEM", false)*PAGE_SIZE;
383 EMPTY_APP_MEM = getIntProp("ro.EMPTY_APP_MEM", false)*PAGE_SIZE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385
Dan Egnor42471dd2010-01-07 17:25:22 -0800386 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387
388 static final String[] EMPTY_STRING_ARRAY = new String[0];
389
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700390 public ActivityStack mMainStack;
391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700393 * Description of a request to start a new activity, which has been held
394 * due to app switches being disabled.
395 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700396 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700397 ActivityRecord r;
398 ActivityRecord sourceRecord;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700399 Uri[] grantedUriPermissions;
400 int grantedMode;
401 boolean onlyIfNeeded;
402 }
403
404 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
405 = new ArrayList<PendingActivityLaunch>();
406
407 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 * List of all active broadcasts that are to be executed immediately
409 * (without waiting for another broadcast to finish). Currently this only
410 * contains broadcasts to registered receivers, to avoid spinning up
411 * a bunch of processes to execute IntentReceiver components.
412 */
413 final ArrayList<BroadcastRecord> mParallelBroadcasts
414 = new ArrayList<BroadcastRecord>();
415
416 /**
417 * List of all active broadcasts that are to be executed one at a time.
418 * The object at the top of the list is the currently activity broadcasts;
419 * those after it are waiting for the top to finish..
420 */
421 final ArrayList<BroadcastRecord> mOrderedBroadcasts
422 = new ArrayList<BroadcastRecord>();
423
424 /**
Dianne Hackborn12527f92009-11-11 17:39:50 -0800425 * Historical data of past broadcasts, for debugging.
426 */
427 static final int MAX_BROADCAST_HISTORY = 100;
428 final BroadcastRecord[] mBroadcastHistory
429 = new BroadcastRecord[MAX_BROADCAST_HISTORY];
430
431 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 * Set when we current have a BROADCAST_INTENT_MSG in flight.
433 */
434 boolean mBroadcastsScheduled = false;
435
436 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 * Activity we have told the window manager to have key focus.
438 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700439 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700440 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 * List of intents that were used to start the most recent tasks.
442 */
443 final ArrayList<TaskRecord> mRecentTasks
444 = new ArrayList<TaskRecord>();
445
446 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 * All of the applications we currently have running organized by name.
448 * The keys are strings of the application package name (as
449 * returned by the package manager), and the keys are ApplicationRecord
450 * objects.
451 */
452 final ProcessMap<ProcessRecord> mProcessNames
453 = new ProcessMap<ProcessRecord>();
454
455 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700456 * The currently running heavy-weight process, if any.
457 */
458 ProcessRecord mHeavyWeightProcess = null;
459
460 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 * The last time that various processes have crashed.
462 */
463 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
464
465 /**
466 * Set of applications that we consider to be bad, and will reject
467 * incoming broadcasts from (which the user has no control over).
468 * Processes are added to this set when they have crashed twice within
469 * a minimum amount of time; they are removed from it when they are
470 * later restarted (hopefully due to some user action). The value is the
471 * time it was added to the list.
472 */
473 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
474
475 /**
476 * All of the processes we currently have running organized by pid.
477 * The keys are the pid running the application.
478 *
479 * <p>NOTE: This object is protected by its own lock, NOT the global
480 * activity manager lock!
481 */
482 final SparseArray<ProcessRecord> mPidsSelfLocked
483 = new SparseArray<ProcessRecord>();
484
485 /**
486 * All of the processes that have been forced to be foreground. The key
487 * is the pid of the caller who requested it (we hold a death
488 * link on it).
489 */
490 abstract class ForegroundToken implements IBinder.DeathRecipient {
491 int pid;
492 IBinder token;
493 }
494 final SparseArray<ForegroundToken> mForegroundProcesses
495 = new SparseArray<ForegroundToken>();
496
497 /**
498 * List of records for processes that someone had tried to start before the
499 * system was ready. We don't start them at that point, but ensure they
500 * are started by the time booting is complete.
501 */
502 final ArrayList<ProcessRecord> mProcessesOnHold
503 = new ArrayList<ProcessRecord>();
504
505 /**
506 * List of records for processes that we have started and are waiting
507 * for them to call back. This is really only needed when running in
508 * single processes mode, in which case we do not have a unique pid for
509 * each process.
510 */
511 final ArrayList<ProcessRecord> mStartingProcesses
512 = new ArrayList<ProcessRecord>();
513
514 /**
515 * List of persistent applications that are in the process
516 * of being started.
517 */
518 final ArrayList<ProcessRecord> mPersistentStartingProcesses
519 = new ArrayList<ProcessRecord>();
520
521 /**
522 * Processes that are being forcibly torn down.
523 */
524 final ArrayList<ProcessRecord> mRemovedProcesses
525 = new ArrayList<ProcessRecord>();
526
527 /**
528 * List of running applications, sorted by recent usage.
529 * The first entry in the list is the least recently used.
530 * It contains ApplicationRecord objects. This list does NOT include
531 * any persistent application records (since we never want to exit them).
532 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800533 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 = new ArrayList<ProcessRecord>();
535
536 /**
537 * List of processes that should gc as soon as things are idle.
538 */
539 final ArrayList<ProcessRecord> mProcessesToGc
540 = new ArrayList<ProcessRecord>();
541
542 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800543 * This is the process holding what we currently consider to be
544 * the "home" activity.
545 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700546 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800547
548 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 * Set of PendingResultRecord objects that are currently active.
550 */
551 final HashSet mPendingResultRecords = new HashSet();
552
553 /**
554 * Set of IntentSenderRecord objects that are currently active.
555 */
556 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
557 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
558
559 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800560 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700561 * already logged DropBox entries for. Guarded by itself. If
562 * something (rogue user app) forces this over
563 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
564 */
565 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
566 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
567
568 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700569 * Strict Mode background batched logging state.
570 *
571 * The string buffer is guarded by itself, and its lock is also
572 * used to determine if another batched write is already
573 * in-flight.
574 */
575 private final StringBuilder mStrictModeBuffer = new StringBuilder();
576
577 /**
Jeff Brown4d94a762010-09-23 11:33:28 -0700578 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
579 */
580 private boolean mPendingBroadcastTimeoutMessage;
581
582 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 * Intent broadcast that we have tried to start, but are
584 * waiting for its application's process to be created. We only
585 * need one (instead of a list) because we always process broadcasts
586 * one at a time, so no others can be started while waiting for this
587 * one.
588 */
589 BroadcastRecord mPendingBroadcast = null;
590
591 /**
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700592 * The receiver index that is pending, to restart the broadcast if needed.
593 */
594 int mPendingBroadcastRecvIndex;
595
596 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 * Keeps track of all IIntentReceivers that have been registered for
598 * broadcasts. Hash keys are the receiver IBinder, hash value is
599 * a ReceiverList.
600 */
601 final HashMap mRegisteredReceivers = new HashMap();
602
603 /**
604 * Resolver for broadcast intents to registered receivers.
605 * Holds BroadcastFilter (subclass of IntentFilter).
606 */
607 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
608 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
609 @Override
610 protected boolean allowFilterResult(
611 BroadcastFilter filter, List<BroadcastFilter> dest) {
612 IBinder target = filter.receiverList.receiver.asBinder();
613 for (int i=dest.size()-1; i>=0; i--) {
614 if (dest.get(i).receiverList.receiver.asBinder() == target) {
615 return false;
616 }
617 }
618 return true;
619 }
620 };
621
622 /**
623 * State of all active sticky broadcasts. Keys are the action of the
624 * sticky Intent, values are an ArrayList of all broadcasted intents with
625 * that action (which should usually be one).
626 */
627 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
628 new HashMap<String, ArrayList<Intent>>();
629
630 /**
631 * All currently running services.
632 */
633 final HashMap<ComponentName, ServiceRecord> mServices =
634 new HashMap<ComponentName, ServiceRecord>();
635
636 /**
637 * All currently running services indexed by the Intent used to start them.
638 */
639 final HashMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent =
640 new HashMap<Intent.FilterComparison, ServiceRecord>();
641
642 /**
643 * All currently bound service connections. Keys are the IBinder of
644 * the client's IServiceConnection.
645 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700646 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
647 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648
649 /**
650 * List of services that we have been asked to start,
651 * but haven't yet been able to. It is used to hold start requests
652 * while waiting for their corresponding application thread to get
653 * going.
654 */
655 final ArrayList<ServiceRecord> mPendingServices
656 = new ArrayList<ServiceRecord>();
657
658 /**
659 * List of services that are scheduled to restart following a crash.
660 */
661 final ArrayList<ServiceRecord> mRestartingServices
662 = new ArrayList<ServiceRecord>();
663
664 /**
665 * List of services that are in the process of being stopped.
666 */
667 final ArrayList<ServiceRecord> mStoppingServices
668 = new ArrayList<ServiceRecord>();
669
670 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700671 * Backup/restore process management
672 */
673 String mBackupAppName = null;
674 BackupRecord mBackupTarget = null;
675
676 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 * List of PendingThumbnailsRecord objects of clients who are still
678 * waiting to receive all of the thumbnails for a task.
679 */
680 final ArrayList mPendingThumbnails = new ArrayList();
681
682 /**
683 * List of HistoryRecord objects that have been finished and must
684 * still report back to a pending thumbnail receiver.
685 */
686 final ArrayList mCancelledThumbnails = new ArrayList();
687
688 /**
689 * All of the currently running global content providers. Keys are a
690 * string containing the provider name and values are a
691 * ContentProviderRecord object containing the data about it. Note
692 * that a single provider may be published under multiple names, so
693 * there may be multiple entries here for a single one in mProvidersByClass.
694 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700695 final HashMap<String, ContentProviderRecord> mProvidersByName
696 = new HashMap<String, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697
698 /**
699 * All of the currently running global content providers. Keys are a
700 * string containing the provider's implementation class and values are a
701 * ContentProviderRecord object containing the data about it.
702 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700703 final HashMap<String, ContentProviderRecord> mProvidersByClass
704 = new HashMap<String, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705
706 /**
707 * List of content providers who have clients waiting for them. The
708 * application is currently being launched and the provider will be
709 * removed from this list once it is published.
710 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700711 final ArrayList<ContentProviderRecord> mLaunchingProviders
712 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713
714 /**
715 * Global set of specific Uri permissions that have been granted.
716 */
717 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
718 = new SparseArray<HashMap<Uri, UriPermission>>();
719
720 /**
721 * Thread-local storage used to carry caller permissions over through
722 * indirect content-provider access.
723 * @see #ActivityManagerService.openContentUri()
724 */
725 private class Identity {
726 public int pid;
727 public int uid;
728
729 Identity(int _pid, int _uid) {
730 pid = _pid;
731 uid = _uid;
732 }
733 }
734 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
735
736 /**
737 * All information we have collected about the runtime performance of
738 * any user id that can impact battery performance.
739 */
740 final BatteryStatsService mBatteryStatsService;
741
742 /**
743 * information about component usage
744 */
745 final UsageStatsService mUsageStatsService;
746
747 /**
748 * Current configuration information. HistoryRecord objects are given
749 * a reference to this object to indicate which configuration they are
750 * currently running in, so this object must be kept immutable.
751 */
752 Configuration mConfiguration = new Configuration();
753
754 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800755 * Current sequencing integer of the configuration, for skipping old
756 * configurations.
757 */
758 int mConfigurationSeq = 0;
759
760 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700761 * Hardware-reported OpenGLES version.
762 */
763 final int GL_ES_VERSION;
764
765 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 * List of initialization arguments to pass to all processes when binding applications to them.
767 * For example, references to the commonly used services.
768 */
769 HashMap<String, IBinder> mAppBindArgs;
770
771 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700772 * Temporary to avoid allocations. Protected by main lock.
773 */
774 final StringBuilder mStringBuilder = new StringBuilder(256);
775
776 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 * Used to control how we initialize the service.
778 */
779 boolean mStartRunning = false;
780 ComponentName mTopComponent;
781 String mTopAction;
782 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700783 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 boolean mSystemReady = false;
785 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700786 boolean mWaitingUpdate = false;
787 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700788 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700789 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790
791 Context mContext;
792
793 int mFactoryTest;
794
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700795 boolean mCheckedForSetup;
796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700798 * The time at which we will allow normal application switches again,
799 * after a call to {@link #stopAppSwitches()}.
800 */
801 long mAppSwitchesAllowedTime;
802
803 /**
804 * This is set to true after the first switch after mAppSwitchesAllowedTime
805 * is set; any switches after that will clear the time.
806 */
807 boolean mDidAppSwitch;
808
809 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700810 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700811 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700812 long mLastPowerCheckRealtime;
813
814 /**
815 * Last time (in uptime) at which we checked for power usage.
816 */
817 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700818
819 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 * Set while we are wanting to sleep, to prevent any
821 * activities from being started/resumed.
822 */
823 boolean mSleeping = false;
824
825 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700826 * Set if we are shutting down the system, similar to sleeping.
827 */
828 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829
830 /**
831 * Task identifier that activities are currently being started
832 * in. Incremented each time a new task is created.
833 * todo: Replace this with a TokenSpace class that generates non-repeating
834 * integers that won't wrap.
835 */
836 int mCurTask = 1;
837
838 /**
839 * Current sequence id for oom_adj computation traversal.
840 */
841 int mAdjSeq = 0;
842
843 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700844 * Current sequence id for process LRU updating.
845 */
846 int mLruSeq = 0;
847
848 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 * Set to true if the ANDROID_SIMPLE_PROCESS_MANAGEMENT envvar
850 * is set, indicating the user wants processes started in such a way
851 * that they can use ANDROID_PROCESS_WRAPPER and know what will be
852 * running in each process (thus no pre-initialized process, etc).
853 */
854 boolean mSimpleProcessManagement = false;
855
856 /**
857 * System monitoring: number of processes that died since the last
858 * N procs were started.
859 */
860 int[] mProcDeaths = new int[20];
861
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700862 /**
863 * This is set if we had to do a delayed dexopt of an app before launching
864 * it, to increasing the ANR timeouts in that case.
865 */
866 boolean mDidDexOpt;
867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 String mDebugApp = null;
869 boolean mWaitForDebugger = false;
870 boolean mDebugTransient = false;
871 String mOrigDebugApp = null;
872 boolean mOrigWaitForDebugger = false;
873 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700874 IActivityController mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700876 final RemoteCallbackList<IActivityWatcher> mWatchers
877 = new RemoteCallbackList<IActivityWatcher>();
878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 /**
880 * Callback of last caller to {@link #requestPss}.
881 */
882 Runnable mRequestPssCallback;
883
884 /**
885 * Remaining processes for which we are waiting results from the last
886 * call to {@link #requestPss}.
887 */
888 final ArrayList<ProcessRecord> mRequestPssList
889 = new ArrayList<ProcessRecord>();
890
891 /**
892 * Runtime statistics collection thread. This object's lock is used to
893 * protect all related state.
894 */
895 final Thread mProcessStatsThread;
896
897 /**
898 * Used to collect process stats when showing not responding dialog.
899 * Protected by mProcessStatsThread.
900 */
901 final ProcessStats mProcessStats = new ProcessStats(
902 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700903 final AtomicLong mLastCpuTime = new AtomicLong(0);
904 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 long mLastWriteTime = 0;
907
908 /**
909 * Set to true after the system has finished booting.
910 */
911 boolean mBooted = false;
912
913 int mProcessLimit = 0;
914
915 WindowManagerService mWindowManager;
916
917 static ActivityManagerService mSelf;
918 static ActivityThread mSystemThread;
919
920 private final class AppDeathRecipient implements IBinder.DeathRecipient {
921 final ProcessRecord mApp;
922 final int mPid;
923 final IApplicationThread mAppThread;
924
925 AppDeathRecipient(ProcessRecord app, int pid,
926 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800927 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 TAG, "New death recipient " + this
929 + " for thread " + thread.asBinder());
930 mApp = app;
931 mPid = pid;
932 mAppThread = thread;
933 }
934
935 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800936 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 TAG, "Death received in " + this
938 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 synchronized(ActivityManagerService.this) {
940 appDiedLocked(mApp, mPid, mAppThread);
941 }
942 }
943 }
944
945 static final int SHOW_ERROR_MSG = 1;
946 static final int SHOW_NOT_RESPONDING_MSG = 2;
947 static final int SHOW_FACTORY_ERROR_MSG = 3;
948 static final int UPDATE_CONFIGURATION_MSG = 4;
949 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
950 static final int WAIT_FOR_DEBUGGER_MSG = 6;
951 static final int BROADCAST_INTENT_MSG = 7;
952 static final int BROADCAST_TIMEOUT_MSG = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 static final int SERVICE_TIMEOUT_MSG = 12;
954 static final int UPDATE_TIME_ZONE = 13;
955 static final int SHOW_UID_ERROR_MSG = 14;
956 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700958 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700959 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800960 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700961 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
962 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700963 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700964 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700965 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700966 static final int UPDATE_HTTP_PROXY = 29;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967
968 AlertDialog mUidAlert;
969
970 final Handler mHandler = new Handler() {
971 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800972 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 //}
974
975 public void handleMessage(Message msg) {
976 switch (msg.what) {
977 case SHOW_ERROR_MSG: {
978 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 synchronized (ActivityManagerService.this) {
980 ProcessRecord proc = (ProcessRecord)data.get("app");
981 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800982 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 return;
984 }
985 AppErrorResult res = (AppErrorResult) data.get("result");
Dianne Hackborn55280a92009-05-07 15:53:46 -0700986 if (!mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800987 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 d.show();
989 proc.crashDialog = d;
990 } else {
991 // The device is asleep, so just pretend that the user
992 // saw a crash dialog and hit "force quit".
993 res.set(0);
994 }
995 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700996
997 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 } break;
999 case SHOW_NOT_RESPONDING_MSG: {
1000 synchronized (ActivityManagerService.this) {
1001 HashMap data = (HashMap) msg.obj;
1002 ProcessRecord proc = (ProcessRecord)data.get("app");
1003 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001004 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 return;
1006 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001007
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001008 Intent intent = new Intent("android.intent.action.ANR");
1009 if (!mProcessesReady) {
1010 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1011 }
1012 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -08001013 null, null, 0, null, null, null,
1014 false, false, MY_PID, Process.SYSTEM_UID);
1015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001017 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 d.show();
1019 proc.anrDialog = d;
1020 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001021
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001022 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001024 case SHOW_STRICT_MODE_VIOLATION_MSG: {
1025 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1026 synchronized (ActivityManagerService.this) {
1027 ProcessRecord proc = (ProcessRecord) data.get("app");
1028 if (proc == null) {
1029 Slog.e(TAG, "App not found when showing strict mode dialog.");
1030 break;
1031 }
1032 if (proc.crashDialog != null) {
1033 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1034 return;
1035 }
1036 AppErrorResult res = (AppErrorResult) data.get("result");
1037 if (!mSleeping && !mShuttingDown) {
1038 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
1039 d.show();
1040 proc.crashDialog = d;
1041 } else {
1042 // The device is asleep, so just pretend that the user
1043 // saw a crash dialog and hit "force quit".
1044 res.set(0);
1045 }
1046 }
1047 ensureBootCompleted();
1048 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 case SHOW_FACTORY_ERROR_MSG: {
1050 Dialog d = new FactoryErrorDialog(
1051 mContext, msg.getData().getCharSequence("msg"));
1052 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001053 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 } break;
1055 case UPDATE_CONFIGURATION_MSG: {
1056 final ContentResolver resolver = mContext.getContentResolver();
1057 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1058 } break;
1059 case GC_BACKGROUND_PROCESSES_MSG: {
1060 synchronized (ActivityManagerService.this) {
1061 performAppGcsIfAppropriateLocked();
1062 }
1063 } break;
1064 case WAIT_FOR_DEBUGGER_MSG: {
1065 synchronized (ActivityManagerService.this) {
1066 ProcessRecord app = (ProcessRecord)msg.obj;
1067 if (msg.arg1 != 0) {
1068 if (!app.waitedForDebugger) {
1069 Dialog d = new AppWaitingForDebuggerDialog(
1070 ActivityManagerService.this,
1071 mContext, app);
1072 app.waitDialog = d;
1073 app.waitedForDebugger = true;
1074 d.show();
1075 }
1076 } else {
1077 if (app.waitDialog != null) {
1078 app.waitDialog.dismiss();
1079 app.waitDialog = null;
1080 }
1081 }
1082 }
1083 } break;
1084 case BROADCAST_INTENT_MSG: {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001085 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 TAG, "Received BROADCAST_INTENT_MSG");
1087 processNextBroadcast(true);
1088 } break;
1089 case BROADCAST_TIMEOUT_MSG: {
Jeff Brown4d94a762010-09-23 11:33:28 -07001090 synchronized (ActivityManagerService.this) {
1091 broadcastTimeoutLocked(true);
Jeff Hamiltonacf84742010-05-25 22:10:18 -05001092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001095 if (mDidDexOpt) {
1096 mDidDexOpt = false;
1097 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1098 nmsg.obj = msg.obj;
1099 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
1100 return;
1101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 serviceTimeout((ProcessRecord)msg.obj);
1103 } break;
1104 case UPDATE_TIME_ZONE: {
1105 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001106 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1107 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 if (r.thread != null) {
1109 try {
1110 r.thread.updateTimeZone();
1111 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001112 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 }
1114 }
1115 }
1116 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001117 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001118 case CLEAR_DNS_CACHE: {
1119 synchronized (ActivityManagerService.this) {
1120 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1121 ProcessRecord r = mLruProcesses.get(i);
1122 if (r.thread != null) {
1123 try {
1124 r.thread.clearDnsCache();
1125 } catch (RemoteException ex) {
1126 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1127 }
1128 }
1129 }
1130 }
1131 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001132 case UPDATE_HTTP_PROXY: {
1133 ProxyProperties proxy = (ProxyProperties)msg.obj;
1134 String host = "";
1135 String port = "";
1136 String exclList = "";
1137 if (proxy != null) {
1138 host = proxy.getHost();
1139 port = Integer.toString(proxy.getPort());
1140 exclList = proxy.getExclusionList();
1141 }
1142 synchronized (ActivityManagerService.this) {
1143 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1144 ProcessRecord r = mLruProcesses.get(i);
1145 if (r.thread != null) {
1146 try {
1147 r.thread.setHttpProxy(host, port, exclList);
1148 } catch (RemoteException ex) {
1149 Slog.w(TAG, "Failed to update http proxy for: " +
1150 r.info.processName);
1151 }
1152 }
1153 }
1154 }
1155 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 case SHOW_UID_ERROR_MSG: {
1157 // XXX This is a temporary dialog, no need to localize.
1158 AlertDialog d = new BaseErrorDialog(mContext);
1159 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1160 d.setCancelable(false);
1161 d.setTitle("System UIDs Inconsistent");
1162 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 +02001163 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1165 mUidAlert = d;
1166 d.show();
1167 } break;
1168 case IM_FEELING_LUCKY_MSG: {
1169 if (mUidAlert != null) {
1170 mUidAlert.dismiss();
1171 mUidAlert = null;
1172 }
1173 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001175 if (mDidDexOpt) {
1176 mDidDexOpt = false;
1177 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1178 nmsg.obj = msg.obj;
1179 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1180 return;
1181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 ProcessRecord app = (ProcessRecord)msg.obj;
1183 synchronized (ActivityManagerService.this) {
1184 processStartTimedOutLocked(app);
1185 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001186 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001187 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1188 synchronized (ActivityManagerService.this) {
1189 doPendingActivityLaunchesLocked(true);
1190 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001191 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001192 case KILL_APPLICATION_MSG: {
1193 synchronized (ActivityManagerService.this) {
1194 int uid = msg.arg1;
1195 boolean restart = (msg.arg2 == 1);
1196 String pkg = (String) msg.obj;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001197 forceStopPackageLocked(pkg, uid, restart, false, true);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001198 }
1199 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001200 case FINALIZE_PENDING_INTENT_MSG: {
1201 ((PendingIntentRecord)msg.obj).completeFinalize();
1202 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001203 case POST_HEAVY_NOTIFICATION_MSG: {
1204 INotificationManager inm = NotificationManager.getService();
1205 if (inm == null) {
1206 return;
1207 }
1208
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001209 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001210 ProcessRecord process = root.app;
1211 if (process == null) {
1212 return;
1213 }
1214
1215 try {
1216 Context context = mContext.createPackageContext(process.info.packageName, 0);
1217 String text = mContext.getString(R.string.heavy_weight_notification,
1218 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1219 Notification notification = new Notification();
1220 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1221 notification.when = 0;
1222 notification.flags = Notification.FLAG_ONGOING_EVENT;
1223 notification.tickerText = text;
1224 notification.defaults = 0; // please be quiet
1225 notification.sound = null;
1226 notification.vibrate = null;
1227 notification.setLatestEventInfo(context, text,
1228 mContext.getText(R.string.heavy_weight_notification_detail),
1229 PendingIntent.getActivity(mContext, 0, root.intent,
1230 PendingIntent.FLAG_CANCEL_CURRENT));
1231
1232 try {
1233 int[] outId = new int[1];
1234 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1235 notification, outId);
1236 } catch (RuntimeException e) {
1237 Slog.w(ActivityManagerService.TAG,
1238 "Error showing notification for heavy-weight app", e);
1239 } catch (RemoteException e) {
1240 }
1241 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001242 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001243 }
1244 } break;
1245 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1246 INotificationManager inm = NotificationManager.getService();
1247 if (inm == null) {
1248 return;
1249 }
1250 try {
1251 inm.cancelNotification("android",
1252 R.string.heavy_weight_notification);
1253 } catch (RuntimeException e) {
1254 Slog.w(ActivityManagerService.TAG,
1255 "Error canceling notification for service", e);
1256 } catch (RemoteException e) {
1257 }
1258 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001259 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1260 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001261 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001262 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001263 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1264 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001265 }
1266 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 }
1268 }
1269 };
1270
1271 public static void setSystemProcess() {
1272 try {
1273 ActivityManagerService m = mSelf;
1274
1275 ServiceManager.addService("activity", m);
1276 ServiceManager.addService("meminfo", new MemBinder(m));
1277 if (MONITOR_CPU_USAGE) {
1278 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 ServiceManager.addService("permission", new PermissionController(m));
1281
1282 ApplicationInfo info =
1283 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001284 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001285 mSystemThread.installSystemApplicationInfo(info);
1286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 synchronized (mSelf) {
1288 ProcessRecord app = mSelf.newProcessRecordLocked(
1289 mSystemThread.getApplicationThread(), info,
1290 info.processName);
1291 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001292 app.pid = MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 app.maxAdj = SYSTEM_ADJ;
1294 mSelf.mProcessNames.put(app.processName, app.info.uid, app);
1295 synchronized (mSelf.mPidsSelfLocked) {
1296 mSelf.mPidsSelfLocked.put(app.pid, app);
1297 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001298 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 }
1300 } catch (PackageManager.NameNotFoundException e) {
1301 throw new RuntimeException(
1302 "Unable to find android system package", e);
1303 }
1304 }
1305
1306 public void setWindowManager(WindowManagerService wm) {
1307 mWindowManager = wm;
1308 }
1309
1310 public static final Context main(int factoryTest) {
1311 AThread thr = new AThread();
1312 thr.start();
1313
1314 synchronized (thr) {
1315 while (thr.mService == null) {
1316 try {
1317 thr.wait();
1318 } catch (InterruptedException e) {
1319 }
1320 }
1321 }
1322
1323 ActivityManagerService m = thr.mService;
1324 mSelf = m;
1325 ActivityThread at = ActivityThread.systemMain();
1326 mSystemThread = at;
1327 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001328 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 m.mContext = context;
1330 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001331 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332
1333 m.mBatteryStatsService.publish(context);
1334 m.mUsageStatsService.publish(context);
1335
1336 synchronized (thr) {
1337 thr.mReady = true;
1338 thr.notifyAll();
1339 }
1340
1341 m.startRunning(null, null, null, null);
1342
1343 return context;
1344 }
1345
1346 public static ActivityManagerService self() {
1347 return mSelf;
1348 }
1349
1350 static class AThread extends Thread {
1351 ActivityManagerService mService;
1352 boolean mReady = false;
1353
1354 public AThread() {
1355 super("ActivityManager");
1356 }
1357
1358 public void run() {
1359 Looper.prepare();
1360
1361 android.os.Process.setThreadPriority(
1362 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001363 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364
1365 ActivityManagerService m = new ActivityManagerService();
1366
1367 synchronized (this) {
1368 mService = m;
1369 notifyAll();
1370 }
1371
1372 synchronized (this) {
1373 while (!mReady) {
1374 try {
1375 wait();
1376 } catch (InterruptedException e) {
1377 }
1378 }
1379 }
1380
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001381 // For debug builds, log event loop stalls to dropbox for analysis.
1382 if (StrictMode.conditionallyEnableDebugLogging()) {
1383 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1384 }
1385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 Looper.loop();
1387 }
1388 }
1389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 static class MemBinder extends Binder {
1391 ActivityManagerService mActivityManagerService;
1392 MemBinder(ActivityManagerService activityManagerService) {
1393 mActivityManagerService = activityManagerService;
1394 }
1395
1396 @Override
1397 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1398 ActivityManagerService service = mActivityManagerService;
1399 ArrayList<ProcessRecord> procs;
1400 synchronized (mActivityManagerService) {
1401 if (args != null && args.length > 0
1402 && args[0].charAt(0) != '-') {
1403 procs = new ArrayList<ProcessRecord>();
1404 int pid = -1;
1405 try {
1406 pid = Integer.parseInt(args[0]);
1407 } catch (NumberFormatException e) {
1408
1409 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001410 for (int i=service.mLruProcesses.size()-1; i>=0; i--) {
1411 ProcessRecord proc = service.mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 if (proc.pid == pid) {
1413 procs.add(proc);
1414 } else if (proc.processName.equals(args[0])) {
1415 procs.add(proc);
1416 }
1417 }
1418 if (procs.size() <= 0) {
1419 pw.println("No process found for: " + args[0]);
1420 return;
1421 }
1422 } else {
Dianne Hackborn472ad872010-04-07 17:31:48 -07001423 procs = new ArrayList<ProcessRecord>(service.mLruProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425 }
1426 dumpApplicationMemoryUsage(fd, pw, procs, " ", args);
1427 }
1428 }
1429
1430 static class CpuBinder extends Binder {
1431 ActivityManagerService mActivityManagerService;
1432 CpuBinder(ActivityManagerService activityManagerService) {
1433 mActivityManagerService = activityManagerService;
1434 }
1435
1436 @Override
1437 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1438 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001439 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1440 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1441 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 }
1443 }
1444 }
1445
1446 private ActivityManagerService() {
1447 String v = System.getenv("ANDROID_SIMPLE_PROCESS_MANAGEMENT");
1448 if (v != null && Integer.getInteger(v) != 0) {
1449 mSimpleProcessManagement = true;
1450 }
1451 v = System.getenv("ANDROID_DEBUG_APP");
1452 if (v != null) {
1453 mSimpleProcessManagement = true;
1454 }
1455
Joe Onorato8a9b2202010-02-26 18:56:32 -08001456 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 File dataDir = Environment.getDataDirectory();
1459 File systemDir = new File(dataDir, "system");
1460 systemDir.mkdirs();
1461 mBatteryStatsService = new BatteryStatsService(new File(
1462 systemDir, "batterystats.bin").toString());
1463 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001464 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001465 mOnBattery = DEBUG_POWER ? true
1466 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001467 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001469 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001470 systemDir, "usagestats").toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471
Jack Palevichb90d28c2009-07-22 15:35:24 -07001472 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1473 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1474
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001475 mConfiguration.setToDefaults();
1476 mConfiguration.locale = Locale.getDefault();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 mProcessStats.init();
1478
1479 // Add ourself to the Watchdog monitors.
1480 Watchdog.getInstance().addMonitor(this);
1481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 mProcessStatsThread = new Thread("ProcessStats") {
1483 public void run() {
1484 while (true) {
1485 try {
1486 try {
1487 synchronized(this) {
1488 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001489 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001491 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 // + ", write delay=" + nextWriteDelay);
1493 if (nextWriteDelay < nextCpuDelay) {
1494 nextCpuDelay = nextWriteDelay;
1495 }
1496 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001497 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 this.wait(nextCpuDelay);
1499 }
1500 }
1501 } catch (InterruptedException e) {
1502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 updateCpuStatsNow();
1504 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001505 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507 }
1508 }
1509 };
1510 mProcessStatsThread.start();
1511 }
1512
1513 @Override
1514 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1515 throws RemoteException {
1516 try {
1517 return super.onTransact(code, data, reply, flags);
1518 } catch (RuntimeException e) {
1519 // The activity manager only throws security exceptions, so let's
1520 // log all others.
1521 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001522 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 }
1524 throw e;
1525 }
1526 }
1527
1528 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001529 final long now = SystemClock.uptimeMillis();
1530 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1531 return;
1532 }
1533 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1534 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 mProcessStatsThread.notify();
1536 }
1537 }
1538 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 void updateCpuStatsNow() {
1541 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001542 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 final long now = SystemClock.uptimeMillis();
1544 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001547 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1548 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 haveNewCpuStats = true;
1550 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001551 //Slog.i(TAG, mProcessStats.printCurrentState());
1552 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 // + mProcessStats.getTotalCpuPercent() + "%");
1554
Joe Onorato8a9b2202010-02-26 18:56:32 -08001555 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 if ("true".equals(SystemProperties.get("events.cpu"))) {
1557 int user = mProcessStats.getLastUserTime();
1558 int system = mProcessStats.getLastSystemTime();
1559 int iowait = mProcessStats.getLastIoWaitTime();
1560 int irq = mProcessStats.getLastIrqTime();
1561 int softIrq = mProcessStats.getLastSoftIrqTime();
1562 int idle = mProcessStats.getLastIdleTime();
1563
1564 int total = user + system + iowait + irq + softIrq + idle;
1565 if (total == 0) total = 1;
1566
Doug Zongker2bec3d42009-12-04 12:52:44 -08001567 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 ((user+system+iowait+irq+softIrq) * 100) / total,
1569 (user * 100) / total,
1570 (system * 100) / total,
1571 (iowait * 100) / total,
1572 (irq * 100) / total,
1573 (softIrq * 100) / total);
1574 }
1575 }
1576
Amith Yamasanie43530a2009-08-21 13:11:37 -07001577 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001578 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001579 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 synchronized(mPidsSelfLocked) {
1581 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001582 if (mOnBattery) {
1583 int perc = bstats.startAddingCpuLocked();
1584 int totalUTime = 0;
1585 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001586 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001588 ProcessStats.Stats st = mProcessStats.getStats(i);
1589 if (!st.working) {
1590 continue;
1591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001593 int otherUTime = (st.rel_utime*perc)/100;
1594 int otherSTime = (st.rel_stime*perc)/100;
1595 totalUTime += otherUTime;
1596 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 if (pr != null) {
1598 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001599 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1600 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001601 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001602 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001603 } else {
1604 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001605 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001606 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001607 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1608 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001609 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001613 bstats.finishAddingCpuLocked(perc, totalUTime,
1614 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 }
1616 }
1617 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1620 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001621 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 }
1623 }
1624 }
1625 }
1626
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001627 @Override
1628 public void batteryNeedsCpuUpdate() {
1629 updateCpuStatsNow();
1630 }
1631
1632 @Override
1633 public void batteryPowerChanged(boolean onBattery) {
1634 // When plugging in, update the CPU stats first before changing
1635 // the plug state.
1636 updateCpuStatsNow();
1637 synchronized (this) {
1638 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001639 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001640 }
1641 }
1642 }
1643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 /**
1645 * Initialize the application bind args. These are passed to each
1646 * process when the bindApplication() IPC is sent to the process. They're
1647 * lazily setup to make sure the services are running when they're asked for.
1648 */
1649 private HashMap<String, IBinder> getCommonServicesLocked() {
1650 if (mAppBindArgs == null) {
1651 mAppBindArgs = new HashMap<String, IBinder>();
1652
1653 // Setup the application init args
1654 mAppBindArgs.put("package", ServiceManager.getService("package"));
1655 mAppBindArgs.put("window", ServiceManager.getService("window"));
1656 mAppBindArgs.put(Context.ALARM_SERVICE,
1657 ServiceManager.getService(Context.ALARM_SERVICE));
1658 }
1659 return mAppBindArgs;
1660 }
1661
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001662 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 if (mFocusedActivity != r) {
1664 mFocusedActivity = r;
1665 mWindowManager.setFocusedApp(r, true);
1666 }
1667 }
1668
Dianne Hackborn906497c2010-05-10 15:57:38 -07001669 private final void updateLruProcessInternalLocked(ProcessRecord app,
1670 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001672 int lrui = mLruProcesses.indexOf(app);
1673 if (lrui >= 0) mLruProcesses.remove(lrui);
1674
1675 int i = mLruProcesses.size()-1;
1676 int skipTop = 0;
1677
Dianne Hackborn906497c2010-05-10 15:57:38 -07001678 app.lruSeq = mLruSeq;
1679
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001680 // compute the new weight for this process.
1681 if (updateActivityTime) {
1682 app.lastActivityTime = SystemClock.uptimeMillis();
1683 }
1684 if (app.activities.size() > 0) {
1685 // If this process has activities, we more strongly want to keep
1686 // it around.
1687 app.lruWeight = app.lastActivityTime;
1688 } else if (app.pubProviders.size() > 0) {
1689 // If this process contains content providers, we want to keep
1690 // it a little more strongly.
1691 app.lruWeight = app.lastActivityTime - CONTENT_APP_IDLE_OFFSET;
1692 // Also don't let it kick out the first few "real" hidden processes.
1693 skipTop = MIN_HIDDEN_APPS;
1694 } else {
1695 // If this process doesn't have activities, we less strongly
1696 // want to keep it around, and generally want to avoid getting
1697 // in front of any very recently used activities.
1698 app.lruWeight = app.lastActivityTime - EMPTY_APP_IDLE_OFFSET;
1699 // Also don't let it kick out the first few "real" hidden processes.
1700 skipTop = MIN_HIDDEN_APPS;
1701 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001702
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001703 while (i >= 0) {
1704 ProcessRecord p = mLruProcesses.get(i);
1705 // If this app shouldn't be in front of the first N background
1706 // apps, then skip over that many that are currently hidden.
1707 if (skipTop > 0 && p.setAdj >= HIDDEN_APP_MIN_ADJ) {
1708 skipTop--;
1709 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001710 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001711 mLruProcesses.add(i+1, app);
1712 break;
1713 }
1714 i--;
1715 }
1716 if (i < 0) {
1717 mLruProcesses.add(0, app);
1718 }
1719
Dianne Hackborn906497c2010-05-10 15:57:38 -07001720 // If the app is currently using a content provider or service,
1721 // bump those processes as well.
1722 if (app.connections.size() > 0) {
1723 for (ConnectionRecord cr : app.connections) {
1724 if (cr.binding != null && cr.binding.service != null
1725 && cr.binding.service.app != null
1726 && cr.binding.service.app.lruSeq != mLruSeq) {
1727 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1728 updateActivityTime, i+1);
1729 }
1730 }
1731 }
1732 if (app.conProviders.size() > 0) {
1733 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
1734 if (cpr.app != null && cpr.app.lruSeq != mLruSeq) {
1735 updateLruProcessInternalLocked(cpr.app, oomAdj,
1736 updateActivityTime, i+1);
1737 }
1738 }
1739 }
1740
Joe Onorato8a9b2202010-02-26 18:56:32 -08001741 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 if (oomAdj) {
1743 updateOomAdjLocked();
1744 }
1745 }
1746
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001747 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001748 boolean oomAdj, boolean updateActivityTime) {
1749 mLruSeq++;
1750 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1751 }
1752
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001753 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 String processName, int uid) {
1755 if (uid == Process.SYSTEM_UID) {
1756 // The system gets to run in any process. If there are multiple
1757 // processes with the same uid, just pick the first (this
1758 // should never happen).
1759 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1760 processName);
1761 return procs != null ? procs.valueAt(0) : null;
1762 }
1763 ProcessRecord proc = mProcessNames.get(processName, uid);
1764 return proc;
1765 }
1766
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001767 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001768 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001769 try {
1770 if (pm.performDexOpt(packageName)) {
1771 mDidDexOpt = true;
1772 }
1773 } catch (RemoteException e) {
1774 }
1775 }
1776
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001777 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 int transit = mWindowManager.getPendingAppTransition();
1779 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1780 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1781 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1782 }
1783
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001784 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001786 String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 ProcessRecord app = getProcessRecordLocked(processName, info.uid);
1788 // We don't have to do anything more if:
1789 // (1) There is an existing application record; and
1790 // (2) The caller doesn't think it is dead, OR there is no thread
1791 // object attached to it so we know it couldn't have crashed; and
1792 // (3) There is a pid assigned to it, so it is either starting or
1793 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001794 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 + " app=" + app + " knownToBeDead=" + knownToBeDead
1796 + " thread=" + (app != null ? app.thread : null)
1797 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001798 if (app != null && app.pid > 0) {
1799 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001800 // We already have the app running, or are waiting for it to
1801 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001802 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001803 return app;
1804 } else {
1805 // An application record is attached to a previous process,
1806 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001807 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001808 handleAppDiedLocked(app, true);
1809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 String hostingNameStr = hostingName != null
1813 ? hostingName.flattenToShortString() : null;
1814
1815 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1816 // If we are in the background, then check to see if this process
1817 // is bad. If so, we will just silently fail.
1818 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001819 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1820 + "/" + info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 return null;
1822 }
1823 } else {
1824 // When the user is explicitly starting a process, then clear its
1825 // crash count so that we won't make it bad until they see at
1826 // least one crash dialog again, and make the process good again
1827 // if it had been bad.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001828 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
1829 + "/" + info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 mProcessCrashTimes.remove(info.processName, info.uid);
1831 if (mBadProcesses.get(info.processName, info.uid) != null) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08001832 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 info.processName);
1834 mBadProcesses.remove(info.processName, info.uid);
1835 if (app != null) {
1836 app.bad = false;
1837 }
1838 }
1839 }
1840
1841 if (app == null) {
1842 app = newProcessRecordLocked(null, info, processName);
1843 mProcessNames.put(processName, info.uid, app);
1844 } else {
1845 // If this is a new package in the process, add the package to the list
1846 app.addPackage(info.packageName);
1847 }
1848
1849 // If the system is not ready yet, then hold off on starting this
1850 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001851 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001852 && !isAllowedWhileBooting(info)
1853 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 if (!mProcessesOnHold.contains(app)) {
1855 mProcessesOnHold.add(app);
1856 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001857 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 return app;
1859 }
1860
1861 startProcessLocked(app, hostingType, hostingNameStr);
1862 return (app.pid != 0) ? app : null;
1863 }
1864
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001865 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1866 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1867 }
1868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 private final void startProcessLocked(ProcessRecord app,
1870 String hostingType, String hostingNameStr) {
1871 if (app.pid > 0 && app.pid != MY_PID) {
1872 synchronized (mPidsSelfLocked) {
1873 mPidsSelfLocked.remove(app.pid);
1874 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1875 }
1876 app.pid = 0;
1877 }
1878
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001879 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1880 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 mProcessesOnHold.remove(app);
1882
1883 updateCpuStats();
1884
1885 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1886 mProcDeaths[0] = 0;
1887
1888 try {
1889 int uid = app.info.uid;
1890 int[] gids = null;
1891 try {
1892 gids = mContext.getPackageManager().getPackageGids(
1893 app.info.packageName);
1894 } catch (PackageManager.NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001895 Slog.w(TAG, "Unable to retrieve gids", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 }
1897 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1898 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1899 && mTopComponent != null
1900 && app.processName.equals(mTopComponent.getPackageName())) {
1901 uid = 0;
1902 }
1903 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1904 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1905 uid = 0;
1906 }
1907 }
1908 int debugFlags = 0;
1909 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1910 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
1911 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001912 // Run the app in safe mode if its manifest requests so or the
1913 // system is booted in safe mode.
1914 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1915 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001916 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1919 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1920 }
1921 if ("1".equals(SystemProperties.get("debug.assert"))) {
1922 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1923 }
1924 int pid = Process.start("android.app.ActivityThread",
1925 mSimpleProcessManagement ? app.processName : null, uid, uid,
1926 gids, debugFlags, null);
1927 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1928 synchronized (bs) {
1929 if (bs.isOnBattery()) {
1930 app.batteryStats.incStartsLocked();
1931 }
1932 }
1933
Doug Zongker2bec3d42009-12-04 12:52:44 -08001934 EventLog.writeEvent(EventLogTags.AM_PROC_START, pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 app.processName, hostingType,
1936 hostingNameStr != null ? hostingNameStr : "");
1937
1938 if (app.persistent) {
Christopher Tatec27181c2010-06-30 14:41:09 -07001939 Watchdog.getInstance().processStarted(app.processName, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 }
1941
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07001942 StringBuilder buf = mStringBuilder;
1943 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 buf.append("Start proc ");
1945 buf.append(app.processName);
1946 buf.append(" for ");
1947 buf.append(hostingType);
1948 if (hostingNameStr != null) {
1949 buf.append(" ");
1950 buf.append(hostingNameStr);
1951 }
1952 buf.append(": pid=");
1953 buf.append(pid);
1954 buf.append(" uid=");
1955 buf.append(uid);
1956 buf.append(" gids={");
1957 if (gids != null) {
1958 for (int gi=0; gi<gids.length; gi++) {
1959 if (gi != 0) buf.append(", ");
1960 buf.append(gids[gi]);
1961
1962 }
1963 }
1964 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001965 Slog.i(TAG, buf.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 if (pid == 0 || pid == MY_PID) {
1967 // Processes are being emulated with threads.
1968 app.pid = MY_PID;
1969 app.removed = false;
1970 mStartingProcesses.add(app);
1971 } else if (pid > 0) {
1972 app.pid = pid;
1973 app.removed = false;
1974 synchronized (mPidsSelfLocked) {
1975 this.mPidsSelfLocked.put(pid, app);
1976 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1977 msg.obj = app;
1978 mHandler.sendMessageDelayed(msg, PROC_START_TIMEOUT);
1979 }
1980 } else {
1981 app.pid = 0;
1982 RuntimeException e = new RuntimeException(
1983 "Failure starting process " + app.processName
1984 + ": returned pid=" + pid);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001985 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 }
1987 } catch (RuntimeException e) {
1988 // XXX do better error recovery.
1989 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001990 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 }
1992 }
1993
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001994 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 if (resumed) {
1996 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
1997 } else {
1998 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
1999 }
2000 }
2001
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002002 boolean startHomeActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002003 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2004 && mTopAction == null) {
2005 // We are running in factory test mode, but unable to find
2006 // the factory test app, so just sit around displaying the
2007 // error message and don't try to start anything.
2008 return false;
2009 }
2010 Intent intent = new Intent(
2011 mTopAction,
2012 mTopData != null ? Uri.parse(mTopData) : null);
2013 intent.setComponent(mTopComponent);
2014 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2015 intent.addCategory(Intent.CATEGORY_HOME);
2016 }
2017 ActivityInfo aInfo =
2018 intent.resolveActivityInfo(mContext.getPackageManager(),
2019 STOCK_PM_FLAGS);
2020 if (aInfo != null) {
2021 intent.setComponent(new ComponentName(
2022 aInfo.applicationInfo.packageName, aInfo.name));
2023 // Don't do this if the home app is currently being
2024 // instrumented.
2025 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2026 aInfo.applicationInfo.uid);
2027 if (app == null || app.instrumentationClass == null) {
2028 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002029 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002030 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002031 }
2032 }
2033
2034
2035 return true;
2036 }
2037
2038 /**
2039 * Starts the "new version setup screen" if appropriate.
2040 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002041 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002042 // Only do this once per boot.
2043 if (mCheckedForSetup) {
2044 return;
2045 }
2046
2047 // We will show this screen if the current one is a different
2048 // version than the last one shown, and we are not running in
2049 // low-level factory test mode.
2050 final ContentResolver resolver = mContext.getContentResolver();
2051 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2052 Settings.Secure.getInt(resolver,
2053 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2054 mCheckedForSetup = true;
2055
2056 // See if we should be showing the platform update setup UI.
2057 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2058 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2059 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2060
2061 // We don't allow third party apps to replace this.
2062 ResolveInfo ri = null;
2063 for (int i=0; ris != null && i<ris.size(); i++) {
2064 if ((ris.get(i).activityInfo.applicationInfo.flags
2065 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2066 ri = ris.get(i);
2067 break;
2068 }
2069 }
2070
2071 if (ri != null) {
2072 String vers = ri.activityInfo.metaData != null
2073 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2074 : null;
2075 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2076 vers = ri.activityInfo.applicationInfo.metaData.getString(
2077 Intent.METADATA_SETUP_VERSION);
2078 }
2079 String lastVers = Settings.Secure.getString(
2080 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2081 if (vers != null && !vers.equals(lastVers)) {
2082 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2083 intent.setComponent(new ComponentName(
2084 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002085 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002086 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002087 }
2088 }
2089 }
2090 }
2091
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002092 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002093 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002094
2095 final int identHash = System.identityHashCode(r);
2096 updateUsageStats(r, true);
2097
2098 int i = mWatchers.beginBroadcast();
2099 while (i > 0) {
2100 i--;
2101 IActivityWatcher w = mWatchers.getBroadcastItem(i);
2102 if (w != null) {
2103 try {
2104 w.activityResuming(identHash);
2105 } catch (RemoteException e) {
2106 }
2107 }
2108 }
2109 mWatchers.finishBroadcast();
2110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002112 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002113 final int N = mPendingActivityLaunches.size();
2114 if (N <= 0) {
2115 return;
2116 }
2117 for (int i=0; i<N; i++) {
2118 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002119 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002120 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
2121 doResume && i == (N-1));
2122 }
2123 mPendingActivityLaunches.clear();
2124 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002125
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002126 public final int startActivity(IApplicationThread caller,
2127 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2128 int grantedMode, IBinder resultTo,
2129 String resultWho, int requestCode, boolean onlyIfNeeded,
2130 boolean debug) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002131 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002132 grantedUriPermissions, grantedMode, resultTo, resultWho,
2133 requestCode, onlyIfNeeded, debug, null, null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002134 }
2135
2136 public final WaitResult startActivityAndWait(IApplicationThread caller,
2137 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2138 int grantedMode, IBinder resultTo,
2139 String resultWho, int requestCode, boolean onlyIfNeeded,
2140 boolean debug) {
2141 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002142 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002143 grantedUriPermissions, grantedMode, resultTo, resultWho,
2144 requestCode, onlyIfNeeded, debug, res, null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002145 return res;
2146 }
2147
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002148 public final int startActivityWithConfig(IApplicationThread caller,
2149 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2150 int grantedMode, IBinder resultTo,
2151 String resultWho, int requestCode, boolean onlyIfNeeded,
2152 boolean debug, Configuration config) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002153 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002154 grantedUriPermissions, grantedMode, resultTo, resultWho,
2155 requestCode, onlyIfNeeded, debug, null, config);
2156 }
2157
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002158 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002159 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002160 IBinder resultTo, String resultWho, int requestCode,
2161 int flagsMask, int flagsValues) {
2162 // Refuse possible leaked file descriptors
2163 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2164 throw new IllegalArgumentException("File descriptors passed in Intent");
2165 }
2166
2167 IIntentSender sender = intent.getTarget();
2168 if (!(sender instanceof PendingIntentRecord)) {
2169 throw new IllegalArgumentException("Bad PendingIntent object");
2170 }
2171
2172 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002173
2174 synchronized (this) {
2175 // If this is coming from the currently resumed activity, it is
2176 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002177 if (mMainStack.mResumedActivity != null
2178 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002179 Binder.getCallingUid()) {
2180 mAppSwitchesAllowedTime = 0;
2181 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002182 }
2183
2184 return pir.sendInner(0, fillInIntent, resolvedType,
2185 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
2186 }
2187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002188 public boolean startNextMatchingActivity(IBinder callingActivity,
2189 Intent intent) {
2190 // Refuse possible leaked file descriptors
2191 if (intent != null && intent.hasFileDescriptors() == true) {
2192 throw new IllegalArgumentException("File descriptors passed in Intent");
2193 }
2194
2195 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002196 int index = mMainStack.indexOfTokenLocked(callingActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 if (index < 0) {
2198 return false;
2199 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002200 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 if (r.app == null || r.app.thread == null) {
2202 // The caller is not running... d'oh!
2203 return false;
2204 }
2205 intent = new Intent(intent);
2206 // The caller is not allowed to change the data.
2207 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2208 // And we are resetting to find the next component...
2209 intent.setComponent(null);
2210
2211 ActivityInfo aInfo = null;
2212 try {
2213 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002214 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002216 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217
2218 // Look for the original activity in the list...
2219 final int N = resolves != null ? resolves.size() : 0;
2220 for (int i=0; i<N; i++) {
2221 ResolveInfo rInfo = resolves.get(i);
2222 if (rInfo.activityInfo.packageName.equals(r.packageName)
2223 && rInfo.activityInfo.name.equals(r.info.name)) {
2224 // We found the current one... the next matching is
2225 // after it.
2226 i++;
2227 if (i<N) {
2228 aInfo = resolves.get(i).activityInfo;
2229 }
2230 break;
2231 }
2232 }
2233 } catch (RemoteException e) {
2234 }
2235
2236 if (aInfo == null) {
2237 // Nobody who is next!
2238 return false;
2239 }
2240
2241 intent.setComponent(new ComponentName(
2242 aInfo.applicationInfo.packageName, aInfo.name));
2243 intent.setFlags(intent.getFlags()&~(
2244 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2245 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2246 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2247 Intent.FLAG_ACTIVITY_NEW_TASK));
2248
2249 // Okay now we need to start the new activity, replacing the
2250 // currently running activity. This is a little tricky because
2251 // we want to start the new one as if the current one is finished,
2252 // but not finish the current one first so that there is no flicker.
2253 // And thus...
2254 final boolean wasFinishing = r.finishing;
2255 r.finishing = true;
2256
2257 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002258 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 final String resultWho = r.resultWho;
2260 final int requestCode = r.requestCode;
2261 r.resultTo = null;
2262 if (resultTo != null) {
2263 resultTo.removeResultsLocked(r, resultWho, requestCode);
2264 }
2265
2266 final long origId = Binder.clearCallingIdentity();
2267 // XXX we are not dealing with propagating grantedUriPermissions...
2268 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002269 int res = mMainStack.startActivityLocked(r.app.thread, intent,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 r.resolvedType, null, 0, aInfo, resultTo, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002271 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 Binder.restoreCallingIdentity(origId);
2273
2274 r.finishing = wasFinishing;
2275 if (res != START_SUCCESS) {
2276 return false;
2277 }
2278 return true;
2279 }
2280 }
2281
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002282 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 Intent intent, String resolvedType, IBinder resultTo,
2284 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002285
2286 // This is so super not safe, that only the system (or okay root)
2287 // can do it.
2288 final int callingUid = Binder.getCallingUid();
2289 if (callingUid != 0 && callingUid != Process.myUid()) {
2290 throw new SecurityException(
2291 "startActivityInPackage only available to the system");
2292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002294 return mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
2295 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false, null, null);
2296 }
2297
2298 public final int startActivities(IApplicationThread caller,
2299 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2300 return mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo);
2301 }
2302
2303 public final int startActivitiesInPackage(int uid,
2304 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2305
2306 // This is so super not safe, that only the system (or okay root)
2307 // can do it.
2308 final int callingUid = Binder.getCallingUid();
2309 if (callingUid != 0 && callingUid != Process.myUid()) {
2310 throw new SecurityException(
2311 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 }
2313
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002314 return mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 }
2316
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002317 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002319 // Quick case: check if the top-most recent task is the same.
2320 if (N > 0 && mRecentTasks.get(0) == task) {
2321 return;
2322 }
2323 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 for (int i=0; i<N; i++) {
2325 TaskRecord tr = mRecentTasks.get(i);
2326 if ((task.affinity != null && task.affinity.equals(tr.affinity))
2327 || (task.intent != null && task.intent.filterEquals(tr.intent))) {
2328 mRecentTasks.remove(i);
2329 i--;
2330 N--;
2331 if (task.intent == null) {
2332 // If the new recent task we are adding is not fully
2333 // specified, then replace it with the existing recent task.
2334 task = tr;
2335 }
2336 }
2337 }
2338 if (N >= MAX_RECENT_TASKS) {
2339 mRecentTasks.remove(N-1);
2340 }
2341 mRecentTasks.add(0, task);
2342 }
2343
2344 public void setRequestedOrientation(IBinder token,
2345 int requestedOrientation) {
2346 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002347 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 if (index < 0) {
2349 return;
2350 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002351 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 final long origId = Binder.clearCallingIdentity();
2353 mWindowManager.setAppOrientation(r, requestedOrientation);
2354 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002355 mConfiguration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 r.mayFreezeScreenLocked(r.app) ? r : null);
2357 if (config != null) {
2358 r.frozenBeforeDestroy = true;
2359 if (!updateConfigurationLocked(config, r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002360 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 }
2362 }
2363 Binder.restoreCallingIdentity(origId);
2364 }
2365 }
2366
2367 public int getRequestedOrientation(IBinder token) {
2368 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002369 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 if (index < 0) {
2371 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2372 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002373 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 return mWindowManager.getAppOrientation(r);
2375 }
2376 }
2377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 /**
2379 * This is the internal entry point for handling Activity.finish().
2380 *
2381 * @param token The Binder token referencing the Activity we want to finish.
2382 * @param resultCode Result code, if any, from this Activity.
2383 * @param resultData Result data (Intent), if any, from this Activity.
2384 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002385 * @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 -08002386 */
2387 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2388 // Refuse possible leaked file descriptors
2389 if (resultData != null && resultData.hasFileDescriptors() == true) {
2390 throw new IllegalArgumentException("File descriptors passed in Intent");
2391 }
2392
2393 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002394 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002396 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 if (next != null) {
2398 // ask watcher if this is allowed
2399 boolean resumeOK = true;
2400 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002401 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002403 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 }
2405
2406 if (!resumeOK) {
2407 return false;
2408 }
2409 }
2410 }
2411 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002412 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 resultData, "app-request");
2414 Binder.restoreCallingIdentity(origId);
2415 return res;
2416 }
2417 }
2418
Dianne Hackborn860755f2010-06-03 18:47:52 -07002419 public final void finishHeavyWeightApp() {
2420 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2421 != PackageManager.PERMISSION_GRANTED) {
2422 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2423 + Binder.getCallingPid()
2424 + ", uid=" + Binder.getCallingUid()
2425 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2426 Slog.w(TAG, msg);
2427 throw new SecurityException(msg);
2428 }
2429
2430 synchronized(this) {
2431 if (mHeavyWeightProcess == null) {
2432 return;
2433 }
2434
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002435 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002436 mHeavyWeightProcess.activities);
2437 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002438 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002439 if (!r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002440 int index = mMainStack.indexOfTokenLocked(r);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002441 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002442 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002443 null, "finish-heavy");
2444 }
2445 }
2446 }
2447
2448 mHeavyWeightProcess = null;
2449 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2450 }
2451 }
2452
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002453 public void crashApplication(int uid, int initialPid, String packageName,
2454 String message) {
2455 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2456 != PackageManager.PERMISSION_GRANTED) {
2457 String msg = "Permission Denial: crashApplication() from pid="
2458 + Binder.getCallingPid()
2459 + ", uid=" + Binder.getCallingUid()
2460 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2461 Slog.w(TAG, msg);
2462 throw new SecurityException(msg);
2463 }
2464
2465 synchronized(this) {
2466 ProcessRecord proc = null;
2467
2468 // Figure out which process to kill. We don't trust that initialPid
2469 // still has any relation to current pids, so must scan through the
2470 // list.
2471 synchronized (mPidsSelfLocked) {
2472 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2473 ProcessRecord p = mPidsSelfLocked.valueAt(i);
2474 if (p.info.uid != uid) {
2475 continue;
2476 }
2477 if (p.pid == initialPid) {
2478 proc = p;
2479 break;
2480 }
2481 for (String str : p.pkgList) {
2482 if (str.equals(packageName)) {
2483 proc = p;
2484 }
2485 }
2486 }
2487 }
2488
2489 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002490 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002491 + " initialPid=" + initialPid
2492 + " packageName=" + packageName);
2493 return;
2494 }
2495
2496 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002497 if (proc.pid == Process.myPid()) {
2498 Log.w(TAG, "crashApplication: trying to crash self!");
2499 return;
2500 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002501 long ident = Binder.clearCallingIdentity();
2502 try {
2503 proc.thread.scheduleCrash(message);
2504 } catch (RemoteException e) {
2505 }
2506 Binder.restoreCallingIdentity(ident);
2507 }
2508 }
2509 }
2510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 public final void finishSubActivity(IBinder token, String resultWho,
2512 int requestCode) {
2513 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002514 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 if (index < 0) {
2516 return;
2517 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002518 ActivityRecord self = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519
2520 final long origId = Binder.clearCallingIdentity();
2521
2522 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002523 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2524 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 if (r.resultTo == self && r.requestCode == requestCode) {
2526 if ((r.resultWho == null && resultWho == null) ||
2527 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002528 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 Activity.RESULT_CANCELED, null, "request-sub");
2530 }
2531 }
2532 }
2533
2534 Binder.restoreCallingIdentity(origId);
2535 }
2536 }
2537
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002538 public boolean willActivityBeVisible(IBinder token) {
2539 synchronized(this) {
2540 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002541 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2542 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002543 if (r == token) {
2544 return true;
2545 }
2546 if (r.fullscreen && !r.finishing) {
2547 return false;
2548 }
2549 }
2550 return true;
2551 }
2552 }
2553
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002554 public void overridePendingTransition(IBinder token, String packageName,
2555 int enterAnim, int exitAnim) {
2556 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002557 int index = mMainStack.indexOfTokenLocked(token);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002558 if (index < 0) {
2559 return;
2560 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002561 ActivityRecord self = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002562
2563 final long origId = Binder.clearCallingIdentity();
2564
2565 if (self.state == ActivityState.RESUMED
2566 || self.state == ActivityState.PAUSING) {
2567 mWindowManager.overridePendingAppTransition(packageName,
2568 enterAnim, exitAnim);
2569 }
2570
2571 Binder.restoreCallingIdentity(origId);
2572 }
2573 }
2574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 * Main function for removing an existing process from the activity manager
2577 * as a result of that process going away. Clears out all connections
2578 * to the process.
2579 */
2580 private final void handleAppDiedLocked(ProcessRecord app,
2581 boolean restarting) {
2582 cleanUpApplicationRecordLocked(app, restarting, -1);
2583 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002584 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 }
2586
2587 // Just in case...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002588 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2589 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2590 mMainStack.mPausingActivity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002592 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2593 mMainStack.mLastPausedActivity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 }
2595
2596 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002597 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598
2599 boolean atTop = true;
2600 boolean hasVisibleActivities = false;
2601
2602 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002603 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002604 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 TAG, "Removing app " + app + " from history with " + i + " entries");
2606 while (i > 0) {
2607 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002608 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002609 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2611 if (r.app == app) {
2612 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002613 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 TAG, "Removing this entry! frozen=" + r.haveState
2615 + " finishing=" + r.finishing);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08002616 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002617 mMainStack.mHistory.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618
2619 r.inHistory = false;
2620 mWindowManager.removeAppToken(r);
2621 if (VALIDATE_TOKENS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002622 mWindowManager.validateAppTokens(mMainStack.mHistory);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002624 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625
2626 } else {
2627 // We have the current state for this activity, so
2628 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002629 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 TAG, "Keeping entry, setting app to null");
2631 if (r.visible) {
2632 hasVisibleActivities = true;
2633 }
2634 r.app = null;
2635 r.nowVisible = false;
2636 if (!r.haveState) {
2637 r.icicle = null;
2638 }
2639 }
2640
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002641 r.stack.cleanUpActivityLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 r.state = ActivityState.STOPPED;
2643 }
2644 atTop = false;
2645 }
2646
2647 app.activities.clear();
2648
2649 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002650 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 + " running instrumentation " + app.instrumentationClass);
2652 Bundle info = new Bundle();
2653 info.putString("shortMsg", "Process crashed.");
2654 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2655 }
2656
2657 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002658 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 // If there was nothing to resume, and we are not already
2660 // restarting this process, but there is a visible activity that
2661 // is hosted by the process... then make sure all visible
2662 // activities are running, taking care of restarting this
2663 // process.
2664 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002665 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 }
2667 }
2668 }
2669 }
2670
2671 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2672 IBinder threadBinder = thread.asBinder();
2673
2674 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002675 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2676 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2678 return i;
2679 }
2680 }
2681 return -1;
2682 }
2683
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002684 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 IApplicationThread thread) {
2686 if (thread == null) {
2687 return null;
2688 }
2689
2690 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002691 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 }
2693
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002694 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 IApplicationThread thread) {
2696
2697 mProcDeaths[0]++;
2698
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002699 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2700 synchronized (stats) {
2701 stats.noteProcessDiedLocked(app.info.uid, pid);
2702 }
2703
Magnus Edlund7bb25812010-02-24 15:45:06 +01002704 // Clean up already done if the process has been re-started.
2705 if (app.pid == pid && app.thread != null &&
2706 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002707 if (!app.killedBackground) {
2708 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2709 + ") has died.");
2710 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002711 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002712 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 TAG, "Dying app: " + app + ", pid: " + pid
2714 + ", thread: " + thread.asBinder());
2715 boolean doLowMem = app.instrumentationClass == null;
2716 handleAppDiedLocked(app, false);
2717
2718 if (doLowMem) {
2719 // If there are no longer any background processes running,
2720 // and the app that died was not running instrumentation,
2721 // then tell everyone we are now low on memory.
2722 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002723 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2724 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 if (rec.thread != null && rec.setAdj >= HIDDEN_APP_MIN_ADJ) {
2726 haveBg = true;
2727 break;
2728 }
2729 }
2730
2731 if (!haveBg) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002732 Slog.i(TAG, "Low Memory: No more background processes.");
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002733 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002734 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002735 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2736 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002737 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002738 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2739 // The low memory report is overriding any current
2740 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002741 // heavy/important/visible/foreground processes first.
2742 if (rec.setAdj <= HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002743 rec.lastRequestedGc = 0;
2744 } else {
2745 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002747 rec.reportLowMemory = true;
2748 rec.lastLowMemory = now;
2749 mProcessesToGc.remove(rec);
2750 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 }
2752 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002753 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 }
2755 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002756 } else if (app.pid != pid) {
2757 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002758 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002759 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002760 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002761 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002762 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 + thread.asBinder());
2764 }
2765 }
2766
Dan Egnor42471dd2010-01-07 17:25:22 -08002767 /**
2768 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002769 * @param clearTraces causes the dump file to be erased prior to the new
2770 * traces being written, if true; when false, the new traces will be
2771 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002772 * @param firstPids of dalvik VM processes to dump stack traces for first
2773 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002774 * @return file containing stack traces, or null if no dump file is configured
2775 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002776 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2777 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002778 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2779 if (tracesPath == null || tracesPath.length() == 0) {
2780 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002782
2783 File tracesFile = new File(tracesPath);
2784 try {
2785 File tracesDir = tracesFile.getParentFile();
2786 if (!tracesDir.exists()) tracesFile.mkdirs();
2787 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2788
Christopher Tate6ee412d2010-05-28 12:01:56 -07002789 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002790 tracesFile.createNewFile();
2791 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2792 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002793 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002794 return null;
2795 }
2796
2797 // Use a FileObserver to detect when traces finish writing.
2798 // The order of traces is considered important to maintain for legibility.
2799 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2800 public synchronized void onEvent(int event, String path) { notify(); }
2801 };
2802
2803 try {
2804 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002805
2806 // First collect all of the stacks of the most important pids.
2807 try {
2808 int num = firstPids.size();
2809 for (int i = 0; i < num; i++) {
2810 synchronized (observer) {
2811 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2812 observer.wait(200); // Wait for write-close, give up after 200msec
2813 }
2814 }
2815 } catch (InterruptedException e) {
2816 Log.wtf(TAG, e);
2817 }
2818
2819 // Next measure CPU usage.
2820 if (processStats != null) {
2821 processStats.init();
2822 System.gc();
2823 processStats.update();
2824 try {
2825 synchronized (processStats) {
2826 processStats.wait(500); // measure over 1/2 second.
2827 }
2828 } catch (InterruptedException e) {
2829 }
2830 processStats.update();
2831
2832 // We'll take the stack crawls of just the top apps using CPU.
2833 final int N = processStats.countWorkingStats();
2834 int numProcs = 0;
2835 for (int i=0; i<N && numProcs<5; i++) {
2836 ProcessStats.Stats stats = processStats.getWorkingStats(i);
2837 if (lastPids.indexOfKey(stats.pid) >= 0) {
2838 numProcs++;
2839 try {
2840 synchronized (observer) {
2841 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
2842 observer.wait(200); // Wait for write-close, give up after 200msec
2843 }
2844 } catch (InterruptedException e) {
2845 Log.wtf(TAG, e);
2846 }
2847
2848 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002849 }
2850 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002851
2852 return tracesFile;
2853
Dan Egnor42471dd2010-01-07 17:25:22 -08002854 } finally {
2855 observer.stopWatching();
2856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 }
2858
Jeff Brown4d94a762010-09-23 11:33:28 -07002859 private final class AppNotResponding implements Runnable {
2860 private final ProcessRecord mApp;
2861 private final String mAnnotation;
2862
2863 public AppNotResponding(ProcessRecord app, String annotation) {
2864 mApp = app;
2865 mAnnotation = annotation;
2866 }
2867
2868 @Override
2869 public void run() {
2870 appNotResponding(mApp, null, null, mAnnotation);
2871 }
2872 }
2873
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002874 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
2875 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002876 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
2877 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
2878
Dianne Hackborn287952c2010-09-22 22:34:31 -07002879 if (mController != null) {
2880 try {
2881 // 0 == continue, -1 = kill process immediately
2882 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
2883 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
2884 } catch (RemoteException e) {
2885 mController = null;
2886 }
2887 }
2888
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002889 long anrTime = SystemClock.uptimeMillis();
2890 if (MONITOR_CPU_USAGE) {
2891 updateCpuStatsNow();
2892 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002893
2894 synchronized (this) {
2895 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
2896 if (mShuttingDown) {
2897 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
2898 return;
2899 } else if (app.notResponding) {
2900 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
2901 return;
2902 } else if (app.crashing) {
2903 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
2904 return;
2905 }
2906
2907 // In case we come through here for the same app before completing
2908 // this one, mark as anring now so we will bail out.
2909 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08002910
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002911 // Log the ANR to the event log.
2912 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
2913 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08002914
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002915 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002916 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002917
2918 int parentPid = app.pid;
2919 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002920 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002921
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002922 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08002923
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002924 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
2925 ProcessRecord r = mLruProcesses.get(i);
2926 if (r != null && r.thread != null) {
2927 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002928 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
2929 if (r.persistent) {
2930 firstPids.add(pid);
2931 } else {
2932 lastPids.put(pid, Boolean.TRUE);
2933 }
2934 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 }
2937 }
2938
Dan Egnor42471dd2010-01-07 17:25:22 -08002939 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002940 StringBuilder info = mStringBuilder;
2941 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08002942 info.append("ANR in ").append(app.processName);
2943 if (activity != null && activity.shortComponentName != null) {
2944 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07002945 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08002946 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08002948 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002950 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08002951 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953
Dianne Hackborn287952c2010-09-22 22:34:31 -07002954 final ProcessStats processStats = new ProcessStats(true);
2955
2956 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
2957
Dan Egnor42471dd2010-01-07 17:25:22 -08002958 String cpuInfo = null;
2959 if (MONITOR_CPU_USAGE) {
2960 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002961 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002962 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002963 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002964 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08002965 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 }
2967
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002968 info.append(processStats.printCurrentState(anrTime));
2969
Joe Onorato8a9b2202010-02-26 18:56:32 -08002970 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08002971 if (tracesFile == null) {
2972 // There is no trace file, so dump (only) the alleged culprit's threads to the log
2973 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
2974 }
2975
2976 addErrorToDropBox("anr", app, activity, parent, annotation, cpuInfo, tracesFile, null);
2977
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002978 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08002980 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
2981 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002983 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
2984 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 }
2986 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002987 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 }
2989 }
2990
Dan Egnor42471dd2010-01-07 17:25:22 -08002991 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
2992 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
2993 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002994
2995 synchronized (this) {
2996 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
2997 Process.killProcess(app.pid);
2998 return;
2999 }
3000
3001 // Set the app's notResponding state, and look up the errorReportReceiver
3002 makeAppNotRespondingLocked(app,
3003 activity != null ? activity.shortComponentName : null,
3004 annotation != null ? "ANR " + annotation : "ANR",
3005 info.toString());
3006
3007 // Bring up the infamous App Not Responding dialog
3008 Message msg = Message.obtain();
3009 HashMap map = new HashMap();
3010 msg.what = SHOW_NOT_RESPONDING_MSG;
3011 msg.obj = map;
3012 map.put("app", app);
3013 if (activity != null) {
3014 map.put("activity", activity);
3015 }
3016
3017 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 }
3020
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003021 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3022 if (!mLaunchWarningShown) {
3023 mLaunchWarningShown = true;
3024 mHandler.post(new Runnable() {
3025 @Override
3026 public void run() {
3027 synchronized (ActivityManagerService.this) {
3028 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3029 d.show();
3030 mHandler.postDelayed(new Runnable() {
3031 @Override
3032 public void run() {
3033 synchronized (ActivityManagerService.this) {
3034 d.dismiss();
3035 mLaunchWarningShown = false;
3036 }
3037 }
3038 }, 4000);
3039 }
3040 }
3041 });
3042 }
3043 }
3044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 public boolean clearApplicationUserData(final String packageName,
3046 final IPackageDataObserver observer) {
3047 int uid = Binder.getCallingUid();
3048 int pid = Binder.getCallingPid();
3049 long callingId = Binder.clearCallingIdentity();
3050 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003051 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 int pkgUid = -1;
3053 synchronized(this) {
3054 try {
3055 pkgUid = pm.getPackageUid(packageName);
3056 } catch (RemoteException e) {
3057 }
3058 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003059 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 return false;
3061 }
3062 if (uid == pkgUid || checkComponentPermission(
3063 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003064 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003066 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 } else {
3068 throw new SecurityException(pid+" does not have permission:"+
3069 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3070 "for process:"+packageName);
3071 }
3072 }
3073
3074 try {
3075 //clear application user data
3076 pm.clearApplicationUserData(packageName, observer);
3077 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3078 Uri.fromParts("package", packageName, null));
3079 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003080 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
3081 null, null, 0, null, null, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 } catch (RemoteException e) {
3083 }
3084 } finally {
3085 Binder.restoreCallingIdentity(callingId);
3086 }
3087 return true;
3088 }
3089
Dianne Hackborn03abb812010-01-04 18:43:19 -08003090 public void killBackgroundProcesses(final String packageName) {
3091 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3092 != PackageManager.PERMISSION_GRANTED &&
3093 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3094 != PackageManager.PERMISSION_GRANTED) {
3095 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 + Binder.getCallingPid()
3097 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003098 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003099 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 throw new SecurityException(msg);
3101 }
3102
3103 long callingId = Binder.clearCallingIdentity();
3104 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003105 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 int pkgUid = -1;
3107 synchronized(this) {
3108 try {
3109 pkgUid = pm.getPackageUid(packageName);
3110 } catch (RemoteException e) {
3111 }
3112 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003113 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003114 return;
3115 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003116 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003117 SECONDARY_SERVER_ADJ, false, true);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003118 }
3119 } finally {
3120 Binder.restoreCallingIdentity(callingId);
3121 }
3122 }
3123
3124 public void forceStopPackage(final String packageName) {
3125 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3126 != PackageManager.PERMISSION_GRANTED) {
3127 String msg = "Permission Denial: forceStopPackage() from pid="
3128 + Binder.getCallingPid()
3129 + ", uid=" + Binder.getCallingUid()
3130 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003131 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003132 throw new SecurityException(msg);
3133 }
3134
3135 long callingId = Binder.clearCallingIdentity();
3136 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003137 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003138 int pkgUid = -1;
3139 synchronized(this) {
3140 try {
3141 pkgUid = pm.getPackageUid(packageName);
3142 } catch (RemoteException e) {
3143 }
3144 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003145 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003146 return;
3147 }
3148 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003149 try {
3150 pm.setPackageStoppedState(packageName, true);
3151 } catch (RemoteException e) {
3152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153 }
3154 } finally {
3155 Binder.restoreCallingIdentity(callingId);
3156 }
3157 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003158
3159 /*
3160 * The pkg name and uid have to be specified.
3161 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3162 */
3163 public void killApplicationWithUid(String pkg, int uid) {
3164 if (pkg == null) {
3165 return;
3166 }
3167 // Make sure the uid is valid.
3168 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003169 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003170 return;
3171 }
3172 int callerUid = Binder.getCallingUid();
3173 // Only the system server can kill an application
3174 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003175 // Post an aysnc message to kill the application
3176 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3177 msg.arg1 = uid;
3178 msg.arg2 = 0;
3179 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003180 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003181 } else {
3182 throw new SecurityException(callerUid + " cannot kill pkg: " +
3183 pkg);
3184 }
3185 }
3186
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003187 public void closeSystemDialogs(String reason) {
3188 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003189 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003190 if (reason != null) {
3191 intent.putExtra("reason", reason);
3192 }
3193
3194 final int uid = Binder.getCallingUid();
3195 final long origId = Binder.clearCallingIdentity();
3196 synchronized (this) {
3197 int i = mWatchers.beginBroadcast();
3198 while (i > 0) {
3199 i--;
3200 IActivityWatcher w = mWatchers.getBroadcastItem(i);
3201 if (w != null) {
3202 try {
3203 w.closingSystemDialogs(reason);
3204 } catch (RemoteException e) {
3205 }
3206 }
3207 }
3208 mWatchers.finishBroadcast();
3209
Dianne Hackbornffa42482009-09-23 22:20:11 -07003210 mWindowManager.closeSystemDialogs(reason);
3211
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003212 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3213 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003214 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003215 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003216 Activity.RESULT_CANCELED, null, "close-sys");
3217 }
3218 }
3219
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003220 broadcastIntentLocked(null, null, intent, null,
3221 null, 0, null, null, null, false, false, -1, uid);
3222 }
3223 Binder.restoreCallingIdentity(origId);
3224 }
3225
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003226 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003227 throws RemoteException {
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003228 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3229 for (int i=pids.length-1; i>=0; i--) {
3230 infos[i] = new Debug.MemoryInfo();
3231 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003232 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003233 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003234 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003235
3236 public void killApplicationProcess(String processName, int uid) {
3237 if (processName == null) {
3238 return;
3239 }
3240
3241 int callerUid = Binder.getCallingUid();
3242 // Only the system server can kill an application
3243 if (callerUid == Process.SYSTEM_UID) {
3244 synchronized (this) {
3245 ProcessRecord app = getProcessRecordLocked(processName, uid);
3246 if (app != null) {
3247 try {
3248 app.thread.scheduleSuicide();
3249 } catch (RemoteException e) {
3250 // If the other end already died, then our work here is done.
3251 }
3252 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003253 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003254 + processName + " / " + uid);
3255 }
3256 }
3257 } else {
3258 throw new SecurityException(callerUid + " cannot kill app process: " +
3259 processName);
3260 }
3261 }
3262
Dianne Hackborn03abb812010-01-04 18:43:19 -08003263 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003264 forceStopPackageLocked(packageName, uid, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3266 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003267 if (!mProcessesReady) {
3268 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 intent.putExtra(Intent.EXTRA_UID, uid);
3271 broadcastIntentLocked(null, null, intent,
3272 null, null, 0, null, null, null,
3273 false, false, MY_PID, Process.SYSTEM_UID);
3274 }
3275
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003276 private final boolean killPackageProcessesLocked(String packageName, int uid,
3277 int minOomAdj, boolean callerWillRestart, boolean doit) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003278 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279
Dianne Hackborn03abb812010-01-04 18:43:19 -08003280 // Remove all processes this package may have touched: all with the
3281 // same UID (except for the system or root user), and all whose name
3282 // matches the package name.
3283 final String procNamePrefix = packageName + ":";
3284 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3285 final int NA = apps.size();
3286 for (int ia=0; ia<NA; ia++) {
3287 ProcessRecord app = apps.valueAt(ia);
3288 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003289 if (doit) {
3290 procs.add(app);
3291 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003292 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3293 || app.processName.equals(packageName)
3294 || app.processName.startsWith(procNamePrefix)) {
3295 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003296 if (!doit) {
3297 return true;
3298 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003299 app.removed = true;
3300 procs.add(app);
3301 }
3302 }
3303 }
3304 }
3305
3306 int N = procs.size();
3307 for (int i=0; i<N; i++) {
3308 removeProcessLocked(procs.get(i), callerWillRestart);
3309 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003310 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003311 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003312
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003313 private final boolean forceStopPackageLocked(String name, int uid,
3314 boolean callerWillRestart, boolean purgeCache, boolean doit) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 int i, N;
3316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 if (uid < 0) {
3318 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003319 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 } catch (RemoteException e) {
3321 }
3322 }
3323
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003324 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003325 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003326
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003327 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3328 while (badApps.hasNext()) {
3329 SparseArray<Long> ba = badApps.next();
3330 if (ba.get(uid) != null) {
3331 badApps.remove();
3332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 }
3334 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003335
3336 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
3337 callerWillRestart, doit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003339 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3340 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 if (r.packageName.equals(name)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003342 if (!doit) {
3343 return true;
3344 }
3345 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003346 Slog.i(TAG, " Force finishing activity " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 if (r.app != null) {
3348 r.app.removed = true;
3349 }
3350 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003351 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "uninstall");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 }
3353 }
3354
3355 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3356 for (ServiceRecord service : mServices.values()) {
3357 if (service.packageName.equals(name)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003358 if (!doit) {
3359 return true;
3360 }
3361 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003362 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 if (service.app != null) {
3364 service.app.removed = true;
3365 }
3366 service.app = null;
3367 services.add(service);
3368 }
3369 }
3370
3371 N = services.size();
3372 for (i=0; i<N; i++) {
3373 bringDownServiceLocked(services.get(i), true);
3374 }
3375
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003376 if (doit) {
3377 if (purgeCache) {
3378 AttributeCache ac = AttributeCache.instance();
3379 if (ac != null) {
3380 ac.removePackage(name);
3381 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003382 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003383 mMainStack.resumeTopActivityLocked(null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003384 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003385
3386 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 }
3388
3389 private final boolean removeProcessLocked(ProcessRecord app, boolean callerWillRestart) {
3390 final String name = app.processName;
3391 final int uid = app.info.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003392 if (DEBUG_PROCESSES) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 TAG, "Force removing process " + app + " (" + name
3394 + "/" + uid + ")");
3395
3396 mProcessNames.remove(name, uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003397 if (mHeavyWeightProcess == app) {
3398 mHeavyWeightProcess = null;
3399 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 boolean needRestart = false;
3402 if (app.pid > 0 && app.pid != MY_PID) {
3403 int pid = app.pid;
3404 synchronized (mPidsSelfLocked) {
3405 mPidsSelfLocked.remove(pid);
3406 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3407 }
3408 handleAppDiedLocked(app, true);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003409 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 Process.killProcess(pid);
3411
3412 if (app.persistent) {
3413 if (!callerWillRestart) {
3414 addAppLocked(app.info);
3415 } else {
3416 needRestart = true;
3417 }
3418 }
3419 } else {
3420 mRemovedProcesses.add(app);
3421 }
3422
3423 return needRestart;
3424 }
3425
3426 private final void processStartTimedOutLocked(ProcessRecord app) {
3427 final int pid = app.pid;
3428 boolean gone = false;
3429 synchronized (mPidsSelfLocked) {
3430 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3431 if (knownApp != null && knownApp.thread == null) {
3432 mPidsSelfLocked.remove(pid);
3433 gone = true;
3434 }
3435 }
3436
3437 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003438 Slog.w(TAG, "Process " + app + " failed to attach");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003439 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.info.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003440 app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003442 if (mHeavyWeightProcess == app) {
3443 mHeavyWeightProcess = null;
3444 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3445 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003446 // Take care of any launching providers waiting for this process.
3447 checkAppInLaunchingProvidersLocked(app, true);
3448 // Take care of any services that are waiting for the process.
3449 for (int i=0; i<mPendingServices.size(); i++) {
3450 ServiceRecord sr = mPendingServices.get(i);
3451 if (app.info.uid == sr.appInfo.uid
3452 && app.processName.equals(sr.processName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003453 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003454 mPendingServices.remove(i);
3455 i--;
3456 bringDownServiceLocked(sr, true);
3457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003459 Process.killProcess(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003460 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003461 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003462 try {
3463 IBackupManager bm = IBackupManager.Stub.asInterface(
3464 ServiceManager.getService(Context.BACKUP_SERVICE));
3465 bm.agentDisconnected(app.info.packageName);
3466 } catch (RemoteException e) {
3467 // Can't happen; the backup manager is local
3468 }
3469 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003470 if (mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003471 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003472 mPendingBroadcast.state = BroadcastRecord.IDLE;
3473 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003474 mPendingBroadcast = null;
3475 scheduleBroadcastsLocked();
3476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003478 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 }
3480 }
3481
3482 private final boolean attachApplicationLocked(IApplicationThread thread,
3483 int pid) {
3484
3485 // Find the application record that is being attached... either via
3486 // the pid if we are running in multiple processes, or just pull the
3487 // next app record if we are emulating process with anonymous threads.
3488 ProcessRecord app;
3489 if (pid != MY_PID && pid >= 0) {
3490 synchronized (mPidsSelfLocked) {
3491 app = mPidsSelfLocked.get(pid);
3492 }
3493 } else if (mStartingProcesses.size() > 0) {
3494 app = mStartingProcesses.remove(0);
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003495 app.setPid(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 } else {
3497 app = null;
3498 }
3499
3500 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003501 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003503 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 if (pid > 0 && pid != MY_PID) {
3505 Process.killProcess(pid);
3506 } else {
3507 try {
3508 thread.scheduleExit();
3509 } catch (Exception e) {
3510 // Ignore exceptions.
3511 }
3512 }
3513 return false;
3514 }
3515
3516 // If this application record is still attached to a previous
3517 // process, clean it up now.
3518 if (app.thread != null) {
3519 handleAppDiedLocked(app, true);
3520 }
3521
3522 // Tell the process all about itself.
3523
Joe Onorato8a9b2202010-02-26 18:56:32 -08003524 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 TAG, "Binding process pid " + pid + " to record " + app);
3526
3527 String processName = app.processName;
3528 try {
3529 thread.asBinder().linkToDeath(new AppDeathRecipient(
3530 app, pid, thread), 0);
3531 } catch (RemoteException e) {
3532 app.resetPackageList();
3533 startProcessLocked(app, "link fail", processName);
3534 return false;
3535 }
3536
Doug Zongker2bec3d42009-12-04 12:52:44 -08003537 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538
3539 app.thread = thread;
3540 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003541 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3542 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 app.forcingToForeground = null;
3544 app.foregroundServices = false;
3545 app.debugging = false;
3546
3547 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3548
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003549 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003550 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003552 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003553 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003554 }
3555
Joe Onorato8a9b2202010-02-26 18:56:32 -08003556 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 TAG, "New app record " + app
3558 + " thread=" + thread.asBinder() + " pid=" + pid);
3559 try {
3560 int testMode = IApplicationThread.DEBUG_OFF;
3561 if (mDebugApp != null && mDebugApp.equals(processName)) {
3562 testMode = mWaitForDebugger
3563 ? IApplicationThread.DEBUG_WAIT
3564 : IApplicationThread.DEBUG_ON;
3565 app.debugging = true;
3566 if (mDebugTransient) {
3567 mDebugApp = mOrigDebugApp;
3568 mWaitForDebugger = mOrigWaitForDebugger;
3569 }
3570 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003571
Christopher Tate181fafa2009-05-14 11:12:14 -07003572 // If the app is being launched for restore or full backup, set it up specially
3573 boolean isRestrictedBackupMode = false;
3574 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3575 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
3576 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3577 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003578
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003579 ensurePackageDexOpt(app.instrumentationInfo != null
3580 ? app.instrumentationInfo.packageName
3581 : app.info.packageName);
3582 if (app.instrumentationClass != null) {
3583 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003584 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003585 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003586 + processName + " with config " + mConfiguration);
Dianne Hackborn1655be42009-05-08 14:29:01 -07003587 thread.bindApplication(processName, app.instrumentationInfo != null
3588 ? app.instrumentationInfo : app.info, providers,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003589 app.instrumentationClass, app.instrumentationProfileFile,
3590 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003591 isRestrictedBackupMode || !normalMode,
3592 mConfiguration, getCommonServicesLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003593 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003594 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 } catch (Exception e) {
3596 // todo: Yikes! What should we do? For now we will try to
3597 // start another process, but that could easily get us in
3598 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003599 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600
3601 app.resetPackageList();
3602 startProcessLocked(app, "bind fail", processName);
3603 return false;
3604 }
3605
3606 // Remove this record from the list of starting applications.
3607 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003608 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3609 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 mProcessesOnHold.remove(app);
3611
3612 boolean badApp = false;
3613 boolean didSomething = false;
3614
3615 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003616 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003617 if (hr != null && normalMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
3619 && processName.equals(hr.processName)) {
3620 try {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003621 if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 didSomething = true;
3623 }
3624 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003625 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 + hr.intent.getComponent().flattenToShortString(), e);
3627 badApp = true;
3628 }
3629 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003630 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 }
3632 }
3633
3634 // Find any services that should be running in this process...
3635 if (!badApp && mPendingServices.size() > 0) {
3636 ServiceRecord sr = null;
3637 try {
3638 for (int i=0; i<mPendingServices.size(); i++) {
3639 sr = mPendingServices.get(i);
3640 if (app.info.uid != sr.appInfo.uid
3641 || !processName.equals(sr.processName)) {
3642 continue;
3643 }
3644
3645 mPendingServices.remove(i);
3646 i--;
3647 realStartServiceLocked(sr, app);
3648 didSomething = true;
3649 }
3650 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003651 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 + sr.shortName, e);
3653 badApp = true;
3654 }
3655 }
3656
3657 // Check if the next broadcast receiver is in this process...
3658 BroadcastRecord br = mPendingBroadcast;
3659 if (!badApp && br != null && br.curApp == app) {
3660 try {
3661 mPendingBroadcast = null;
3662 processCurBroadcastLocked(br, app);
3663 didSomething = true;
3664 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003665 Slog.w(TAG, "Exception in new application when starting receiver "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 + br.curComponent.flattenToShortString(), e);
3667 badApp = true;
Jeff Brown4d94a762010-09-23 11:33:28 -07003668 logBroadcastReceiverDiscardLocked(br);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 finishReceiverLocked(br.receiver, br.resultCode, br.resultData,
3670 br.resultExtras, br.resultAbort, true);
3671 scheduleBroadcastsLocked();
Magnus Edlund7bb25812010-02-24 15:45:06 +01003672 // We need to reset the state if we fails to start the receiver.
3673 br.state = BroadcastRecord.IDLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 }
3675 }
3676
Christopher Tate181fafa2009-05-14 11:12:14 -07003677 // Check whether the next backup agent is in this process...
3678 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.info.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003679 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003680 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003681 try {
3682 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, mBackupTarget.backupMode);
3683 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003684 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003685 e.printStackTrace();
3686 }
3687 }
3688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 if (badApp) {
3690 // todo: Also need to kill application to deal with all
3691 // kinds of exceptions.
3692 handleAppDiedLocked(app, false);
3693 return false;
3694 }
3695
3696 if (!didSomething) {
3697 updateOomAdjLocked();
3698 }
3699
3700 return true;
3701 }
3702
3703 public final void attachApplication(IApplicationThread thread) {
3704 synchronized (this) {
3705 int callingPid = Binder.getCallingPid();
3706 final long origId = Binder.clearCallingIdentity();
3707 attachApplicationLocked(thread, callingPid);
3708 Binder.restoreCallingIdentity(origId);
3709 }
3710 }
3711
Dianne Hackborne88846e2009-09-30 21:34:25 -07003712 public final void activityIdle(IBinder token, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003713 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003714 mMainStack.activityIdleInternal(token, false, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 Binder.restoreCallingIdentity(origId);
3716 }
3717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003720 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 mWindowManager.enableScreenAfterBoot();
3722 }
3723
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003724 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003725 IntentFilter pkgFilter = new IntentFilter();
3726 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
3727 pkgFilter.addDataScheme("package");
3728 mContext.registerReceiver(new BroadcastReceiver() {
3729 @Override
3730 public void onReceive(Context context, Intent intent) {
3731 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3732 if (pkgs != null) {
3733 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07003734 synchronized (ActivityManagerService.this) {
3735 if (forceStopPackageLocked(pkg, -1, false, false, false)) {
3736 setResultCode(Activity.RESULT_OK);
3737 return;
3738 }
3739 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003740 }
3741 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003742 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003743 }, pkgFilter);
3744
3745 synchronized (this) {
3746 // Ensure that any processes we had put on hold are now started
3747 // up.
3748 final int NP = mProcessesOnHold.size();
3749 if (NP > 0) {
3750 ArrayList<ProcessRecord> procs =
3751 new ArrayList<ProcessRecord>(mProcessesOnHold);
3752 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003753 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
3754 + procs.get(ip));
3755 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003756 }
3757 }
3758
3759 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003760 // Start looking for apps that are abusing wake locks.
3761 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003762 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003763 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07003764 SystemProperties.set("sys.boot_completed", "1");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003765 broadcastIntentLocked(null, null,
3766 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
3767 null, null, 0, null, null,
3768 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
3769 false, false, MY_PID, Process.SYSTEM_UID);
3770 }
3771 }
3772 }
3773
3774 final void ensureBootCompleted() {
3775 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003776 boolean enableScreen;
3777 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003778 booting = mBooting;
3779 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003780 enableScreen = !mBooted;
3781 mBooted = true;
3782 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003783
3784 if (booting) {
3785 finishBooting();
3786 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003787
3788 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003789 enableScreenAfterBoot();
3790 }
3791 }
3792
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003793 public final void activityPaused(IBinder token) {
3794 final long origId = Binder.clearCallingIdentity();
3795 mMainStack.activityPaused(token, false);
3796 Binder.restoreCallingIdentity(origId);
3797 }
3798
3799 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
3800 CharSequence description) {
3801 if (localLOGV) Slog.v(
3802 TAG, "Activity stopped: token=" + token);
3803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 // Refuse possible leaked file descriptors
3805 if (icicle != null && icicle.hasFileDescriptors()) {
3806 throw new IllegalArgumentException("File descriptors passed in Bundle");
3807 }
3808
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003809 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810
3811 final long origId = Binder.clearCallingIdentity();
3812
3813 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003814 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003816 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003817 r.icicle = icicle;
3818 r.haveState = true;
3819 if (thumbnail != null) {
3820 r.thumbnail = thumbnail;
Dianne Hackbornd2835932010-12-13 16:28:46 -08003821 if (r.task != null) {
3822 r.task.lastThumbnail = r.thumbnail;
3823 }
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 r.description = description;
Dianne Hackbornd2835932010-12-13 16:28:46 -08003826 if (r.task != null) {
3827 r.task.lastDescription = r.description;
3828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 r.stopped = true;
3830 r.state = ActivityState.STOPPED;
3831 if (!r.finishing) {
3832 if (r.configDestroy) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003833 r.stack.destroyActivityLocked(r, true);
3834 r.stack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 }
3836 }
3837 }
3838 }
3839
3840 if (r != null) {
3841 sendPendingThumbnail(r, null, null, null, false);
3842 }
3843
3844 trimApplications();
3845
3846 Binder.restoreCallingIdentity(origId);
3847 }
3848
3849 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003850 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003851 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 }
3853
3854 public String getCallingPackage(IBinder token) {
3855 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003856 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07003857 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 }
3859 }
3860
3861 public ComponentName getCallingActivity(IBinder token) {
3862 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003863 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 return r != null ? r.intent.getComponent() : null;
3865 }
3866 }
3867
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003868 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003869 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003871 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 if (r != null) {
3873 return r.resultTo;
3874 }
3875 }
3876 return null;
3877 }
3878
3879 public ComponentName getActivityClassForToken(IBinder token) {
3880 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003881 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003883 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 return r.intent.getComponent();
3885 }
3886 return null;
3887 }
3888 }
3889
3890 public String getPackageForToken(IBinder token) {
3891 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003892 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003894 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 return r.packageName;
3896 }
3897 return null;
3898 }
3899 }
3900
3901 public IIntentSender getIntentSender(int type,
3902 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003903 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003905 if (intents != null) {
3906 if (intents.length < 1) {
3907 throw new IllegalArgumentException("Intents array length must be >= 1");
3908 }
3909 for (int i=0; i<intents.length; i++) {
3910 Intent intent = intents[i];
3911 if (intent == null) {
3912 throw new IllegalArgumentException("Null intent at index " + i);
3913 }
3914 if (intent.hasFileDescriptors()) {
3915 throw new IllegalArgumentException("File descriptors passed in Intent");
3916 }
3917 if (type == INTENT_SENDER_BROADCAST &&
3918 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
3919 throw new IllegalArgumentException(
3920 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
3921 }
3922 intents[i] = new Intent(intent);
3923 }
3924 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003925 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003926 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003927 }
3928 }
3929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 synchronized(this) {
3931 int callingUid = Binder.getCallingUid();
3932 try {
3933 if (callingUid != 0 && callingUid != Process.SYSTEM_UID &&
3934 Process.supportsProcesses()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003935 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 .getPackageUid(packageName);
3937 if (uid != Binder.getCallingUid()) {
3938 String msg = "Permission Denial: getIntentSender() from pid="
3939 + Binder.getCallingPid()
3940 + ", uid=" + Binder.getCallingUid()
3941 + ", (need uid=" + uid + ")"
3942 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003943 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 throw new SecurityException(msg);
3945 }
3946 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003947
3948 return getIntentSenderLocked(type, packageName, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003949 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 } catch (RemoteException e) {
3952 throw new SecurityException(e);
3953 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003954 }
3955 }
3956
3957 IIntentSender getIntentSenderLocked(int type,
3958 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003959 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003960 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003961 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003962 int index = mMainStack.indexOfTokenLocked(token);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003963 if (index < 0) {
3964 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003966 activity = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003967 if (activity.finishing) {
3968 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003970 }
3971
3972 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
3973 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
3974 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
3975 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
3976 |PendingIntent.FLAG_UPDATE_CURRENT);
3977
3978 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
3979 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003980 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003981 WeakReference<PendingIntentRecord> ref;
3982 ref = mIntentSenderRecords.get(key);
3983 PendingIntentRecord rec = ref != null ? ref.get() : null;
3984 if (rec != null) {
3985 if (!cancelCurrent) {
3986 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003987 if (rec.key.requestIntent != null) {
3988 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
3989 }
3990 if (intents != null) {
3991 intents[intents.length-1] = rec.key.requestIntent;
3992 rec.key.allIntents = intents;
3993 rec.key.allResolvedTypes = resolvedTypes;
3994 } else {
3995 rec.key.allIntents = null;
3996 rec.key.allResolvedTypes = null;
3997 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 return rec;
4000 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004001 rec.canceled = true;
4002 mIntentSenderRecords.remove(key);
4003 }
4004 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 return rec;
4006 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004007 rec = new PendingIntentRecord(this, key, callingUid);
4008 mIntentSenderRecords.put(key, rec.ref);
4009 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
4010 if (activity.pendingResults == null) {
4011 activity.pendingResults
4012 = new HashSet<WeakReference<PendingIntentRecord>>();
4013 }
4014 activity.pendingResults.add(rec.ref);
4015 }
4016 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 }
4018
4019 public void cancelIntentSender(IIntentSender sender) {
4020 if (!(sender instanceof PendingIntentRecord)) {
4021 return;
4022 }
4023 synchronized(this) {
4024 PendingIntentRecord rec = (PendingIntentRecord)sender;
4025 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004026 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 .getPackageUid(rec.key.packageName);
4028 if (uid != Binder.getCallingUid()) {
4029 String msg = "Permission Denial: cancelIntentSender() from pid="
4030 + Binder.getCallingPid()
4031 + ", uid=" + Binder.getCallingUid()
4032 + " is not allowed to cancel packges "
4033 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004034 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 throw new SecurityException(msg);
4036 }
4037 } catch (RemoteException e) {
4038 throw new SecurityException(e);
4039 }
4040 cancelIntentSenderLocked(rec, true);
4041 }
4042 }
4043
4044 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4045 rec.canceled = true;
4046 mIntentSenderRecords.remove(rec.key);
4047 if (cleanActivity && rec.key.activity != null) {
4048 rec.key.activity.pendingResults.remove(rec.ref);
4049 }
4050 }
4051
4052 public String getPackageForIntentSender(IIntentSender pendingResult) {
4053 if (!(pendingResult instanceof PendingIntentRecord)) {
4054 return null;
4055 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004056 try {
4057 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4058 return res.key.packageName;
4059 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 }
4061 return null;
4062 }
4063
4064 public void setProcessLimit(int max) {
4065 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4066 "setProcessLimit()");
4067 mProcessLimit = max;
4068 }
4069
4070 public int getProcessLimit() {
4071 return mProcessLimit;
4072 }
4073
4074 void foregroundTokenDied(ForegroundToken token) {
4075 synchronized (ActivityManagerService.this) {
4076 synchronized (mPidsSelfLocked) {
4077 ForegroundToken cur
4078 = mForegroundProcesses.get(token.pid);
4079 if (cur != token) {
4080 return;
4081 }
4082 mForegroundProcesses.remove(token.pid);
4083 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4084 if (pr == null) {
4085 return;
4086 }
4087 pr.forcingToForeground = null;
4088 pr.foregroundServices = false;
4089 }
4090 updateOomAdjLocked();
4091 }
4092 }
4093
4094 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4095 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4096 "setProcessForeground()");
4097 synchronized(this) {
4098 boolean changed = false;
4099
4100 synchronized (mPidsSelfLocked) {
4101 ProcessRecord pr = mPidsSelfLocked.get(pid);
4102 if (pr == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004103 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 return;
4105 }
4106 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4107 if (oldToken != null) {
4108 oldToken.token.unlinkToDeath(oldToken, 0);
4109 mForegroundProcesses.remove(pid);
4110 pr.forcingToForeground = null;
4111 changed = true;
4112 }
4113 if (isForeground && token != null) {
4114 ForegroundToken newToken = new ForegroundToken() {
4115 public void binderDied() {
4116 foregroundTokenDied(this);
4117 }
4118 };
4119 newToken.pid = pid;
4120 newToken.token = token;
4121 try {
4122 token.linkToDeath(newToken, 0);
4123 mForegroundProcesses.put(pid, newToken);
4124 pr.forcingToForeground = token;
4125 changed = true;
4126 } catch (RemoteException e) {
4127 // If the process died while doing this, we will later
4128 // do the cleanup with the process death link.
4129 }
4130 }
4131 }
4132
4133 if (changed) {
4134 updateOomAdjLocked();
4135 }
4136 }
4137 }
4138
4139 // =========================================================
4140 // PERMISSIONS
4141 // =========================================================
4142
4143 static class PermissionController extends IPermissionController.Stub {
4144 ActivityManagerService mActivityManagerService;
4145 PermissionController(ActivityManagerService activityManagerService) {
4146 mActivityManagerService = activityManagerService;
4147 }
4148
4149 public boolean checkPermission(String permission, int pid, int uid) {
4150 return mActivityManagerService.checkPermission(permission, pid,
4151 uid) == PackageManager.PERMISSION_GRANTED;
4152 }
4153 }
4154
4155 /**
4156 * This can be called with or without the global lock held.
4157 */
4158 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004159 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 // We might be performing an operation on behalf of an indirect binder
4161 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4162 // client identity accordingly before proceeding.
4163 Identity tlsIdentity = sCallerIdentity.get();
4164 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004165 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4167 uid = tlsIdentity.uid;
4168 pid = tlsIdentity.pid;
4169 }
4170
4171 // Root, system server and our own process get to do everything.
4172 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID ||
4173 !Process.supportsProcesses()) {
4174 return PackageManager.PERMISSION_GRANTED;
4175 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004176 // If there is a uid that owns whatever is being accessed, it has
4177 // blanket access to it regardless of the permissions it requires.
4178 if (owningUid >= 0 && uid == owningUid) {
4179 return PackageManager.PERMISSION_GRANTED;
4180 }
4181 // If the target is not exported, then nobody else can get to it.
4182 if (!exported) {
4183 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 return PackageManager.PERMISSION_DENIED;
4185 }
4186 if (permission == null) {
4187 return PackageManager.PERMISSION_GRANTED;
4188 }
4189 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004190 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 .checkUidPermission(permission, uid);
4192 } catch (RemoteException e) {
4193 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004194 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004195 }
4196 return PackageManager.PERMISSION_DENIED;
4197 }
4198
4199 /**
4200 * As the only public entry point for permissions checking, this method
4201 * can enforce the semantic that requesting a check on a null global
4202 * permission is automatically denied. (Internally a null permission
4203 * string is used when calling {@link #checkComponentPermission} in cases
4204 * when only uid-based security is needed.)
4205 *
4206 * This can be called with or without the global lock held.
4207 */
4208 public int checkPermission(String permission, int pid, int uid) {
4209 if (permission == null) {
4210 return PackageManager.PERMISSION_DENIED;
4211 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004212 return checkComponentPermission(permission, pid, uid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 }
4214
4215 /**
4216 * Binder IPC calls go through the public entry point.
4217 * This can be called with or without the global lock held.
4218 */
4219 int checkCallingPermission(String permission) {
4220 return checkPermission(permission,
4221 Binder.getCallingPid(),
4222 Binder.getCallingUid());
4223 }
4224
4225 /**
4226 * This can be called with or without the global lock held.
4227 */
4228 void enforceCallingPermission(String permission, String func) {
4229 if (checkCallingPermission(permission)
4230 == PackageManager.PERMISSION_GRANTED) {
4231 return;
4232 }
4233
4234 String msg = "Permission Denial: " + func + " from pid="
4235 + Binder.getCallingPid()
4236 + ", uid=" + Binder.getCallingUid()
4237 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004238 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 throw new SecurityException(msg);
4240 }
4241
4242 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07004243 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
4244 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4245 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
4246 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4247 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004249 // Is the component private from the target uid?
4250 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
4251
4252 // Acceptable if the there is no read permission needed from the
4253 // target or the target is holding the read permission.
4254 if (!readPerm) {
4255 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004256 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004257 == PackageManager.PERMISSION_GRANTED)) {
4258 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 }
4260 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004261
4262 // Acceptable if the there is no write permission needed from the
4263 // target or the target is holding the read permission.
4264 if (!writePerm) {
4265 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004267 == PackageManager.PERMISSION_GRANTED)) {
4268 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 }
4270 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004271
4272 // Acceptable if there is a path permission matching the URI that
4273 // the target holds the permission on.
4274 PathPermission[] pps = pi.pathPermissions;
4275 if (pps != null && (!readPerm || !writePerm)) {
4276 final String path = uri.getPath();
4277 int i = pps.length;
4278 while (i > 0 && (!readPerm || !writePerm)) {
4279 i--;
4280 PathPermission pp = pps[i];
4281 if (!readPerm) {
4282 final String pprperm = pp.getReadPermission();
4283 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4284 + pprperm + " for " + pp.getPath()
4285 + ": match=" + pp.match(path)
4286 + " check=" + pm.checkUidPermission(pprperm, uid));
4287 if (pprperm != null && pp.match(path) &&
4288 (pm.checkUidPermission(pprperm, uid)
4289 == PackageManager.PERMISSION_GRANTED)) {
4290 readPerm = true;
4291 }
4292 }
4293 if (!writePerm) {
4294 final String ppwperm = pp.getWritePermission();
4295 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4296 + ppwperm + " for " + pp.getPath()
4297 + ": match=" + pp.match(path)
4298 + " check=" + pm.checkUidPermission(ppwperm, uid));
4299 if (ppwperm != null && pp.match(path) &&
4300 (pm.checkUidPermission(ppwperm, uid)
4301 == PackageManager.PERMISSION_GRANTED)) {
4302 writePerm = true;
4303 }
4304 }
4305 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 } catch (RemoteException e) {
4308 return false;
4309 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004310
4311 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004312 }
4313
4314 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4315 int modeFlags) {
4316 // Root gets to do everything.
4317 if (uid == 0 || !Process.supportsProcesses()) {
4318 return true;
4319 }
4320 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4321 if (perms == null) return false;
4322 UriPermission perm = perms.get(uri);
4323 if (perm == null) return false;
4324 return (modeFlags&perm.modeFlags) == modeFlags;
4325 }
4326
4327 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
4328 // Another redirected-binder-call permissions check as in
4329 // {@link checkComponentPermission}.
4330 Identity tlsIdentity = sCallerIdentity.get();
4331 if (tlsIdentity != null) {
4332 uid = tlsIdentity.uid;
4333 pid = tlsIdentity.pid;
4334 }
4335
4336 // Our own process gets to do everything.
4337 if (pid == MY_PID) {
4338 return PackageManager.PERMISSION_GRANTED;
4339 }
4340 synchronized(this) {
4341 return checkUriPermissionLocked(uri, uid, modeFlags)
4342 ? PackageManager.PERMISSION_GRANTED
4343 : PackageManager.PERMISSION_DENIED;
4344 }
4345 }
4346
Dianne Hackborn39792d22010-08-19 18:01:52 -07004347 /**
4348 * Check if the targetPkg can be granted permission to access uri by
4349 * the callingUid using the given modeFlags. Throws a security exception
4350 * if callingUid is not allowed to do this. Returns the uid of the target
4351 * if the URI permission grant should be performed; returns -1 if it is not
4352 * needed (for example targetPkg already has permission to access the URI).
4353 */
4354 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
4355 Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4357 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4358 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004359 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 }
4361
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004362 if (targetPkg != null) {
4363 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4364 "Checking grant " + targetPkg + " permission to " + uri);
4365 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004366
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004367 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368
4369 // If this is not a content: uri, we can't do anything with it.
4370 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004371 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004372 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004373 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 }
4375
4376 String name = uri.getAuthority();
4377 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004378 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 if (cpr != null) {
4380 pi = cpr.info;
4381 } else {
4382 try {
4383 pi = pm.resolveContentProvider(name,
4384 PackageManager.GET_URI_PERMISSION_PATTERNS);
4385 } catch (RemoteException ex) {
4386 }
4387 }
4388 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004389 Slog.w(TAG, "No content provider found for: " + name);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004390 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 }
4392
4393 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004394 if (targetPkg != null) {
4395 try {
4396 targetUid = pm.getPackageUid(targetPkg);
4397 if (targetUid < 0) {
4398 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4399 "Can't grant URI permission no uid for: " + targetPkg);
4400 return -1;
4401 }
4402 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004403 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004404 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004405 } else {
4406 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004407 }
4408
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004409 if (targetUid >= 0) {
4410 // First... does the target actually need this permission?
4411 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4412 // No need to grant the target this permission.
4413 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4414 "Target " + targetPkg + " already has full permission to " + uri);
4415 return -1;
4416 }
4417 } else {
4418 // First... there is no target package, so can anyone access it?
4419 boolean allowed = pi.exported;
4420 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4421 if (pi.readPermission != null) {
4422 allowed = false;
4423 }
4424 }
4425 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4426 if (pi.writePermission != null) {
4427 allowed = false;
4428 }
4429 }
4430 if (allowed) {
4431 return -1;
4432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004433 }
4434
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004435 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004436 if (!pi.grantUriPermissions) {
4437 throw new SecurityException("Provider " + pi.packageName
4438 + "/" + pi.name
4439 + " does not allow granting of Uri permissions (uri "
4440 + uri + ")");
4441 }
4442 if (pi.uriPermissionPatterns != null) {
4443 final int N = pi.uriPermissionPatterns.length;
4444 boolean allowed = false;
4445 for (int i=0; i<N; i++) {
4446 if (pi.uriPermissionPatterns[i] != null
4447 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4448 allowed = true;
4449 break;
4450 }
4451 }
4452 if (!allowed) {
4453 throw new SecurityException("Provider " + pi.packageName
4454 + "/" + pi.name
4455 + " does not allow granting of permission to path of Uri "
4456 + uri);
4457 }
4458 }
4459
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004460 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004462 if (callingUid != Process.myUid()) {
4463 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4464 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4465 throw new SecurityException("Uid " + callingUid
4466 + " does not have permission to uri " + uri);
4467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 }
4469 }
4470
Dianne Hackborn39792d22010-08-19 18:01:52 -07004471 return targetUid;
4472 }
4473
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004474 public int checkGrantUriPermission(int callingUid, String targetPkg,
4475 Uri uri, int modeFlags) {
4476 synchronized(this) {
4477 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4478 }
4479 }
4480
Dianne Hackborn39792d22010-08-19 18:01:52 -07004481 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4482 Uri uri, int modeFlags, UriPermissionOwner owner) {
4483 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4484 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4485 if (modeFlags == 0) {
4486 return;
4487 }
4488
4489 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004490 // to the uri, and the target doesn't. Let's now give this to
4491 // the target.
4492
Joe Onorato8a9b2202010-02-26 18:56:32 -08004493 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004494 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 HashMap<Uri, UriPermission> targetUris
4497 = mGrantedUriPermissions.get(targetUid);
4498 if (targetUris == null) {
4499 targetUris = new HashMap<Uri, UriPermission>();
4500 mGrantedUriPermissions.put(targetUid, targetUris);
4501 }
4502
4503 UriPermission perm = targetUris.get(uri);
4504 if (perm == null) {
4505 perm = new UriPermission(targetUid, uri);
4506 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004510 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004511 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004512 } else {
4513 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4514 perm.readOwners.add(owner);
4515 owner.addReadPermission(perm);
4516 }
4517 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4518 perm.writeOwners.add(owner);
4519 owner.addWritePermission(perm);
4520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004521 }
4522 }
4523
Dianne Hackborn39792d22010-08-19 18:01:52 -07004524 void grantUriPermissionLocked(int callingUid,
4525 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004526 if (targetPkg == null) {
4527 throw new NullPointerException("targetPkg");
4528 }
4529
Dianne Hackborn39792d22010-08-19 18:01:52 -07004530 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4531 if (targetUid < 0) {
4532 return;
4533 }
4534
4535 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4536 }
4537
4538 /**
4539 * Like checkGrantUriPermissionLocked, but takes an Intent.
4540 */
4541 int checkGrantUriPermissionFromIntentLocked(int callingUid,
4542 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004543 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004544 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004545 + " from " + intent + "; flags=0x"
4546 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4547
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004548 if (targetPkg == null) {
4549 throw new NullPointerException("targetPkg");
4550 }
4551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004553 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004554 }
4555 Uri data = intent.getData();
4556 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004557 return -1;
4558 }
4559 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4560 intent.getFlags());
4561 }
4562
4563 /**
4564 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4565 */
4566 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
4567 String targetPkg, Intent intent, UriPermissionOwner owner) {
4568 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
4569 intent.getFlags(), owner);
4570 }
4571
4572 void grantUriPermissionFromIntentLocked(int callingUid,
4573 String targetPkg, Intent intent, UriPermissionOwner owner) {
4574 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
4575 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 return;
4577 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004578
4579 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 }
4581
4582 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4583 Uri uri, int modeFlags) {
4584 synchronized(this) {
4585 final ProcessRecord r = getRecordForAppLocked(caller);
4586 if (r == null) {
4587 throw new SecurityException("Unable to find app for caller "
4588 + caller
4589 + " when granting permission to uri " + uri);
4590 }
4591 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004592 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 }
4594 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004595 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 }
4597
4598 grantUriPermissionLocked(r.info.uid, targetPkg, uri, modeFlags,
4599 null);
4600 }
4601 }
4602
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004603 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4605 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4606 HashMap<Uri, UriPermission> perms
4607 = mGrantedUriPermissions.get(perm.uid);
4608 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004609 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004610 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611 perms.remove(perm.uri);
4612 if (perms.size() == 0) {
4613 mGrantedUriPermissions.remove(perm.uid);
4614 }
4615 }
4616 }
4617 }
4618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004619 private void revokeUriPermissionLocked(int callingUid, Uri uri,
4620 int modeFlags) {
4621 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4622 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4623 if (modeFlags == 0) {
4624 return;
4625 }
4626
Joe Onorato8a9b2202010-02-26 18:56:32 -08004627 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004628 "Revoking all granted permissions to " + uri);
4629
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004630 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004631
4632 final String authority = uri.getAuthority();
4633 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004634 ContentProviderRecord cpr = mProvidersByName.get(authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 if (cpr != null) {
4636 pi = cpr.info;
4637 } else {
4638 try {
4639 pi = pm.resolveContentProvider(authority,
4640 PackageManager.GET_URI_PERMISSION_PATTERNS);
4641 } catch (RemoteException ex) {
4642 }
4643 }
4644 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004645 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004646 return;
4647 }
4648
4649 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07004650 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 // Right now, if you are not the original owner of the permission,
4652 // you are not allowed to revoke it.
4653 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4654 throw new SecurityException("Uid " + callingUid
4655 + " does not have permission to uri " + uri);
4656 //}
4657 }
4658
4659 // Go through all of the permissions and remove any that match.
4660 final List<String> SEGMENTS = uri.getPathSegments();
4661 if (SEGMENTS != null) {
4662 final int NS = SEGMENTS.size();
4663 int N = mGrantedUriPermissions.size();
4664 for (int i=0; i<N; i++) {
4665 HashMap<Uri, UriPermission> perms
4666 = mGrantedUriPermissions.valueAt(i);
4667 Iterator<UriPermission> it = perms.values().iterator();
4668 toploop:
4669 while (it.hasNext()) {
4670 UriPermission perm = it.next();
4671 Uri targetUri = perm.uri;
4672 if (!authority.equals(targetUri.getAuthority())) {
4673 continue;
4674 }
4675 List<String> targetSegments = targetUri.getPathSegments();
4676 if (targetSegments == null) {
4677 continue;
4678 }
4679 if (targetSegments.size() < NS) {
4680 continue;
4681 }
4682 for (int j=0; j<NS; j++) {
4683 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
4684 continue toploop;
4685 }
4686 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004687 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004688 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 perm.clearModes(modeFlags);
4690 if (perm.modeFlags == 0) {
4691 it.remove();
4692 }
4693 }
4694 if (perms.size() == 0) {
4695 mGrantedUriPermissions.remove(
4696 mGrantedUriPermissions.keyAt(i));
4697 N--;
4698 i--;
4699 }
4700 }
4701 }
4702 }
4703
4704 public void revokeUriPermission(IApplicationThread caller, Uri uri,
4705 int modeFlags) {
4706 synchronized(this) {
4707 final ProcessRecord r = getRecordForAppLocked(caller);
4708 if (r == null) {
4709 throw new SecurityException("Unable to find app for caller "
4710 + caller
4711 + " when revoking permission to uri " + uri);
4712 }
4713 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004714 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 return;
4716 }
4717
4718 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4719 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4720 if (modeFlags == 0) {
4721 return;
4722 }
4723
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004724 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004725
4726 final String authority = uri.getAuthority();
4727 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004728 ContentProviderRecord cpr = mProvidersByName.get(authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 if (cpr != null) {
4730 pi = cpr.info;
4731 } else {
4732 try {
4733 pi = pm.resolveContentProvider(authority,
4734 PackageManager.GET_URI_PERMISSION_PATTERNS);
4735 } catch (RemoteException ex) {
4736 }
4737 }
4738 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004739 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004740 return;
4741 }
4742
4743 revokeUriPermissionLocked(r.info.uid, uri, modeFlags);
4744 }
4745 }
4746
Dianne Hackborn7e269642010-08-25 19:50:20 -07004747 @Override
4748 public IBinder newUriPermissionOwner(String name) {
4749 synchronized(this) {
4750 UriPermissionOwner owner = new UriPermissionOwner(this, name);
4751 return owner.getExternalTokenLocked();
4752 }
4753 }
4754
4755 @Override
4756 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
4757 Uri uri, int modeFlags) {
4758 synchronized(this) {
4759 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
4760 if (owner == null) {
4761 throw new IllegalArgumentException("Unknown owner: " + token);
4762 }
4763 if (fromUid != Binder.getCallingUid()) {
4764 if (Binder.getCallingUid() != Process.myUid()) {
4765 // Only system code can grant URI permissions on behalf
4766 // of other users.
4767 throw new SecurityException("nice try");
4768 }
4769 }
4770 if (targetPkg == null) {
4771 throw new IllegalArgumentException("null target");
4772 }
4773 if (uri == null) {
4774 throw new IllegalArgumentException("null uri");
4775 }
4776
4777 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
4778 }
4779 }
4780
4781 @Override
4782 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
4783 synchronized(this) {
4784 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
4785 if (owner == null) {
4786 throw new IllegalArgumentException("Unknown owner: " + token);
4787 }
4788
4789 if (uri == null) {
4790 owner.removeUriPermissionsLocked(mode);
4791 } else {
4792 owner.removeUriPermissionLocked(uri, mode);
4793 }
4794 }
4795 }
4796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004797 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
4798 synchronized (this) {
4799 ProcessRecord app =
4800 who != null ? getRecordForAppLocked(who) : null;
4801 if (app == null) return;
4802
4803 Message msg = Message.obtain();
4804 msg.what = WAIT_FOR_DEBUGGER_MSG;
4805 msg.obj = app;
4806 msg.arg1 = waiting ? 1 : 0;
4807 mHandler.sendMessage(msg);
4808 }
4809 }
4810
4811 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
4812 outInfo.availMem = Process.getFreeMemory();
The Android Open Source Project4df24232009-03-05 14:34:35 -08004813 outInfo.threshold = HOME_APP_MEM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004814 outInfo.lowMemory = outInfo.availMem <
The Android Open Source Project4df24232009-03-05 14:34:35 -08004815 (HOME_APP_MEM + ((HIDDEN_APP_MEM-HOME_APP_MEM)/2));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004816 }
4817
4818 // =========================================================
4819 // TASK MANAGEMENT
4820 // =========================================================
4821
4822 public List getTasks(int maxNum, int flags,
4823 IThumbnailReceiver receiver) {
4824 ArrayList list = new ArrayList();
4825
4826 PendingThumbnailsRecord pending = null;
4827 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004828 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004829
4830 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004831 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004832 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
4833 + ", receiver=" + receiver);
4834
4835 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
4836 != PackageManager.PERMISSION_GRANTED) {
4837 if (receiver != null) {
4838 // If the caller wants to wait for pending thumbnails,
4839 // it ain't gonna get them.
4840 try {
4841 receiver.finished();
4842 } catch (RemoteException ex) {
4843 }
4844 }
4845 String msg = "Permission Denial: getTasks() from pid="
4846 + Binder.getCallingPid()
4847 + ", uid=" + Binder.getCallingUid()
4848 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004849 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004850 throw new SecurityException(msg);
4851 }
4852
Dianne Hackbornd2835932010-12-13 16:28:46 -08004853 final boolean canReadFb = (flags&ActivityManager.TASKS_GET_THUMBNAILS) != 0
4854 && checkCallingPermission(
4855 android.Manifest.permission.READ_FRAME_BUFFER)
4856 == PackageManager.PERMISSION_GRANTED;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004857
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004858 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004859 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004860 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004861 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004862 CharSequence topDescription = null;
4863 TaskRecord curTask = null;
4864 int numActivities = 0;
4865 int numRunning = 0;
4866 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004867 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004868 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004869 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870
4871 // Initialize state for next task if needed.
4872 if (top == null ||
4873 (top.state == ActivityState.INITIALIZING
4874 && top.task == r.task)) {
4875 top = r;
4876 topDescription = r.description;
4877 curTask = r.task;
4878 numActivities = numRunning = 0;
4879 }
4880
4881 // Add 'r' into the current task.
4882 numActivities++;
4883 if (r.app != null && r.app.thread != null) {
4884 numRunning++;
4885 }
4886 if (topDescription == null) {
4887 topDescription = r.description;
4888 }
4889
Joe Onorato8a9b2202010-02-26 18:56:32 -08004890 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 TAG, r.intent.getComponent().flattenToShortString()
4892 + ": task=" + r.task);
4893
4894 // If the next one is a different task, generate a new
4895 // TaskInfo entry for what we have.
4896 if (next == null || next.task != curTask) {
4897 ActivityManager.RunningTaskInfo ci
4898 = new ActivityManager.RunningTaskInfo();
4899 ci.id = curTask.taskId;
4900 ci.baseActivity = r.intent.getComponent();
4901 ci.topActivity = top.intent.getComponent();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004902 if (canReadFb) {
4903 if (top.thumbnail != null) {
4904 ci.thumbnail = top.thumbnail;
4905 } else if (top.state == ActivityState.RESUMED) {
Dianne Hackbornd2835932010-12-13 16:28:46 -08004906 ci.thumbnail = top.stack.screenshotActivities(top);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004907 }
4908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004909 ci.description = topDescription;
4910 ci.numActivities = numActivities;
4911 ci.numRunning = numRunning;
4912 //System.out.println(
4913 // "#" + maxNum + ": " + " descr=" + ci.description);
4914 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004915 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004916 TAG, "State=" + top.state + "Idle=" + top.idle
4917 + " app=" + top.app
4918 + " thr=" + (top.app != null ? top.app.thread : null));
4919 if (top.state == ActivityState.RESUMED
4920 || top.state == ActivityState.PAUSING) {
4921 if (top.idle && top.app != null
4922 && top.app.thread != null) {
4923 topRecord = top;
4924 topThumbnail = top.app.thread;
4925 } else {
4926 top.thumbnailNeeded = true;
4927 }
4928 }
4929 if (pending == null) {
4930 pending = new PendingThumbnailsRecord(receiver);
4931 }
4932 pending.pendingRecords.add(top);
4933 }
4934 list.add(ci);
4935 maxNum--;
4936 top = null;
4937 }
4938 }
4939
4940 if (pending != null) {
4941 mPendingThumbnails.add(pending);
4942 }
4943 }
4944
Joe Onorato8a9b2202010-02-26 18:56:32 -08004945 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004946
4947 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004948 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004949 try {
4950 topThumbnail.requestThumbnail(topRecord);
4951 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004952 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004953 sendPendingThumbnail(null, topRecord, null, null, true);
4954 }
4955 }
4956
4957 if (pending == null && receiver != null) {
4958 // In this case all thumbnails were available and the client
4959 // is being asked to be told when the remaining ones come in...
4960 // which is unusually, since the top-most currently running
4961 // activity should never have a canned thumbnail! Oh well.
4962 try {
4963 receiver.finished();
4964 } catch (RemoteException ex) {
4965 }
4966 }
4967
4968 return list;
4969 }
4970
4971 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
4972 int flags) {
4973 synchronized (this) {
4974 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
4975 "getRecentTasks()");
4976
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004977 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07004978
Dianne Hackbornd2835932010-12-13 16:28:46 -08004979 ActivityRecord resumed = mMainStack.mResumedActivity;
4980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004981 final int N = mRecentTasks.size();
4982 ArrayList<ActivityManager.RecentTaskInfo> res
4983 = new ArrayList<ActivityManager.RecentTaskInfo>(
4984 maxNum < N ? maxNum : N);
4985 for (int i=0; i<N && maxNum > 0; i++) {
4986 TaskRecord tr = mRecentTasks.get(i);
4987 if (((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
4988 || (tr.intent == null)
4989 || ((tr.intent.getFlags()
4990 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
4991 ActivityManager.RecentTaskInfo rti
4992 = new ActivityManager.RecentTaskInfo();
4993 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08004994 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004995 rti.baseIntent = new Intent(
4996 tr.intent != null ? tr.intent : tr.affinityIntent);
4997 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08004998 rti.description = tr.lastDescription;
4999
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005000 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5001 // Check whether this activity is currently available.
5002 try {
5003 if (rti.origActivity != null) {
5004 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5005 continue;
5006 }
5007 } else if (rti.baseIntent != null) {
5008 if (pm.queryIntentActivities(rti.baseIntent,
5009 null, 0) == null) {
5010 continue;
5011 }
5012 }
5013 } catch (RemoteException e) {
5014 // Will never happen.
5015 }
5016 }
5017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005018 res.add(rti);
5019 maxNum--;
5020 }
5021 }
5022 return res;
5023 }
5024 }
5025
Dianne Hackbornd94df452011-02-16 18:53:31 -08005026 public Bitmap getTaskThumbnail(int id) {
5027 synchronized (this) {
5028 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5029 "getTaskThumbnail()");
5030 ActivityRecord resumed = mMainStack.mResumedActivity;
5031 final int N = mRecentTasks.size();
5032 for (int i=0; i<N; i++) {
5033 TaskRecord tr = mRecentTasks.get(i);
5034 if (tr.taskId == id) {
5035 if (resumed != null && resumed.task == tr) {
5036 return resumed.stack.screenshotActivities(resumed);
5037 } else {
5038 return tr.lastThumbnail;
5039 }
5040 }
5041 }
5042 }
5043 return null;
5044 }
5045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005046 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5047 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005048 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005049 TaskRecord jt = startTask;
5050
5051 // First look backwards
5052 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005053 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005054 if (r.task != jt) {
5055 jt = r.task;
5056 if (affinity.equals(jt.affinity)) {
5057 return j;
5058 }
5059 }
5060 }
5061
5062 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005063 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 jt = startTask;
5065 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005066 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005067 if (r.task != jt) {
5068 if (affinity.equals(jt.affinity)) {
5069 return j;
5070 }
5071 jt = r.task;
5072 }
5073 }
5074
5075 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005076 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005077 return N-1;
5078 }
5079
5080 return -1;
5081 }
5082
5083 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005084 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005085 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005086 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005087 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5088 "moveTaskToFront()");
5089
5090 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005091 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5092 Binder.getCallingUid(), "Task to front")) {
5093 return;
5094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005095 final long origId = Binder.clearCallingIdentity();
5096 try {
5097 int N = mRecentTasks.size();
5098 for (int i=0; i<N; i++) {
5099 TaskRecord tr = mRecentTasks.get(i);
5100 if (tr.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005101 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5102 mMainStack.mUserLeaving = true;
5103 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005104 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5105 // Caller wants the home activity moved with it. To accomplish this,
5106 // we'll just move the home task to the top first.
5107 mMainStack.moveHomeToFrontLocked();
5108 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005109 mMainStack.moveTaskToFrontLocked(tr, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005110 return;
5111 }
5112 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005113 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5114 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005115 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005116 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5117 mMainStack.mUserLeaving = true;
5118 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005119 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5120 // Caller wants the home activity moved with it. To accomplish this,
5121 // we'll just move the home task to the top first.
5122 mMainStack.moveHomeToFrontLocked();
5123 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005124 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 return;
5126 }
5127 }
5128 } finally {
5129 Binder.restoreCallingIdentity(origId);
5130 }
5131 }
5132 }
5133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005134 public void moveTaskToBack(int task) {
5135 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5136 "moveTaskToBack()");
5137
5138 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005139 if (mMainStack.mResumedActivity != null
5140 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005141 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5142 Binder.getCallingUid(), "Task to back")) {
5143 return;
5144 }
5145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005146 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005147 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 Binder.restoreCallingIdentity(origId);
5149 }
5150 }
5151
5152 /**
5153 * Moves an activity, and all of the other activities within the same task, to the bottom
5154 * of the history stack. The activity's order within the task is unchanged.
5155 *
5156 * @param token A reference to the activity we wish to move
5157 * @param nonRoot If false then this only works if the activity is the root
5158 * of a task; if true it will work for any activity in a task.
5159 * @return Returns true if the move completed, false if not.
5160 */
5161 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
5162 synchronized(this) {
5163 final long origId = Binder.clearCallingIdentity();
5164 int taskId = getTaskForActivityLocked(token, !nonRoot);
5165 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005166 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005167 }
5168 Binder.restoreCallingIdentity(origId);
5169 }
5170 return false;
5171 }
5172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 public void moveTaskBackwards(int task) {
5174 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5175 "moveTaskBackwards()");
5176
5177 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005178 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5179 Binder.getCallingUid(), "Task backwards")) {
5180 return;
5181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005182 final long origId = Binder.clearCallingIdentity();
5183 moveTaskBackwardsLocked(task);
5184 Binder.restoreCallingIdentity(origId);
5185 }
5186 }
5187
5188 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005189 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005190 }
5191
5192 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5193 synchronized(this) {
5194 return getTaskForActivityLocked(token, onlyRoot);
5195 }
5196 }
5197
5198 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005199 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 TaskRecord lastTask = null;
5201 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005202 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 if (r == token) {
5204 if (!onlyRoot || lastTask != r.task) {
5205 return r.task.taskId;
5206 }
5207 return -1;
5208 }
5209 lastTask = r.task;
5210 }
5211
5212 return -1;
5213 }
5214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005215 public void finishOtherInstances(IBinder token, ComponentName className) {
5216 synchronized(this) {
5217 final long origId = Binder.clearCallingIdentity();
5218
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005219 int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 TaskRecord lastTask = null;
5221 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005222 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 if (r.realActivity.equals(className)
5224 && r != token && lastTask != r.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005225 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005226 null, "others")) {
5227 i--;
5228 N--;
5229 }
5230 }
5231 lastTask = r.task;
5232 }
5233
5234 Binder.restoreCallingIdentity(origId);
5235 }
5236 }
5237
5238 // =========================================================
5239 // THUMBNAILS
5240 // =========================================================
5241
5242 public void reportThumbnail(IBinder token,
5243 Bitmap thumbnail, CharSequence description) {
5244 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5245 final long origId = Binder.clearCallingIdentity();
5246 sendPendingThumbnail(null, token, thumbnail, description, true);
5247 Binder.restoreCallingIdentity(origId);
5248 }
5249
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005250 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005251 Bitmap thumbnail, CharSequence description, boolean always) {
5252 TaskRecord task = null;
5253 ArrayList receivers = null;
5254
5255 //System.out.println("Send pending thumbnail: " + r);
5256
5257 synchronized(this) {
5258 if (r == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005259 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 if (index < 0) {
5261 return;
5262 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005263 r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005264 }
5265 if (thumbnail == null) {
5266 thumbnail = r.thumbnail;
5267 description = r.description;
5268 }
5269 if (thumbnail == null && !always) {
5270 // If there is no thumbnail, and this entry is not actually
5271 // going away, then abort for now and pick up the next
5272 // thumbnail we get.
5273 return;
5274 }
5275 task = r.task;
5276
5277 int N = mPendingThumbnails.size();
5278 int i=0;
5279 while (i<N) {
5280 PendingThumbnailsRecord pr =
5281 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5282 //System.out.println("Looking in " + pr.pendingRecords);
5283 if (pr.pendingRecords.remove(r)) {
5284 if (receivers == null) {
5285 receivers = new ArrayList();
5286 }
5287 receivers.add(pr);
5288 if (pr.pendingRecords.size() == 0) {
5289 pr.finished = true;
5290 mPendingThumbnails.remove(i);
5291 N--;
5292 continue;
5293 }
5294 }
5295 i++;
5296 }
5297 }
5298
5299 if (receivers != null) {
5300 final int N = receivers.size();
5301 for (int i=0; i<N; i++) {
5302 try {
5303 PendingThumbnailsRecord pr =
5304 (PendingThumbnailsRecord)receivers.get(i);
5305 pr.receiver.newThumbnail(
5306 task != null ? task.taskId : -1, thumbnail, description);
5307 if (pr.finished) {
5308 pr.receiver.finished();
5309 }
5310 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005311 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 }
5313 }
5314 }
5315 }
5316
5317 // =========================================================
5318 // CONTENT PROVIDERS
5319 // =========================================================
5320
5321 private final List generateApplicationProvidersLocked(ProcessRecord app) {
5322 List providers = null;
5323 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005324 providers = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005325 queryContentProviders(app.processName, app.info.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005326 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 } catch (RemoteException ex) {
5328 }
5329 if (providers != null) {
5330 final int N = providers.size();
5331 for (int i=0; i<N; i++) {
5332 ProviderInfo cpi =
5333 (ProviderInfo)providers.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07005334 ContentProviderRecord cpr = mProvidersByClass.get(cpi.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005335 if (cpr == null) {
5336 cpr = new ContentProviderRecord(cpi, app.info);
5337 mProvidersByClass.put(cpi.name, cpr);
5338 }
5339 app.pubProviders.put(cpi.name, cpr);
5340 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005341 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005342 }
5343 }
5344 return providers;
5345 }
5346
5347 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005348 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005349 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
5350 final int callingUid = (r != null) ? r.info.uid : Binder.getCallingUid();
5351 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005352 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005353 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354 return null;
5355 }
5356 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005357 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005358 == PackageManager.PERMISSION_GRANTED) {
5359 return null;
5360 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005361
5362 PathPermission[] pps = cpi.pathPermissions;
5363 if (pps != null) {
5364 int i = pps.length;
5365 while (i > 0) {
5366 i--;
5367 PathPermission pp = pps[i];
5368 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005369 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005370 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005371 return null;
5372 }
5373 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005374 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005375 == PackageManager.PERMISSION_GRANTED) {
5376 return null;
5377 }
5378 }
5379 }
5380
Dianne Hackbornb424b632010-08-18 15:59:05 -07005381 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5382 if (perms != null) {
5383 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5384 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5385 return null;
5386 }
5387 }
5388 }
5389
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005390 String msg;
5391 if (!cpi.exported) {
5392 msg = "Permission Denial: opening provider " + cpi.name
5393 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5394 + ", uid=" + callingUid + ") that is not exported from uid "
5395 + cpi.applicationInfo.uid;
5396 } else {
5397 msg = "Permission Denial: opening provider " + cpi.name
5398 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5399 + ", uid=" + callingUid + ") requires "
5400 + cpi.readPermission + " or " + cpi.writePermission;
5401 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005402 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005403 return msg;
5404 }
5405
5406 private final ContentProviderHolder getContentProviderImpl(
5407 IApplicationThread caller, String name) {
5408 ContentProviderRecord cpr;
5409 ProviderInfo cpi = null;
5410
5411 synchronized(this) {
5412 ProcessRecord r = null;
5413 if (caller != null) {
5414 r = getRecordForAppLocked(caller);
5415 if (r == null) {
5416 throw new SecurityException(
5417 "Unable to find app for caller " + caller
5418 + " (pid=" + Binder.getCallingPid()
5419 + ") when getting content provider " + name);
5420 }
5421 }
5422
5423 // First check if this content provider has been published...
Dianne Hackborn860755f2010-06-03 18:47:52 -07005424 cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005425 if (cpr != null) {
5426 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005427 String msg;
5428 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5429 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 }
5431
5432 if (r != null && cpr.canRunHere(r)) {
5433 // This provider has been published or is in the process
5434 // of being published... but it is also allowed to run
5435 // in the caller's process, so don't make a connection
5436 // and just let the caller instantiate its own instance.
5437 if (cpr.provider != null) {
5438 // don't give caller the provider object, it needs
5439 // to make its own.
5440 cpr = new ContentProviderRecord(cpr);
5441 }
5442 return cpr;
5443 }
5444
5445 final long origId = Binder.clearCallingIdentity();
5446
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005447 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 // return it right away.
5449 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005450 if (DEBUG_PROVIDER) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005451 "Adding provider requested by "
5452 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005453 + cpr.info.processName);
5454 Integer cnt = r.conProviders.get(cpr);
5455 if (cnt == null) {
5456 r.conProviders.put(cpr, new Integer(1));
5457 } else {
5458 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460 cpr.clients.add(r);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005461 if (cpr.app != null && r.setAdj <= PERCEPTIBLE_APP_ADJ) {
5462 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005463 // make sure to count it as being accessed and thus
5464 // back up on the LRU list. This is good because
5465 // content providers are often expensive to start.
5466 updateLruProcessLocked(cpr.app, false, true);
5467 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07005468 } else {
5469 cpr.externals++;
5470 }
5471
5472 if (cpr.app != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005473 updateOomAdjLocked(cpr.app);
5474 }
5475
5476 Binder.restoreCallingIdentity(origId);
5477
5478 } else {
5479 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005480 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07005481 resolveContentProvider(name,
5482 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 } catch (RemoteException ex) {
5484 }
5485 if (cpi == null) {
5486 return null;
5487 }
5488
Dianne Hackbornb424b632010-08-18 15:59:05 -07005489 String msg;
5490 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5491 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005492 }
5493
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07005494 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005495 && !cpi.processName.equals("system")) {
5496 // If this content provider does not run in the system
5497 // process, and the system is not yet ready to run other
5498 // processes, then fail fast instead of hanging.
5499 throw new IllegalArgumentException(
5500 "Attempt to launch content provider before system ready");
5501 }
5502
Dianne Hackborn860755f2010-06-03 18:47:52 -07005503 cpr = mProvidersByClass.get(cpi.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 final boolean firstClass = cpr == null;
5505 if (firstClass) {
5506 try {
5507 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005508 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 getApplicationInfo(
5510 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005511 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005513 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 + cpi.name);
5515 return null;
5516 }
5517 cpr = new ContentProviderRecord(cpi, ai);
5518 } catch (RemoteException ex) {
5519 // pm is in same process, this will never happen.
5520 }
5521 }
5522
5523 if (r != null && cpr.canRunHere(r)) {
5524 // If this is a multiprocess provider, then just return its
5525 // info and allow the caller to instantiate it. Only do
5526 // this if the provider is the same user as the caller's
5527 // process, or can run as root (so can be in any process).
5528 return cpr;
5529 }
5530
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005531 if (DEBUG_PROVIDER) {
5532 RuntimeException e = new RuntimeException("here");
Joe Onorato8a9b2202010-02-26 18:56:32 -08005533 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.info.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005534 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 }
5536
5537 // This is single process, and our app is now connecting to it.
5538 // See if we are already in the process of launching this
5539 // provider.
5540 final int N = mLaunchingProviders.size();
5541 int i;
5542 for (i=0; i<N; i++) {
5543 if (mLaunchingProviders.get(i) == cpr) {
5544 break;
5545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 }
5547
5548 // If the provider is not already being launched, then get it
5549 // started.
5550 if (i >= N) {
5551 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08005552
5553 try {
5554 // Content provider is now in use, its package can't be stopped.
5555 try {
5556 AppGlobals.getPackageManager().setPackageStoppedState(
5557 cpr.appInfo.packageName, false);
5558 } catch (RemoteException e) {
5559 }
5560
5561 ProcessRecord proc = startProcessLocked(cpi.processName,
5562 cpr.appInfo, false, 0, "content provider",
5563 new ComponentName(cpi.applicationInfo.packageName,
5564 cpi.name), false);
5565 if (proc == null) {
5566 Slog.w(TAG, "Unable to launch app "
5567 + cpi.applicationInfo.packageName + "/"
5568 + cpi.applicationInfo.uid + " for provider "
5569 + name + ": process is bad");
5570 return null;
5571 }
5572 cpr.launchingApp = proc;
5573 mLaunchingProviders.add(cpr);
5574 } finally {
5575 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 }
5578
5579 // Make sure the provider is published (the same provider class
5580 // may be published under multiple names).
5581 if (firstClass) {
5582 mProvidersByClass.put(cpi.name, cpr);
5583 }
5584 mProvidersByName.put(name, cpr);
5585
5586 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005587 if (DEBUG_PROVIDER) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005588 "Adding provider requested by "
5589 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005590 + cpr.info.processName);
5591 Integer cnt = r.conProviders.get(cpr);
5592 if (cnt == null) {
5593 r.conProviders.put(cpr, new Integer(1));
5594 } else {
5595 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597 cpr.clients.add(r);
5598 } else {
5599 cpr.externals++;
5600 }
5601 }
5602 }
5603
5604 // Wait for the provider to be published...
5605 synchronized (cpr) {
5606 while (cpr.provider == null) {
5607 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005608 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 + cpi.applicationInfo.packageName + "/"
5610 + cpi.applicationInfo.uid + " for provider "
5611 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08005612 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 cpi.applicationInfo.packageName,
5614 cpi.applicationInfo.uid, name);
5615 return null;
5616 }
5617 try {
5618 cpr.wait();
5619 } catch (InterruptedException ex) {
5620 }
5621 }
5622 }
5623 return cpr;
5624 }
5625
5626 public final ContentProviderHolder getContentProvider(
5627 IApplicationThread caller, String name) {
5628 if (caller == null) {
5629 String msg = "null IApplicationThread when getting content provider "
5630 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005631 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 throw new SecurityException(msg);
5633 }
5634
5635 return getContentProviderImpl(caller, name);
5636 }
5637
5638 private ContentProviderHolder getContentProviderExternal(String name) {
5639 return getContentProviderImpl(null, name);
5640 }
5641
5642 /**
5643 * Drop a content provider from a ProcessRecord's bookkeeping
5644 * @param cpr
5645 */
5646 public void removeContentProvider(IApplicationThread caller, String name) {
5647 synchronized (this) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005648 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005650 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08005651 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005652 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 return;
5654 }
5655 final ProcessRecord r = getRecordForAppLocked(caller);
5656 if (r == null) {
5657 throw new SecurityException(
5658 "Unable to find app for caller " + caller +
5659 " when removing content provider " + name);
5660 }
5661 //update content provider record entry info
Dianne Hackborn860755f2010-06-03 18:47:52 -07005662 ContentProviderRecord localCpr = mProvidersByClass.get(cpr.info.name);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005663 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005664 + r.info.processName + " from process "
5665 + localCpr.appInfo.processName);
5666 if (localCpr.app == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08005668 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005669 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 return;
5671 } else {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005672 Integer cnt = r.conProviders.get(localCpr);
5673 if (cnt == null || cnt.intValue() <= 1) {
5674 localCpr.clients.remove(r);
5675 r.conProviders.remove(localCpr);
5676 } else {
5677 r.conProviders.put(localCpr, new Integer(cnt.intValue()-1));
5678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005679 }
5680 updateOomAdjLocked();
5681 }
5682 }
5683
5684 private void removeContentProviderExternal(String name) {
5685 synchronized (this) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005686 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 if(cpr == null) {
5688 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08005689 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005690 return;
5691 }
5692
5693 //update content provider record entry info
Dianne Hackborn860755f2010-06-03 18:47:52 -07005694 ContentProviderRecord localCpr = mProvidersByClass.get(cpr.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 localCpr.externals--;
5696 if (localCpr.externals < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005697 Slog.e(TAG, "Externals < 0 for content provider " + localCpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005698 }
5699 updateOomAdjLocked();
5700 }
5701 }
5702
5703 public final void publishContentProviders(IApplicationThread caller,
5704 List<ContentProviderHolder> providers) {
5705 if (providers == null) {
5706 return;
5707 }
5708
5709 synchronized(this) {
5710 final ProcessRecord r = getRecordForAppLocked(caller);
5711 if (r == null) {
5712 throw new SecurityException(
5713 "Unable to find app for caller " + caller
5714 + " (pid=" + Binder.getCallingPid()
5715 + ") when publishing content providers");
5716 }
5717
5718 final long origId = Binder.clearCallingIdentity();
5719
5720 final int N = providers.size();
5721 for (int i=0; i<N; i++) {
5722 ContentProviderHolder src = providers.get(i);
5723 if (src == null || src.info == null || src.provider == null) {
5724 continue;
5725 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005726 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 if (dst != null) {
5728 mProvidersByClass.put(dst.info.name, dst);
5729 String names[] = dst.info.authority.split(";");
5730 for (int j = 0; j < names.length; j++) {
5731 mProvidersByName.put(names[j], dst);
5732 }
5733
5734 int NL = mLaunchingProviders.size();
5735 int j;
5736 for (j=0; j<NL; j++) {
5737 if (mLaunchingProviders.get(j) == dst) {
5738 mLaunchingProviders.remove(j);
5739 j--;
5740 NL--;
5741 }
5742 }
5743 synchronized (dst) {
5744 dst.provider = src.provider;
5745 dst.app = r;
5746 dst.notifyAll();
5747 }
5748 updateOomAdjLocked(r);
5749 }
5750 }
5751
5752 Binder.restoreCallingIdentity(origId);
5753 }
5754 }
5755
5756 public static final void installSystemProviders() {
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08005757 List providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06005758 synchronized (mSelf) {
5759 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
5760 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08005761 if (providers != null) {
5762 for (int i=providers.size()-1; i>=0; i--) {
5763 ProviderInfo pi = (ProviderInfo)providers.get(i);
5764 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5765 Slog.w(TAG, "Not installing system proc provider " + pi.name
5766 + ": not system .apk");
5767 providers.remove(i);
5768 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005769 }
5770 }
5771 }
Josh Bartel2ecce342010-02-25 10:55:48 -06005772 if (providers != null) {
5773 mSystemThread.installSystemProviders(providers);
5774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775 }
5776
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07005777 /**
5778 * Allows app to retrieve the MIME type of a URI without having permission
5779 * to access its content provider.
5780 *
5781 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
5782 *
5783 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
5784 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
5785 */
5786 public String getProviderMimeType(Uri uri) {
5787 final String name = uri.getAuthority();
5788 final long ident = Binder.clearCallingIdentity();
5789 ContentProviderHolder holder = null;
5790
5791 try {
5792 holder = getContentProviderExternal(name);
5793 if (holder != null) {
5794 return holder.provider.getType(uri);
5795 }
5796 } catch (RemoteException e) {
5797 Log.w(TAG, "Content provider dead retrieving " + uri, e);
5798 return null;
5799 } finally {
5800 if (holder != null) {
5801 removeContentProviderExternal(name);
5802 }
5803 Binder.restoreCallingIdentity(ident);
5804 }
5805
5806 return null;
5807 }
5808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 // =========================================================
5810 // GLOBAL MANAGEMENT
5811 // =========================================================
5812
5813 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
5814 ApplicationInfo info, String customProcess) {
5815 String proc = customProcess != null ? customProcess : info.processName;
5816 BatteryStatsImpl.Uid.Proc ps = null;
5817 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
5818 synchronized (stats) {
5819 ps = stats.getProcessStatsLocked(info.uid, proc);
5820 }
5821 return new ProcessRecord(ps, thread, info, proc);
5822 }
5823
5824 final ProcessRecord addAppLocked(ApplicationInfo info) {
5825 ProcessRecord app = getProcessRecordLocked(info.processName, info.uid);
5826
5827 if (app == null) {
5828 app = newProcessRecordLocked(null, info, null);
5829 mProcessNames.put(info.processName, info.uid, app);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08005830 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 }
5832
Dianne Hackborne7f97212011-02-24 14:40:20 -08005833 // This package really, really can not be stopped.
5834 try {
5835 AppGlobals.getPackageManager().setPackageStoppedState(
5836 info.packageName, false);
5837 } catch (RemoteException e) {
5838 }
5839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
5841 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
5842 app.persistent = true;
5843 app.maxAdj = CORE_SERVER_ADJ;
5844 }
5845 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
5846 mPersistentStartingProcesses.add(app);
5847 startProcessLocked(app, "added application", app.processName);
5848 }
5849
5850 return app;
5851 }
5852
5853 public void unhandledBack() {
5854 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
5855 "unhandledBack()");
5856
5857 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005858 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08005859 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 TAG, "Performing unhandledBack(): stack size = " + count);
5861 if (count > 1) {
5862 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005863 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
5865 Binder.restoreCallingIdentity(origId);
5866 }
5867 }
5868 }
5869
5870 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
5871 String name = uri.getAuthority();
5872 ContentProviderHolder cph = getContentProviderExternal(name);
5873 ParcelFileDescriptor pfd = null;
5874 if (cph != null) {
5875 // We record the binder invoker's uid in thread-local storage before
5876 // going to the content provider to open the file. Later, in the code
5877 // that handles all permissions checks, we look for this uid and use
5878 // that rather than the Activity Manager's own uid. The effect is that
5879 // we do the check against the caller's permissions even though it looks
5880 // to the content provider like the Activity Manager itself is making
5881 // the request.
5882 sCallerIdentity.set(new Identity(
5883 Binder.getCallingPid(), Binder.getCallingUid()));
5884 try {
5885 pfd = cph.provider.openFile(uri, "r");
5886 } catch (FileNotFoundException e) {
5887 // do nothing; pfd will be returned null
5888 } finally {
5889 // Ensure that whatever happens, we clean up the identity state
5890 sCallerIdentity.remove();
5891 }
5892
5893 // We've got the fd now, so we're done with the provider.
5894 removeContentProviderExternal(name);
5895 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005896 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 }
5898 return pfd;
5899 }
5900
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08005901 // Actually is sleeping or shutting down or whatever else in the future
5902 // is an inactive state.
5903 public boolean isSleeping() {
5904 return mSleeping || mShuttingDown;
5905 }
5906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 public void goingToSleep() {
5908 synchronized(this) {
5909 mSleeping = true;
5910 mWindowManager.setEventDispatching(false);
5911
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08005912 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005913
5914 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07005915 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005916 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
5917 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07005918 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005919 }
5920 }
5921
Dianne Hackborn55280a92009-05-07 15:53:46 -07005922 public boolean shutdown(int timeout) {
5923 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
5924 != PackageManager.PERMISSION_GRANTED) {
5925 throw new SecurityException("Requires permission "
5926 + android.Manifest.permission.SHUTDOWN);
5927 }
5928
5929 boolean timedout = false;
5930
5931 synchronized(this) {
5932 mShuttingDown = true;
5933 mWindowManager.setEventDispatching(false);
5934
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005935 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08005936 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07005937 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005938 while (mMainStack.mResumedActivity != null
5939 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07005940 long delay = endTime - System.currentTimeMillis();
5941 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005942 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07005943 timedout = true;
5944 break;
5945 }
5946 try {
5947 this.wait();
5948 } catch (InterruptedException e) {
5949 }
5950 }
5951 }
5952 }
5953
5954 mUsageStatsService.shutdown();
5955 mBatteryStatsService.shutdown();
5956
5957 return timedout;
5958 }
5959
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08005960 public final void activitySlept(IBinder token) {
5961 if (localLOGV) Slog.v(
5962 TAG, "Activity slept: token=" + token);
5963
5964 ActivityRecord r = null;
5965
5966 final long origId = Binder.clearCallingIdentity();
5967
5968 synchronized (this) {
5969 int index = mMainStack.indexOfTokenLocked(token);
5970 if (index >= 0) {
5971 r = (ActivityRecord)mMainStack.mHistory.get(index);
5972 mMainStack.activitySleptLocked(r);
5973 }
5974 }
5975
5976 Binder.restoreCallingIdentity(origId);
5977 }
5978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005979 public void wakingUp() {
5980 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 mWindowManager.setEventDispatching(true);
5982 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08005983 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005984 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 }
5986 }
5987
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005988 public void stopAppSwitches() {
5989 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
5990 != PackageManager.PERMISSION_GRANTED) {
5991 throw new SecurityException("Requires permission "
5992 + android.Manifest.permission.STOP_APP_SWITCHES);
5993 }
5994
5995 synchronized(this) {
5996 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
5997 + APP_SWITCH_DELAY_TIME;
5998 mDidAppSwitch = false;
5999 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6000 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6001 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6002 }
6003 }
6004
6005 public void resumeAppSwitches() {
6006 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6007 != PackageManager.PERMISSION_GRANTED) {
6008 throw new SecurityException("Requires permission "
6009 + android.Manifest.permission.STOP_APP_SWITCHES);
6010 }
6011
6012 synchronized(this) {
6013 // Note that we don't execute any pending app switches... we will
6014 // let those wait until either the timeout, or the next start
6015 // activity request.
6016 mAppSwitchesAllowedTime = 0;
6017 }
6018 }
6019
6020 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6021 String name) {
6022 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6023 return true;
6024 }
6025
6026 final int perm = checkComponentPermission(
6027 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006028 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006029 if (perm == PackageManager.PERMISSION_GRANTED) {
6030 return true;
6031 }
6032
Joe Onorato8a9b2202010-02-26 18:56:32 -08006033 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006034 return false;
6035 }
6036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 public void setDebugApp(String packageName, boolean waitForDebugger,
6038 boolean persistent) {
6039 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6040 "setDebugApp()");
6041
6042 // Note that this is not really thread safe if there are multiple
6043 // callers into it at the same time, but that's not a situation we
6044 // care about.
6045 if (persistent) {
6046 final ContentResolver resolver = mContext.getContentResolver();
6047 Settings.System.putString(
6048 resolver, Settings.System.DEBUG_APP,
6049 packageName);
6050 Settings.System.putInt(
6051 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6052 waitForDebugger ? 1 : 0);
6053 }
6054
6055 synchronized (this) {
6056 if (!persistent) {
6057 mOrigDebugApp = mDebugApp;
6058 mOrigWaitForDebugger = mWaitForDebugger;
6059 }
6060 mDebugApp = packageName;
6061 mWaitForDebugger = waitForDebugger;
6062 mDebugTransient = !persistent;
6063 if (packageName != null) {
6064 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006065 forceStopPackageLocked(packageName, -1, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 Binder.restoreCallingIdentity(origId);
6067 }
6068 }
6069 }
6070
6071 public void setAlwaysFinish(boolean enabled) {
6072 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6073 "setAlwaysFinish()");
6074
6075 Settings.System.putInt(
6076 mContext.getContentResolver(),
6077 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6078
6079 synchronized (this) {
6080 mAlwaysFinishActivities = enabled;
6081 }
6082 }
6083
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006084 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006086 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006088 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 }
6090 }
6091
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006092 public boolean isUserAMonkey() {
6093 // For now the fact that there is a controller implies
6094 // we have a monkey.
6095 synchronized (this) {
6096 return mController != null;
6097 }
6098 }
6099
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006100 public void registerActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06006101 synchronized (this) {
6102 mWatchers.register(watcher);
6103 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006104 }
6105
6106 public void unregisterActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06006107 synchronized (this) {
6108 mWatchers.unregister(watcher);
6109 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006110 }
6111
Daniel Sandler69a48172010-06-23 16:29:36 -04006112 public void setImmersive(IBinder token, boolean immersive) {
6113 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006114 int index = (token != null) ? mMainStack.indexOfTokenLocked(token) : -1;
Daniel Sandler69a48172010-06-23 16:29:36 -04006115 if (index < 0) {
6116 throw new IllegalArgumentException();
6117 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006118 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
Daniel Sandler69a48172010-06-23 16:29:36 -04006119 r.immersive = immersive;
6120 }
6121 }
6122
6123 public boolean isImmersive(IBinder token) {
6124 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006125 int index = (token != null) ? mMainStack.indexOfTokenLocked(token) : -1;
Daniel Sandler69a48172010-06-23 16:29:36 -04006126 if (index < 0) {
6127 throw new IllegalArgumentException();
6128 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006129 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
Daniel Sandler69a48172010-06-23 16:29:36 -04006130 return r.immersive;
6131 }
6132 }
6133
6134 public boolean isTopActivityImmersive() {
6135 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006136 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006137 return (r != null) ? r.immersive : false;
6138 }
6139 }
6140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 public final void enterSafeMode() {
6142 synchronized(this) {
6143 // It only makes sense to do this before the system is ready
6144 // and started launching other packages.
6145 if (!mSystemReady) {
6146 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006147 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 } catch (RemoteException e) {
6149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 }
6151 }
6152 }
6153
Jeff Brownb09abc12011-01-13 21:08:27 -08006154 public final void showSafeModeOverlay() {
6155 View v = LayoutInflater.from(mContext).inflate(
6156 com.android.internal.R.layout.safe_mode, null);
6157 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6158 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6159 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6160 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6161 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6162 lp.format = v.getBackground().getOpacity();
6163 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6164 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6165 ((WindowManager)mContext.getSystemService(
6166 Context.WINDOW_SERVICE)).addView(v, lp);
6167 }
6168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 public void noteWakeupAlarm(IIntentSender sender) {
6170 if (!(sender instanceof PendingIntentRecord)) {
6171 return;
6172 }
6173 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6174 synchronized (stats) {
6175 if (mBatteryStatsService.isOnBattery()) {
6176 mBatteryStatsService.enforceCallingPermission();
6177 PendingIntentRecord rec = (PendingIntentRecord)sender;
6178 int MY_UID = Binder.getCallingUid();
6179 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6180 BatteryStatsImpl.Uid.Pkg pkg =
6181 stats.getPackageStatsLocked(uid, rec.key.packageName);
6182 pkg.incWakeupsLocked();
6183 }
6184 }
6185 }
6186
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006187 public boolean killPids(int[] pids, String pReason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006189 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006191 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 // XXX Note: don't acquire main activity lock here, because the window
6193 // manager calls in with its locks held.
6194
6195 boolean killed = false;
6196 synchronized (mPidsSelfLocked) {
6197 int[] types = new int[pids.length];
6198 int worstType = 0;
6199 for (int i=0; i<pids.length; i++) {
6200 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6201 if (proc != null) {
6202 int type = proc.setAdj;
6203 types[i] = type;
6204 if (type > worstType) {
6205 worstType = type;
6206 }
6207 }
6208 }
6209
6210 // If the worse oom_adj is somewhere in the hidden proc LRU range,
6211 // then constrain it so we will kill all hidden procs.
6212 if (worstType < EMPTY_APP_ADJ && worstType > HIDDEN_APP_MIN_ADJ) {
6213 worstType = HIDDEN_APP_MIN_ADJ;
6214 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006215 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 for (int i=0; i<pids.length; i++) {
6217 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6218 if (proc == null) {
6219 continue;
6220 }
6221 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006222 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006223 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006224 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6225 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006227 proc.killedBackground = true;
6228 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 }
6230 }
6231 }
6232 return killed;
6233 }
6234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 public final void startRunning(String pkg, String cls, String action,
6236 String data) {
6237 synchronized(this) {
6238 if (mStartRunning) {
6239 return;
6240 }
6241 mStartRunning = true;
6242 mTopComponent = pkg != null && cls != null
6243 ? new ComponentName(pkg, cls) : null;
6244 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6245 mTopData = data;
6246 if (!mSystemReady) {
6247 return;
6248 }
6249 }
6250
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006251 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 }
6253
6254 private void retrieveSettings() {
6255 final ContentResolver resolver = mContext.getContentResolver();
6256 String debugApp = Settings.System.getString(
6257 resolver, Settings.System.DEBUG_APP);
6258 boolean waitForDebugger = Settings.System.getInt(
6259 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6260 boolean alwaysFinishActivities = Settings.System.getInt(
6261 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6262
6263 Configuration configuration = new Configuration();
6264 Settings.System.getConfiguration(resolver, configuration);
6265
6266 synchronized (this) {
6267 mDebugApp = mOrigDebugApp = debugApp;
6268 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6269 mAlwaysFinishActivities = alwaysFinishActivities;
6270 // This happens before any activities are started, so we can
6271 // change mConfiguration in-place.
6272 mConfiguration.updateFrom(configuration);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006273 mConfigurationSeq = mConfiguration.seq = 1;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006274 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 }
6276 }
6277
6278 public boolean testIsSystemReady() {
6279 // no need to synchronize(this) just to read & return the value
6280 return mSystemReady;
6281 }
6282
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006283 private static File getCalledPreBootReceiversFile() {
6284 File dataDir = Environment.getDataDirectory();
6285 File systemDir = new File(dataDir, "system");
6286 File fname = new File(systemDir, "called_pre_boots.dat");
6287 return fname;
6288 }
6289
6290 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6291 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6292 File file = getCalledPreBootReceiversFile();
6293 FileInputStream fis = null;
6294 try {
6295 fis = new FileInputStream(file);
6296 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
6297 int vers = dis.readInt();
6298 String codename = dis.readUTF();
6299 if (vers == android.os.Build.VERSION.SDK_INT
6300 && codename.equals(android.os.Build.VERSION.CODENAME)) {
6301 int num = dis.readInt();
6302 while (num > 0) {
6303 num--;
6304 String pkg = dis.readUTF();
6305 String cls = dis.readUTF();
6306 lastDoneReceivers.add(new ComponentName(pkg, cls));
6307 }
6308 }
6309 } catch (FileNotFoundException e) {
6310 } catch (IOException e) {
6311 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6312 } finally {
6313 if (fis != null) {
6314 try {
6315 fis.close();
6316 } catch (IOException e) {
6317 }
6318 }
6319 }
6320 return lastDoneReceivers;
6321 }
6322
6323 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
6324 File file = getCalledPreBootReceiversFile();
6325 FileOutputStream fos = null;
6326 DataOutputStream dos = null;
6327 try {
6328 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
6329 fos = new FileOutputStream(file);
6330 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
6331 dos.writeInt(android.os.Build.VERSION.SDK_INT);
6332 dos.writeUTF(android.os.Build.VERSION.CODENAME);
6333 dos.writeInt(list.size());
6334 for (int i=0; i<list.size(); i++) {
6335 dos.writeUTF(list.get(i).getPackageName());
6336 dos.writeUTF(list.get(i).getClassName());
6337 }
6338 } catch (IOException e) {
6339 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
6340 file.delete();
6341 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006342 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006343 if (dos != null) {
6344 try {
6345 dos.close();
6346 } catch (IOException e) {
6347 // TODO Auto-generated catch block
6348 e.printStackTrace();
6349 }
6350 }
6351 }
6352 }
6353
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006354 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 // In the simulator, startRunning will never have been called, which
6356 // normally sets a few crucial variables. Do it here instead.
6357 if (!Process.supportsProcesses()) {
6358 mStartRunning = true;
6359 mTopAction = Intent.ACTION_MAIN;
6360 }
6361
6362 synchronized(this) {
6363 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006364 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 return;
6366 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006367
6368 // Check to see if there are any update receivers to run.
6369 if (!mDidUpdate) {
6370 if (mWaitingUpdate) {
6371 return;
6372 }
6373 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6374 List<ResolveInfo> ris = null;
6375 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006376 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006377 intent, null, 0);
6378 } catch (RemoteException e) {
6379 }
6380 if (ris != null) {
6381 for (int i=ris.size()-1; i>=0; i--) {
6382 if ((ris.get(i).activityInfo.applicationInfo.flags
6383 &ApplicationInfo.FLAG_SYSTEM) == 0) {
6384 ris.remove(i);
6385 }
6386 }
6387 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006388
6389 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
6390
6391 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006392 for (int i=0; i<ris.size(); i++) {
6393 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006394 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6395 if (lastDoneReceivers.contains(comp)) {
6396 ris.remove(i);
6397 i--;
6398 }
6399 }
6400
6401 for (int i=0; i<ris.size(); i++) {
6402 ActivityInfo ai = ris.get(i).activityInfo;
6403 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6404 doneReceivers.add(comp);
6405 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006406 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08006407 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006408 finisher = new IIntentReceiver.Stub() {
6409 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07006410 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006411 boolean sticky) {
6412 // The raw IIntentReceiver interface is called
6413 // with the AM lock held, so redispatch to
6414 // execute our code without the lock.
6415 mHandler.post(new Runnable() {
6416 public void run() {
6417 synchronized (ActivityManagerService.this) {
6418 mDidUpdate = true;
6419 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006420 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006421 systemReady(goingCallback);
6422 }
6423 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006424 }
6425 };
6426 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006427 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006428 broadcastIntentLocked(null, null, intent, null, finisher,
6429 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackbornd6847842010-01-12 18:14:19 -08006430 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006431 mWaitingUpdate = true;
6432 }
6433 }
6434 }
6435 if (mWaitingUpdate) {
6436 return;
6437 }
6438 mDidUpdate = true;
6439 }
6440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 mSystemReady = true;
6442 if (!mStartRunning) {
6443 return;
6444 }
6445 }
6446
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006447 ArrayList<ProcessRecord> procsToKill = null;
6448 synchronized(mPidsSelfLocked) {
6449 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
6450 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
6451 if (!isAllowedWhileBooting(proc.info)){
6452 if (procsToKill == null) {
6453 procsToKill = new ArrayList<ProcessRecord>();
6454 }
6455 procsToKill.add(proc);
6456 }
6457 }
6458 }
6459
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006460 synchronized(this) {
6461 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006462 for (int i=procsToKill.size()-1; i>=0; i--) {
6463 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006464 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006465 removeProcessLocked(proc, true);
6466 }
6467 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006468
6469 // Now that we have cleaned up any update processes, we
6470 // are ready to start launching real processes and know that
6471 // we won't trample on them any more.
6472 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006473 }
6474
Joe Onorato8a9b2202010-02-26 18:56:32 -08006475 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006476 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 SystemClock.uptimeMillis());
6478
6479 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006480 // Make sure we have no pre-ready processes sitting around.
6481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
6483 ResolveInfo ri = mContext.getPackageManager()
6484 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07006485 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 CharSequence errorMsg = null;
6487 if (ri != null) {
6488 ActivityInfo ai = ri.activityInfo;
6489 ApplicationInfo app = ai.applicationInfo;
6490 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6491 mTopAction = Intent.ACTION_FACTORY_TEST;
6492 mTopData = null;
6493 mTopComponent = new ComponentName(app.packageName,
6494 ai.name);
6495 } else {
6496 errorMsg = mContext.getResources().getText(
6497 com.android.internal.R.string.factorytest_not_system);
6498 }
6499 } else {
6500 errorMsg = mContext.getResources().getText(
6501 com.android.internal.R.string.factorytest_no_action);
6502 }
6503 if (errorMsg != null) {
6504 mTopAction = null;
6505 mTopData = null;
6506 mTopComponent = null;
6507 Message msg = Message.obtain();
6508 msg.what = SHOW_FACTORY_ERROR_MSG;
6509 msg.getData().putCharSequence("msg", errorMsg);
6510 mHandler.sendMessage(msg);
6511 }
6512 }
6513 }
6514
6515 retrieveSettings();
6516
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006517 if (goingCallback != null) goingCallback.run();
6518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 synchronized (this) {
6520 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
6521 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006522 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006523 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 if (apps != null) {
6525 int N = apps.size();
6526 int i;
6527 for (i=0; i<N; i++) {
6528 ApplicationInfo info
6529 = (ApplicationInfo)apps.get(i);
6530 if (info != null &&
6531 !info.packageName.equals("android")) {
6532 addAppLocked(info);
6533 }
6534 }
6535 }
6536 } catch (RemoteException ex) {
6537 // pm is in same process, this will never happen.
6538 }
6539 }
6540
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006541 // Start up initial activity.
6542 mBooting = true;
6543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006545 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 Message msg = Message.obtain();
6547 msg.what = SHOW_UID_ERROR_MSG;
6548 mHandler.sendMessage(msg);
6549 }
6550 } catch (RemoteException e) {
6551 }
6552
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006553 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006554 }
6555 }
6556
Dan Egnorb7f03672009-12-09 16:22:32 -08006557 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006558 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08006560 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08006561 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006562 startAppProblemLocked(app);
6563 app.stopFreezingAllLocked();
6564 return handleAppCrashLocked(app);
6565 }
6566
Dan Egnorb7f03672009-12-09 16:22:32 -08006567 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006568 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006569 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08006570 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08006571 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
6572 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006573 startAppProblemLocked(app);
6574 app.stopFreezingAllLocked();
6575 }
6576
6577 /**
6578 * Generate a process error record, suitable for attachment to a ProcessRecord.
6579 *
6580 * @param app The ProcessRecord in which the error occurred.
6581 * @param condition Crashing, Application Not Responding, etc. Values are defined in
6582 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08006583 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 * @param shortMsg Short message describing the crash.
6585 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08006586 * @param stackTrace Full crash stack trace, may be null.
6587 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 * @return Returns a fully-formed AppErrorStateInfo record.
6589 */
6590 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006591 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08006593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 report.condition = condition;
6595 report.processName = app.processName;
6596 report.pid = app.pid;
6597 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08006598 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006599 report.shortMsg = shortMsg;
6600 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08006601 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602
6603 return report;
6604 }
6605
Dan Egnor42471dd2010-01-07 17:25:22 -08006606 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 synchronized (this) {
6608 app.crashing = false;
6609 app.crashingReport = null;
6610 app.notResponding = false;
6611 app.notRespondingReport = null;
6612 if (app.anrDialog == fromDialog) {
6613 app.anrDialog = null;
6614 }
6615 if (app.waitDialog == fromDialog) {
6616 app.waitDialog = null;
6617 }
6618 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08006619 handleAppCrashLocked(app);
Dianne Hackborn8633e682010-04-22 16:03:41 -07006620 Slog.i(ActivityManagerService.TAG, "Killing "
6621 + app.processName + " (pid=" + app.pid + "): user's request");
6622 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
6623 app.processName, app.setAdj, "user's request after error");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 Process.killProcess(app.pid);
6625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006626 }
6627 }
Dan Egnor42471dd2010-01-07 17:25:22 -08006628
Dan Egnorb7f03672009-12-09 16:22:32 -08006629 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 long now = SystemClock.uptimeMillis();
6631
6632 Long crashTime = mProcessCrashTimes.get(app.info.processName,
6633 app.info.uid);
6634 if (crashTime != null && now < crashTime+MIN_CRASH_INTERVAL) {
6635 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08006636 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006638 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 app.info.processName, app.info.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006640 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6641 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006643 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006645 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 }
6647 }
6648 if (!app.persistent) {
Dianne Hackborn070783f2010-12-29 16:46:28 -08006649 // Don't let services in this process be restarted and potentially
6650 // annoy the user repeatedly. Unless it is persistent, since those
6651 // processes run critical code.
6652 killServicesLocked(app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 // We don't want to start this process again until the user
6654 // explicitly does so... but for persistent process, we really
6655 // need to keep it running. If a persistent process is actually
6656 // repeatedly crashing, then badness for everyone.
Doug Zongker2bec3d42009-12-04 12:52:44 -08006657 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 app.info.processName);
6659 mBadProcesses.put(app.info.processName, app.info.uid, now);
6660 app.bad = true;
6661 mProcessCrashTimes.remove(app.info.processName, app.info.uid);
6662 app.removed = true;
6663 removeProcessLocked(app, false);
6664 return false;
6665 }
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006666 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006667 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006668 if (r.app == app) {
6669 // If the top running activity is from this crashing
6670 // process, then terminate it to avoid getting in a loop.
6671 Slog.w(TAG, " Force finishing activity "
6672 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006673 int index = mMainStack.indexOfTokenLocked(r);
6674 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006675 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08006676 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006677 // stopped, to avoid a situation where one will get
6678 // re-start our crashing activity once it gets resumed again.
6679 index--;
6680 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006681 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006682 if (r.state == ActivityState.RESUMED
6683 || r.state == ActivityState.PAUSING
6684 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08006685 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006686 Slog.w(TAG, " Force finishing activity "
6687 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006688 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006689 Activity.RESULT_CANCELED, null, "crashed");
6690 }
6691 }
6692 }
6693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 }
6695
6696 // Bump up the crash count of any services currently running in the proc.
6697 if (app.services.size() != 0) {
6698 // Any services running in the application need to be placed
6699 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07006700 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07006702 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 sr.crashCount++;
6704 }
6705 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02006706
6707 // If the crashing process is what we consider to be the "home process" and it has been
6708 // replaced by a third-party app, clear the package preferred activities from packages
6709 // with a home activity running in the process to prevent a repeatedly crashing app
6710 // from blocking the user to manually clear the list.
6711 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
6712 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
6713 Iterator it = mHomeProcess.activities.iterator();
6714 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07006715 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02006716 if (r.isHomeActivity) {
6717 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
6718 try {
6719 ActivityThread.getPackageManager()
6720 .clearPackagePreferredActivities(r.packageName);
6721 } catch (RemoteException c) {
6722 // pm is in same process, this will never happen.
6723 }
6724 }
6725 }
6726 }
6727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 mProcessCrashTimes.put(app.info.processName, app.info.uid, now);
6729 return true;
6730 }
6731
6732 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006733 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
6734 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 skipCurrentReceiverLocked(app);
6736 }
6737
6738 void skipCurrentReceiverLocked(ProcessRecord app) {
6739 boolean reschedule = false;
6740 BroadcastRecord r = app.curReceiver;
6741 if (r != null) {
6742 // The current broadcast is waiting for this app's receiver
6743 // to be finished. Looks like that's not going to happen, so
6744 // let the broadcast continue.
Jeff Brown4d94a762010-09-23 11:33:28 -07006745 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
6747 r.resultExtras, r.resultAbort, true);
6748 reschedule = true;
6749 }
6750 r = mPendingBroadcast;
6751 if (r != null && r.curApp == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006752 if (DEBUG_BROADCAST) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006753 "skip & discard pending app " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -07006754 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
6756 r.resultExtras, r.resultAbort, true);
6757 reschedule = true;
6758 }
6759 if (reschedule) {
6760 scheduleBroadcastsLocked();
6761 }
6762 }
6763
Dan Egnor60d87622009-12-16 16:32:58 -08006764 /**
6765 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
6766 * The application process will exit immediately after this call returns.
6767 * @param app object of the crashing app, null for the system server
6768 * @param crashInfo describing the exception
6769 */
6770 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
6771 ProcessRecord r = findAppProcess(app);
6772
6773 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
6774 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08006775 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08006776 crashInfo.exceptionClassName,
6777 crashInfo.exceptionMessage,
6778 crashInfo.throwFileName,
6779 crashInfo.throwLineNumber);
6780
Dan Egnor42471dd2010-01-07 17:25:22 -08006781 addErrorToDropBox("crash", r, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08006782
6783 crashApplication(r, crashInfo);
6784 }
6785
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006786 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006787 IBinder app,
6788 int violationMask,
6789 StrictMode.ViolationInfo info) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006790 ProcessRecord r = findAppProcess(app);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006791
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006792 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08006793 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006794 boolean logIt = true;
6795 synchronized (mAlreadyLoggedViolatedStacks) {
6796 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
6797 logIt = false;
6798 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006799 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006800 // the relative pain numbers, without logging all
6801 // the stack traces repeatedly. We'd want to do
6802 // likewise in the client code, which also does
6803 // dup suppression, before the Binder call.
6804 } else {
6805 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
6806 mAlreadyLoggedViolatedStacks.clear();
6807 }
6808 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
6809 }
6810 }
6811 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006812 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006813 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006814 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006815
6816 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
6817 AppErrorResult result = new AppErrorResult();
6818 synchronized (this) {
6819 final long origId = Binder.clearCallingIdentity();
6820
6821 Message msg = Message.obtain();
6822 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
6823 HashMap<String, Object> data = new HashMap<String, Object>();
6824 data.put("result", result);
6825 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006826 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006827 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006828 msg.obj = data;
6829 mHandler.sendMessage(msg);
6830
6831 Binder.restoreCallingIdentity(origId);
6832 }
6833 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07006834 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006835 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006836 }
6837
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006838 // Depending on the policy in effect, there could be a bunch of
6839 // these in quick succession so we try to batch these together to
6840 // minimize disk writes, number of dropbox entries, and maximize
6841 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006842 private void logStrictModeViolationToDropBox(
6843 ProcessRecord process,
6844 StrictMode.ViolationInfo info) {
6845 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006846 return;
6847 }
6848 final boolean isSystemApp = process == null ||
6849 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
6850 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
6851 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
6852 final DropBoxManager dbox = (DropBoxManager)
6853 mContext.getSystemService(Context.DROPBOX_SERVICE);
6854
6855 // Exit early if the dropbox isn't configured to accept this report type.
6856 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
6857
6858 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006859 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006860 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
6861 synchronized (sb) {
6862 bufferWasEmpty = sb.length() == 0;
6863 appendDropBoxProcessHeaders(process, sb);
6864 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
6865 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006866 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
6867 if (info.violationNumThisLoop != 0) {
6868 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
6869 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07006870 if (info.numAnimationsRunning != 0) {
6871 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
6872 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07006873 if (info.broadcastIntentAction != null) {
6874 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
6875 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08006876 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006877 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006878 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08006879 if (info.numInstances != -1) {
6880 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
6881 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08006882 if (info.tags != null) {
6883 for (String tag : info.tags) {
6884 sb.append("Span-Tag: ").append(tag).append("\n");
6885 }
6886 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006887 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006888 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
6889 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006890 }
6891 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006892
6893 // Only buffer up to ~64k. Various logging bits truncate
6894 // things at 128k.
6895 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006896 }
6897
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006898 // Flush immediately if the buffer's grown too large, or this
6899 // is a non-system app. Non-system apps are isolated with a
6900 // different tag & policy and not batched.
6901 //
6902 // Batching is useful during internal testing with
6903 // StrictMode settings turned up high. Without batching,
6904 // thousands of separate files could be created on boot.
6905 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006906 new Thread("Error dump: " + dropboxTag) {
6907 @Override
6908 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006909 String report;
6910 synchronized (sb) {
6911 report = sb.toString();
6912 sb.delete(0, sb.length());
6913 sb.trimToSize();
6914 }
6915 if (report.length() != 0) {
6916 dbox.addText(dropboxTag, report);
6917 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006918 }
6919 }.start();
6920 return;
6921 }
6922
6923 // System app batching:
6924 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006925 // An existing dropbox-writing thread is outstanding, so
6926 // we don't need to start it up. The existing thread will
6927 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006928 return;
6929 }
6930
6931 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
6932 // (After this point, we shouldn't access AMS internal data structures.)
6933 new Thread("Error dump: " + dropboxTag) {
6934 @Override
6935 public void run() {
6936 // 5 second sleep to let stacks arrive and be batched together
6937 try {
6938 Thread.sleep(5000); // 5 seconds
6939 } catch (InterruptedException e) {}
6940
6941 String errorReport;
6942 synchronized (mStrictModeBuffer) {
6943 errorReport = mStrictModeBuffer.toString();
6944 if (errorReport.length() == 0) {
6945 return;
6946 }
6947 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
6948 mStrictModeBuffer.trimToSize();
6949 }
6950 dbox.addText(dropboxTag, errorReport);
6951 }
6952 }.start();
6953 }
6954
Dan Egnor60d87622009-12-16 16:32:58 -08006955 /**
6956 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
6957 * @param app object of the crashing app, null for the system server
6958 * @param tag reported by the caller
6959 * @param crashInfo describing the context of the error
6960 * @return true if the process should exit immediately (WTF is fatal)
6961 */
6962 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08006963 ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnor60d87622009-12-16 16:32:58 -08006964 ProcessRecord r = findAppProcess(app);
6965
6966 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
6967 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08006968 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08006969 tag, crashInfo.exceptionMessage);
6970
Dan Egnor42471dd2010-01-07 17:25:22 -08006971 addErrorToDropBox("wtf", r, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08006972
Doug Zongker43866e02010-01-07 12:09:54 -08006973 if (Settings.Secure.getInt(mContext.getContentResolver(),
6974 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08006975 crashApplication(r, crashInfo);
6976 return true;
6977 } else {
6978 return false;
6979 }
6980 }
6981
6982 /**
6983 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
6984 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
6985 */
6986 private ProcessRecord findAppProcess(IBinder app) {
6987 if (app == null) {
6988 return null;
6989 }
6990
6991 synchronized (this) {
6992 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
6993 final int NA = apps.size();
6994 for (int ia=0; ia<NA; ia++) {
6995 ProcessRecord p = apps.valueAt(ia);
6996 if (p.thread != null && p.thread.asBinder() == app) {
6997 return p;
6998 }
6999 }
7000 }
7001
Joe Onorato8a9b2202010-02-26 18:56:32 -08007002 Slog.w(TAG, "Can't find mystery application: " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007003 return null;
7004 }
7005 }
7006
7007 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007008 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7009 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007010 */
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007011 private void appendDropBoxProcessHeaders(ProcessRecord process, StringBuilder sb) {
7012 // Note: ProcessRecord 'process' is guarded by the service
7013 // instance. (notably process.pkgList, which could otherwise change
7014 // concurrently during execution of this method)
7015 synchronized (this) {
7016 if (process == null || process.pid == MY_PID) {
7017 sb.append("Process: system_server\n");
7018 } else {
7019 sb.append("Process: ").append(process.processName).append("\n");
7020 }
7021 if (process == null) {
7022 return;
7023 }
Dan Egnora455d192010-03-12 08:52:28 -08007024 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007025 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007026 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7027 for (String pkg : process.pkgList) {
7028 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007029 try {
Dan Egnora455d192010-03-12 08:52:28 -08007030 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7031 if (pi != null) {
7032 sb.append(" v").append(pi.versionCode);
7033 if (pi.versionName != null) {
7034 sb.append(" (").append(pi.versionName).append(")");
7035 }
7036 }
7037 } catch (RemoteException e) {
7038 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007039 }
Dan Egnora455d192010-03-12 08:52:28 -08007040 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007041 }
Dan Egnora455d192010-03-12 08:52:28 -08007042 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007043 }
7044
7045 private static String processClass(ProcessRecord process) {
7046 if (process == null || process.pid == MY_PID) {
7047 return "system_server";
7048 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7049 return "system_app";
7050 } else {
7051 return "data_app";
7052 }
7053 }
7054
7055 /**
7056 * Write a description of an error (crash, WTF, ANR) to the drop box.
7057 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7058 * @param process which caused the error, null means the system server
7059 * @param activity which triggered the error, null if unknown
7060 * @param parent activity related to the error, null if unknown
7061 * @param subject line related to the error, null if absent
7062 * @param report in long form describing the error, null if absent
7063 * @param logFile to include in the report, null if none
7064 * @param crashInfo giving an application stack trace, null if absent
7065 */
7066 public void addErrorToDropBox(String eventType,
7067 ProcessRecord process, ActivityRecord activity, ActivityRecord parent, String subject,
7068 final String report, final File logFile,
7069 final ApplicationErrorReport.CrashInfo crashInfo) {
7070 // NOTE -- this must never acquire the ActivityManagerService lock,
7071 // otherwise the watchdog may be prevented from resetting the system.
7072
7073 final String dropboxTag = processClass(process) + "_" + eventType;
7074 final DropBoxManager dbox = (DropBoxManager)
7075 mContext.getSystemService(Context.DROPBOX_SERVICE);
7076
7077 // Exit early if the dropbox isn't configured to accept this report type.
7078 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7079
7080 final StringBuilder sb = new StringBuilder(1024);
7081 appendDropBoxProcessHeaders(process, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007082 if (activity != null) {
7083 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7084 }
7085 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7086 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7087 }
7088 if (parent != null && parent != activity) {
7089 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7090 }
7091 if (subject != null) {
7092 sb.append("Subject: ").append(subject).append("\n");
7093 }
7094 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007095 if (Debug.isDebuggerConnected()) {
7096 sb.append("Debugger: Connected\n");
7097 }
Dan Egnora455d192010-03-12 08:52:28 -08007098 sb.append("\n");
7099
7100 // Do the rest in a worker thread to avoid blocking the caller on I/O
7101 // (After this point, we shouldn't access AMS internal data structures.)
7102 Thread worker = new Thread("Error dump: " + dropboxTag) {
7103 @Override
7104 public void run() {
7105 if (report != null) {
7106 sb.append(report);
7107 }
7108 if (logFile != null) {
7109 try {
7110 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7111 } catch (IOException e) {
7112 Slog.e(TAG, "Error reading " + logFile, e);
7113 }
7114 }
7115 if (crashInfo != null && crashInfo.stackTrace != null) {
7116 sb.append(crashInfo.stackTrace);
7117 }
7118
7119 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7120 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7121 if (lines > 0) {
7122 sb.append("\n");
7123
7124 // Merge several logcat streams, and take the last N lines
7125 InputStreamReader input = null;
7126 try {
7127 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7128 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7129 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7130
7131 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7132 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7133 input = new InputStreamReader(logcat.getInputStream());
7134
7135 int num;
7136 char[] buf = new char[8192];
7137 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7138 } catch (IOException e) {
7139 Slog.e(TAG, "Error running logcat", e);
7140 } finally {
7141 if (input != null) try { input.close(); } catch (IOException e) {}
7142 }
7143 }
7144
7145 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007146 }
Dan Egnora455d192010-03-12 08:52:28 -08007147 };
7148
7149 if (process == null || process.pid == MY_PID) {
7150 worker.run(); // We may be about to die -- need to run this synchronously
7151 } else {
7152 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007153 }
7154 }
7155
7156 /**
7157 * Bring up the "unexpected error" dialog box for a crashing app.
7158 * Deal with edge cases (intercepts from instrumented applications,
7159 * ActivityController, error intent receivers, that sort of thing).
7160 * @param r the application crashing
7161 * @param crashInfo describing the failure
7162 */
7163 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007164 long timeMillis = System.currentTimeMillis();
7165 String shortMsg = crashInfo.exceptionClassName;
7166 String longMsg = crashInfo.exceptionMessage;
7167 String stackTrace = crashInfo.stackTrace;
7168 if (shortMsg != null && longMsg != null) {
7169 longMsg = shortMsg + ": " + longMsg;
7170 } else if (shortMsg != null) {
7171 longMsg = shortMsg;
7172 }
7173
Dan Egnor60d87622009-12-16 16:32:58 -08007174 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007175 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007176 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 try {
7178 String name = r != null ? r.processName : null;
7179 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007180 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007181 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007182 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007183 + " at watcher's request");
7184 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007185 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007186 }
7187 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007188 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007189 }
7190 }
7191
7192 final long origId = Binder.clearCallingIdentity();
7193
7194 // If this process is running instrumentation, finish it.
7195 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007196 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007198 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7199 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007200 Bundle info = new Bundle();
7201 info.putString("shortMsg", shortMsg);
7202 info.putString("longMsg", longMsg);
7203 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7204 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007205 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007206 }
7207
Dan Egnor60d87622009-12-16 16:32:58 -08007208 // If we can't identify the process or it's already exceeded its crash quota,
7209 // quit right away without showing a crash dialog.
7210 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007212 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007213 }
7214
7215 Message msg = Message.obtain();
7216 msg.what = SHOW_ERROR_MSG;
7217 HashMap data = new HashMap();
7218 data.put("result", result);
7219 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007220 msg.obj = data;
7221 mHandler.sendMessage(msg);
7222
7223 Binder.restoreCallingIdentity(origId);
7224 }
7225
7226 int res = result.get();
7227
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007228 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007229 synchronized (this) {
7230 if (r != null) {
7231 mProcessCrashTimes.put(r.info.processName, r.info.uid,
7232 SystemClock.uptimeMillis());
7233 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007234 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007235 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007236 }
7237 }
7238
7239 if (appErrorIntent != null) {
7240 try {
7241 mContext.startActivity(appErrorIntent);
7242 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007243 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007246 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007247
7248 Intent createAppErrorIntentLocked(ProcessRecord r,
7249 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7250 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007251 if (report == null) {
7252 return null;
7253 }
7254 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7255 result.setComponent(r.errorReportReceiver);
7256 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7257 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7258 return result;
7259 }
7260
Dan Egnorb7f03672009-12-09 16:22:32 -08007261 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7262 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007263 if (r.errorReportReceiver == null) {
7264 return null;
7265 }
7266
7267 if (!r.crashing && !r.notResponding) {
7268 return null;
7269 }
7270
Dan Egnorb7f03672009-12-09 16:22:32 -08007271 ApplicationErrorReport report = new ApplicationErrorReport();
7272 report.packageName = r.info.packageName;
7273 report.installerPackageName = r.errorReportReceiver.getPackageName();
7274 report.processName = r.processName;
7275 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007276 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007277
Dan Egnorb7f03672009-12-09 16:22:32 -08007278 if (r.crashing) {
7279 report.type = ApplicationErrorReport.TYPE_CRASH;
7280 report.crashInfo = crashInfo;
7281 } else if (r.notResponding) {
7282 report.type = ApplicationErrorReport.TYPE_ANR;
7283 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007284
Dan Egnorb7f03672009-12-09 16:22:32 -08007285 report.anrInfo.activity = r.notRespondingReport.tag;
7286 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7287 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007288 }
7289
Dan Egnorb7f03672009-12-09 16:22:32 -08007290 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007291 }
7292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007293 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
7294 // assume our apps are happy - lazy create the list
7295 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7296
7297 synchronized (this) {
7298
7299 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007300 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7301 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007302 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7303 // This one's in trouble, so we'll generate a report for it
7304 // crashes are higher priority (in case there's a crash *and* an anr)
7305 ActivityManager.ProcessErrorStateInfo report = null;
7306 if (app.crashing) {
7307 report = app.crashingReport;
7308 } else if (app.notResponding) {
7309 report = app.notRespondingReport;
7310 }
7311
7312 if (report != null) {
7313 if (errList == null) {
7314 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
7315 }
7316 errList.add(report);
7317 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007318 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007319 " crashing = " + app.crashing +
7320 " notResponding = " + app.notResponding);
7321 }
7322 }
7323 }
7324 }
7325
7326 return errList;
7327 }
7328
7329 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
7330 // Lazy instantiation of list
7331 List<ActivityManager.RunningAppProcessInfo> runList = null;
7332 synchronized (this) {
7333 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007334 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7335 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007336 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
7337 // Generate process state info for running application
7338 ActivityManager.RunningAppProcessInfo currApp =
7339 new ActivityManager.RunningAppProcessInfo(app.processName,
7340 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07007341 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007342 if (mHeavyWeightProcess == app) {
Dianne Hackborn482566e2010-09-03 12:51:28 -07007343 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007344 }
Dianne Hackborn42499172010-10-15 18:45:07 -07007345 if (app.persistent) {
7346 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
7347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007348 int adj = app.curAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007349 if (adj >= EMPTY_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007350 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY;
7351 } else if (adj >= HIDDEN_APP_MIN_ADJ) {
7352 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
The Android Open Source Project4df24232009-03-05 14:34:35 -08007353 currApp.lru = adj - HIDDEN_APP_MIN_ADJ + 1;
7354 } else if (adj >= HOME_APP_ADJ) {
7355 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
7356 currApp.lru = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007357 } else if (adj >= SECONDARY_SERVER_ADJ) {
7358 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07007359 } else if (adj >= HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackborn5383f502010-10-22 12:59:20 -07007360 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07007361 } else if (adj >= PERCEPTIBLE_APP_ADJ) {
7362 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007363 } else if (adj >= VISIBLE_APP_ADJ) {
7364 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
7365 } else {
7366 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
7367 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007368 currApp.importanceReasonCode = app.adjTypeCode;
7369 if (app.adjSource instanceof ProcessRecord) {
7370 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007371 } else if (app.adjSource instanceof ActivityRecord) {
7372 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007373 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
7374 }
7375 if (app.adjTarget instanceof ComponentName) {
7376 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
7377 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007378 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007379 // + " lru=" + currApp.lru);
7380 if (runList == null) {
7381 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
7382 }
7383 runList.add(currApp);
7384 }
7385 }
7386 }
7387 return runList;
7388 }
7389
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007390 public List<ApplicationInfo> getRunningExternalApplications() {
7391 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
7392 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
7393 if (runningApps != null && runningApps.size() > 0) {
7394 Set<String> extList = new HashSet<String>();
7395 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
7396 if (app.pkgList != null) {
7397 for (String pkg : app.pkgList) {
7398 extList.add(pkg);
7399 }
7400 }
7401 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007402 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007403 for (String pkg : extList) {
7404 try {
7405 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
7406 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
7407 retList.add(info);
7408 }
7409 } catch (RemoteException e) {
7410 }
7411 }
7412 }
7413 return retList;
7414 }
7415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007416 @Override
7417 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007418 if (checkCallingPermission(android.Manifest.permission.DUMP)
7419 != PackageManager.PERMISSION_GRANTED) {
7420 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7421 + Binder.getCallingPid()
7422 + ", uid=" + Binder.getCallingUid()
7423 + " without permission "
7424 + android.Manifest.permission.DUMP);
7425 return;
7426 }
7427
7428 boolean dumpAll = false;
7429
7430 int opti = 0;
7431 while (opti < args.length) {
7432 String opt = args[opti];
7433 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7434 break;
7435 }
7436 opti++;
7437 if ("-a".equals(opt)) {
7438 dumpAll = true;
7439 } else if ("-h".equals(opt)) {
7440 pw.println("Activity manager dump options:");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007441 pw.println(" [-a] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007442 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07007443 pw.println(" a[ctivities]: activity stack state");
7444 pw.println(" b[roadcasts]: broadcast state");
7445 pw.println(" i[ntents]: pending intent state");
7446 pw.println(" p[rocesses]: process state");
7447 pw.println(" o[om]: out of memory management");
7448 pw.println(" prov[iders]: content provider state");
7449 pw.println(" s[ervices]: service state");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007450 pw.println(" service [name]: service client-side state");
Dianne Hackborn30d71892010-12-11 10:37:55 -08007451 pw.println(" cmd may also be a component name (com.foo/.myApp),");
7452 pw.println(" a partial substring in a component name, or an");
7453 pw.println(" ActivityRecord hex object identifier.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007454 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007455 } else {
7456 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007457 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007458 }
7459
7460 // Is the caller requesting to dump a particular piece of data?
7461 if (opti < args.length) {
7462 String cmd = args[opti];
7463 opti++;
7464 if ("activities".equals(cmd) || "a".equals(cmd)) {
7465 synchronized (this) {
7466 dumpActivitiesLocked(fd, pw, args, opti, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007467 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007468 return;
7469 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
7470 synchronized (this) {
7471 dumpBroadcastsLocked(fd, pw, args, opti, true);
7472 }
7473 return;
7474 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
7475 synchronized (this) {
7476 dumpPendingIntentsLocked(fd, pw, args, opti, true);
7477 }
7478 return;
7479 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
7480 synchronized (this) {
7481 dumpProcessesLocked(fd, pw, args, opti, true);
7482 }
7483 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07007484 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
7485 synchronized (this) {
7486 dumpOomLocked(fd, pw, args, opti, true);
7487 }
7488 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007489 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
7490 synchronized (this) {
7491 dumpProvidersLocked(fd, pw, args, opti, true);
7492 }
7493 return;
7494 } else if ("service".equals(cmd)) {
Joe Onoratoeb95b082010-10-21 14:54:19 -04007495 dumpService(fd, pw, args, opti);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007496 return;
7497 } else if ("services".equals(cmd) || "s".equals(cmd)) {
7498 synchronized (this) {
7499 dumpServicesLocked(fd, pw, args, opti, true);
7500 }
7501 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07007502 } else {
7503 // Dumping a single activity?
7504 if (dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
7505 return;
7506 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08007507 pw.println("Bad activity command, or no activities match: " + cmd);
7508 pw.println("Use -h for help.");
7509 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007510 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007511 }
7512
7513 // No piece of data specified, dump everything.
7514 synchronized (this) {
7515 boolean needSep;
7516 if (dumpAll) {
7517 pw.println("Providers in Current Activity Manager State:");
7518 }
7519 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll);
7520 if (needSep) {
7521 pw.println(" ");
7522 }
7523 if (dumpAll) {
7524 pw.println("-------------------------------------------------------------------------------");
7525 pw.println("Broadcasts in Current Activity Manager State:");
7526 }
7527 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll);
7528 if (needSep) {
7529 pw.println(" ");
7530 }
7531 if (dumpAll) {
7532 pw.println("-------------------------------------------------------------------------------");
7533 pw.println("Services in Current Activity Manager State:");
7534 }
7535 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll);
7536 if (needSep) {
7537 pw.println(" ");
7538 }
7539 if (dumpAll) {
7540 pw.println("-------------------------------------------------------------------------------");
7541 pw.println("PendingIntents in Current Activity Manager State:");
7542 }
7543 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll);
7544 if (needSep) {
7545 pw.println(" ");
7546 }
7547 if (dumpAll) {
7548 pw.println("-------------------------------------------------------------------------------");
7549 pw.println("Activities in Current Activity Manager State:");
7550 }
7551 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, !dumpAll);
7552 if (needSep) {
7553 pw.println(" ");
7554 }
7555 if (dumpAll) {
7556 pw.println("-------------------------------------------------------------------------------");
7557 pw.println("Processes in Current Activity Manager State:");
7558 }
7559 dumpProcessesLocked(fd, pw, args, opti, dumpAll);
7560 }
7561 }
7562
7563 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7564 int opti, boolean dumpAll, boolean needHeader) {
7565 if (needHeader) {
7566 pw.println(" Activity stack:");
7567 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007568 dumpHistoryList(pw, mMainStack.mHistory, " ", "Hist", true);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007569 pw.println(" ");
7570 pw.println(" Running activities (most recent first):");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007571 dumpHistoryList(pw, mMainStack.mLRUActivities, " ", "Run", false);
7572 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007574 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007575 dumpHistoryList(pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007576 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007577 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007578 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007579 pw.println(" Activities waiting to stop:");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007580 dumpHistoryList(pw, mMainStack.mStoppingActivities, " ", "Stop", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007581 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007582 if (mMainStack.mGoingToSleepActivities.size() > 0) {
7583 pw.println(" ");
7584 pw.println(" Activities waiting to sleep:");
7585 dumpHistoryList(pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false);
7586 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007587 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007588 pw.println(" ");
7589 pw.println(" Activities waiting to finish:");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007590 dumpHistoryList(pw, mMainStack.mFinishingActivities, " ", "Fin", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007593 pw.println(" ");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007594 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
7595 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007596 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007597 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007598 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007600 if (dumpAll && mRecentTasks.size() > 0) {
7601 pw.println(" ");
7602 pw.println("Recent tasks in Current Activity Manager State:");
7603
7604 final int N = mRecentTasks.size();
7605 for (int i=0; i<N; i++) {
7606 TaskRecord tr = mRecentTasks.get(i);
7607 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
7608 pw.println(tr);
7609 mRecentTasks.get(i).dump(pw, " ");
7610 }
7611 }
7612
7613 pw.println(" ");
7614 pw.println(" mCurTask: " + mCurTask);
7615
7616 return true;
7617 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07007618
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007619 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7620 int opti, boolean dumpAll) {
7621 boolean needSep = false;
7622 int numPers = 0;
7623
7624 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007625 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
7626 final int NA = procs.size();
7627 for (int ia=0; ia<NA; ia++) {
7628 if (!needSep) {
7629 pw.println(" All known processes:");
7630 needSep = true;
7631 }
7632 ProcessRecord r = procs.valueAt(ia);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007633 pw.print(r.persistent ? " *PERS*" : " *APP*");
7634 pw.print(" UID "); pw.print(procs.keyAt(ia));
7635 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 r.dump(pw, " ");
7637 if (r.persistent) {
7638 numPers++;
7639 }
7640 }
7641 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007642 }
7643
7644 if (mLruProcesses.size() > 0) {
7645 if (needSep) pw.println(" ");
7646 needSep = true;
7647 pw.println(" Running processes (most recent first):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07007648 dumpProcessOomList(pw, this, mLruProcesses, " ",
7649 "Proc", "PERS", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007650 needSep = true;
7651 }
7652
7653 synchronized (mPidsSelfLocked) {
7654 if (mPidsSelfLocked.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007655 if (needSep) pw.println(" ");
7656 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007657 pw.println(" PID mappings:");
7658 for (int i=0; i<mPidsSelfLocked.size(); i++) {
7659 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
7660 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007661 }
7662 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007663 }
7664
7665 if (mForegroundProcesses.size() > 0) {
7666 if (needSep) pw.println(" ");
7667 needSep = true;
7668 pw.println(" Foreground Processes:");
7669 for (int i=0; i<mForegroundProcesses.size(); i++) {
7670 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
7671 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007672 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007673 }
7674
7675 if (mPersistentStartingProcesses.size() > 0) {
7676 if (needSep) pw.println(" ");
7677 needSep = true;
7678 pw.println(" Persisent processes that are starting:");
7679 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007680 "Starting Norm", "Restarting PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007683 if (mStartingProcesses.size() > 0) {
7684 if (needSep) pw.println(" ");
7685 needSep = true;
7686 pw.println(" Processes that are starting:");
7687 dumpProcessList(pw, this, mStartingProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007688 "Starting Norm", "Starting PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007691 if (mRemovedProcesses.size() > 0) {
7692 if (needSep) pw.println(" ");
7693 needSep = true;
7694 pw.println(" Processes that are being removed:");
7695 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007696 "Removed Norm", "Removed PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007697 }
7698
7699 if (mProcessesOnHold.size() > 0) {
7700 if (needSep) pw.println(" ");
7701 needSep = true;
7702 pw.println(" Processes that are on old until the system is ready:");
7703 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007704 "OnHold Norm", "OnHold PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007706
Dianne Hackborn287952c2010-09-22 22:34:31 -07007707 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007708
7709 if (mProcessCrashTimes.getMap().size() > 0) {
7710 if (needSep) pw.println(" ");
7711 needSep = true;
7712 pw.println(" Time since processes crashed:");
7713 long now = SystemClock.uptimeMillis();
7714 for (Map.Entry<String, SparseArray<Long>> procs
7715 : mProcessCrashTimes.getMap().entrySet()) {
7716 SparseArray<Long> uids = procs.getValue();
7717 final int N = uids.size();
7718 for (int i=0; i<N; i++) {
7719 pw.print(" Process "); pw.print(procs.getKey());
7720 pw.print(" uid "); pw.print(uids.keyAt(i));
7721 pw.print(": last crashed ");
7722 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07007723 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07007724 }
7725 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007727
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007728 if (mBadProcesses.getMap().size() > 0) {
7729 if (needSep) pw.println(" ");
7730 needSep = true;
7731 pw.println(" Bad processes:");
7732 for (Map.Entry<String, SparseArray<Long>> procs
7733 : mBadProcesses.getMap().entrySet()) {
7734 SparseArray<Long> uids = procs.getValue();
7735 final int N = uids.size();
7736 for (int i=0; i<N; i++) {
7737 pw.print(" Bad process "); pw.print(procs.getKey());
7738 pw.print(" uid "); pw.print(uids.keyAt(i));
7739 pw.print(": crashed at time ");
7740 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 }
7742 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007744
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007745 pw.println(" ");
7746 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackborn860755f2010-06-03 18:47:52 -07007747 if (mHeavyWeightProcess != null) {
7748 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7749 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007750 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007751 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007752 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
7753 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
7754 || mOrigWaitForDebugger) {
7755 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
7756 + " mDebugTransient=" + mDebugTransient
7757 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
7758 }
7759 if (mAlwaysFinishActivities || mController != null) {
7760 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
7761 + " mController=" + mController);
7762 }
7763 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007765 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07007766 + " mProcessesReady=" + mProcessesReady
7767 + " mSystemReady=" + mSystemReady);
7768 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 + " mBooted=" + mBooted
7770 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07007771 pw.print(" mLastPowerCheckRealtime=");
7772 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
7773 pw.println("");
7774 pw.print(" mLastPowerCheckUptime=");
7775 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
7776 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007777 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
7778 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07007779 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007781
7782 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 }
7784
Dianne Hackborn287952c2010-09-22 22:34:31 -07007785 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
7786 int opti, boolean needSep, boolean dumpAll) {
7787 if (mProcessesToGc.size() > 0) {
7788 if (needSep) pw.println(" ");
7789 needSep = true;
7790 pw.println(" Processes that are waiting to GC:");
7791 long now = SystemClock.uptimeMillis();
7792 for (int i=0; i<mProcessesToGc.size(); i++) {
7793 ProcessRecord proc = mProcessesToGc.get(i);
7794 pw.print(" Process "); pw.println(proc);
7795 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
7796 pw.print(", last gced=");
7797 pw.print(now-proc.lastRequestedGc);
7798 pw.print(" ms ago, last lowMem=");
7799 pw.print(now-proc.lastLowMemory);
7800 pw.println(" ms ago");
7801
7802 }
7803 }
7804 return needSep;
7805 }
7806
7807 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7808 int opti, boolean dumpAll) {
7809 boolean needSep = false;
7810
7811 if (mLruProcesses.size() > 0) {
7812 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(mLruProcesses);
7813
7814 Comparator<ProcessRecord> comparator = new Comparator<ProcessRecord>() {
7815 @Override
7816 public int compare(ProcessRecord object1, ProcessRecord object2) {
7817 if (object1.setAdj != object2.setAdj) {
7818 return object1.setAdj > object2.setAdj ? -1 : 1;
7819 }
7820 if (object1.setSchedGroup != object2.setSchedGroup) {
7821 return object1.setSchedGroup > object2.setSchedGroup ? -1 : 1;
7822 }
7823 if (object1.keeping != object2.keeping) {
7824 return object1.keeping ? -1 : 1;
7825 }
7826 if (object1.pid != object2.pid) {
7827 return object1.pid > object2.pid ? -1 : 1;
7828 }
7829 return 0;
7830 }
7831 };
7832
7833 Collections.sort(procs, comparator);
7834
7835 if (needSep) pw.println(" ");
7836 needSep = true;
7837 pw.println(" Process OOM control:");
7838 dumpProcessOomList(pw, this, procs, " ",
7839 "Proc", "PERS", true);
7840 needSep = true;
7841 }
7842
7843 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll);
7844
7845 pw.println(" ");
7846 pw.println(" mHomeProcess: " + mHomeProcess);
7847 if (mHeavyWeightProcess != null) {
7848 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7849 }
7850
7851 return true;
7852 }
7853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 /**
7855 * There are three ways to call this:
7856 * - no service specified: dump all the services
7857 * - a flattened component name that matched an existing service was specified as the
7858 * first arg: dump that one service
7859 * - the first arg isn't the flattened component name of an existing service:
7860 * dump all services whose component contains the first arg as a substring
7861 */
Joe Onoratoeb95b082010-10-21 14:54:19 -04007862 protected void dumpService(FileDescriptor fd, PrintWriter pw, String[] args, int opti) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007863 String[] newArgs;
7864 String componentNameString;
7865 ServiceRecord r;
Kenny Root3619b9ab2010-02-13 10:05:42 -08007866 if (opti >= args.length) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007867 componentNameString = null;
7868 newArgs = EMPTY_STRING_ARRAY;
7869 r = null;
7870 } else {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007871 componentNameString = args[opti];
7872 opti++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007873 ComponentName componentName = ComponentName.unflattenFromString(componentNameString);
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007874 synchronized (this) {
7875 r = componentName != null ? mServices.get(componentName) : null;
7876 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007877 newArgs = new String[args.length - opti];
7878 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 }
7880
7881 if (r != null) {
Joe Onoratoeb95b082010-10-21 14:54:19 -04007882 dumpService(fd, pw, r, newArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 } else {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007884 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
7885 synchronized (this) {
7886 for (ServiceRecord r1 : mServices.values()) {
7887 if (componentNameString == null
7888 || r1.name.flattenToString().contains(componentNameString)) {
7889 services.add(r1);
7890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 }
7892 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007893 for (int i=0; i<services.size(); i++) {
Joe Onoratoeb95b082010-10-21 14:54:19 -04007894 dumpService(fd, pw, services.get(i), newArgs);
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007896 }
7897 }
7898
7899 /**
7900 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
7901 * there is a thread associated with the service.
7902 */
Joe Onoratoeb95b082010-10-21 14:54:19 -04007903 private void dumpService(FileDescriptor fd, PrintWriter pw, ServiceRecord r, String[] args) {
7904 pw.println("------------------------------------------------------------"
7905 + "-------------------");
7906 pw.println("APP SERVICE: " + r.name.flattenToString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007907 if (r.app != null && r.app.thread != null) {
7908 try {
7909 // flush anything that is already in the PrintWriter since the thread is going
7910 // to write to the file descriptor directly
7911 pw.flush();
7912 r.app.thread.dumpService(fd, r, args);
7913 pw.print("\n");
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007914 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007915 } catch (RemoteException e) {
7916 pw.println("got a RemoteException while dumping the service");
7917 }
7918 }
7919 }
7920
Dianne Hackborn625ac272010-09-17 18:29:22 -07007921 /**
7922 * There are three things that cmd can be:
7923 * - a flattened component name that matched an existing activity
7924 * - the cmd arg isn't the flattened component name of an existing activity:
7925 * dump all activity whose component contains the cmd as a substring
7926 * - A hex number of the ActivityRecord object instance.
7927 */
7928 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
7929 int opti, boolean dumpAll) {
7930 String[] newArgs;
7931 ComponentName componentName = ComponentName.unflattenFromString(name);
7932 int objectId = 0;
Dianne Hackborn30d71892010-12-11 10:37:55 -08007933 if (componentName == null) {
7934 // Not a '/' separated full component name; maybe an object ID?
7935 try {
7936 objectId = Integer.parseInt(name, 16);
7937 name = null;
7938 componentName = null;
7939 } catch (RuntimeException e) {
7940 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07007941 }
7942 newArgs = new String[args.length - opti];
7943 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
7944
7945 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
7946 synchronized (this) {
7947 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
7948 if (componentName != null) {
7949 if (r1.intent.getComponent().equals(componentName)) {
7950 activities.add(r1);
7951 }
7952 } else if (name != null) {
7953 if (r1.intent.getComponent().flattenToString().contains(name)) {
7954 activities.add(r1);
7955 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08007956 } else if (System.identityHashCode(r1) == objectId) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07007957 activities.add(r1);
7958 }
7959 }
7960 }
7961
7962 if (activities.size() <= 0) {
7963 return false;
7964 }
7965
Dianne Hackborn30d71892010-12-11 10:37:55 -08007966 TaskRecord lastTask = null;
7967 for (int i=activities.size()-1; i>=0; i--) {
7968 ActivityRecord r = (ActivityRecord)activities.get(i);
7969 if (lastTask != r.task) {
7970 lastTask = r.task;
7971 pw.print("* Task "); pw.print(lastTask.affinity);
7972 pw.print(" id="); pw.println(lastTask.taskId);
7973 if (dumpAll) {
7974 lastTask.dump(pw, " ");
7975 }
7976 }
7977 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07007978 }
7979 return true;
7980 }
7981
7982 /**
7983 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
7984 * there is a thread associated with the activity.
7985 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08007986 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
7987 ActivityRecord r, String[] args, boolean dumpAll) {
7988 synchronized (this) {
7989 pw.print(prefix); pw.print("* Activity ");
7990 pw.print(Integer.toHexString(System.identityHashCode(r)));
7991 pw.print(" "); pw.print(r.shortComponentName); pw.print(" pid=");
7992 if (r.app != null) pw.println(r.app.pid);
7993 else pw.println("(not running)");
7994 if (dumpAll) {
7995 r.dump(pw, prefix + " ");
Dianne Hackborn625ac272010-09-17 18:29:22 -07007996 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07007997 }
7998 if (r.app != null && r.app.thread != null) {
7999 try {
8000 // flush anything that is already in the PrintWriter since the thread is going
8001 // to write to the file descriptor directly
8002 pw.flush();
Dianne Hackborn30d71892010-12-11 10:37:55 -08008003 r.app.thread.dumpActivity(fd, r, prefix + " ", args);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008004 pw.flush();
8005 } catch (RemoteException e) {
8006 pw.println("got a RemoteException while dumping the activity");
8007 }
8008 }
8009 }
8010
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008011 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8012 int opti, boolean dumpAll) {
8013 boolean needSep = false;
8014
8015 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008016 if (mRegisteredReceivers.size() > 0) {
8017 pw.println(" ");
8018 pw.println(" Registered Receivers:");
8019 Iterator it = mRegisteredReceivers.values().iterator();
8020 while (it.hasNext()) {
8021 ReceiverList r = (ReceiverList)it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008022 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 r.dump(pw, " ");
8024 }
8025 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 pw.println(" ");
8028 pw.println("Receiver Resolver Table:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008029 mReceiverResolver.dump(pw, null, " ", null, false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008030 needSep = true;
8031 }
8032
8033 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
8034 || mPendingBroadcast != null) {
8035 if (mParallelBroadcasts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008036 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008037 pw.println(" Active broadcasts:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008039 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
8040 pw.println(" Broadcast #" + i + ":");
8041 mParallelBroadcasts.get(i).dump(pw, " ");
8042 }
8043 if (mOrderedBroadcasts.size() > 0) {
8044 pw.println(" ");
Dianne Hackborn399cccb2010-04-13 22:57:49 -07008045 pw.println(" Active ordered broadcasts:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008046 }
8047 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
8048 pw.println(" Serialized Broadcast #" + i + ":");
8049 mOrderedBroadcasts.get(i).dump(pw, " ");
8050 }
8051 pw.println(" ");
8052 pw.println(" Pending broadcast:");
8053 if (mPendingBroadcast != null) {
8054 mPendingBroadcast.dump(pw, " ");
8055 } else {
8056 pw.println(" (null)");
8057 }
8058 needSep = true;
8059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008061 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008062 pw.println(" ");
Dianne Hackborn12527f92009-11-11 17:39:50 -08008063 pw.println(" Historical broadcasts:");
8064 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
8065 BroadcastRecord r = mBroadcastHistory[i];
8066 if (r == null) {
8067 break;
8068 }
8069 pw.println(" Historical Broadcast #" + i + ":");
8070 r.dump(pw, " ");
8071 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008072 needSep = true;
8073 }
8074
8075 if (mStickyBroadcasts != null) {
Dianne Hackborn12527f92009-11-11 17:39:50 -08008076 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008077 pw.println(" Sticky broadcasts:");
8078 StringBuilder sb = new StringBuilder(128);
8079 for (Map.Entry<String, ArrayList<Intent>> ent
8080 : mStickyBroadcasts.entrySet()) {
8081 pw.print(" * Sticky action "); pw.print(ent.getKey());
8082 pw.println(":");
8083 ArrayList<Intent> intents = ent.getValue();
8084 final int N = intents.size();
8085 for (int i=0; i<N; i++) {
8086 sb.setLength(0);
8087 sb.append(" Intent: ");
8088 intents.get(i).toShortString(sb, true, false);
8089 pw.println(sb.toString());
8090 Bundle bundle = intents.get(i).getExtras();
8091 if (bundle != null) {
8092 pw.print(" ");
8093 pw.println(bundle.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008094 }
8095 }
8096 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008097 needSep = true;
8098 }
8099
8100 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008101 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008102 pw.println(" mBroadcastsScheduled=" + mBroadcastsScheduled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 pw.println(" mHandler:");
8104 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008105 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008106 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008107
8108 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109 }
8110
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008111 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8112 int opti, boolean dumpAll) {
8113 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008114
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008115 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008116 if (mServices.size() > 0) {
8117 pw.println(" Active services:");
8118 Iterator<ServiceRecord> it = mServices.values().iterator();
8119 while (it.hasNext()) {
8120 ServiceRecord r = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008121 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 r.dump(pw, " ");
8123 }
8124 needSep = true;
8125 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008127
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008128 if (mPendingServices.size() > 0) {
8129 if (needSep) pw.println(" ");
8130 pw.println(" Pending services:");
8131 for (int i=0; i<mPendingServices.size(); i++) {
8132 ServiceRecord r = mPendingServices.get(i);
8133 pw.print(" * Pending "); pw.println(r);
8134 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008136 needSep = true;
8137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008139 if (mRestartingServices.size() > 0) {
8140 if (needSep) pw.println(" ");
8141 pw.println(" Restarting services:");
8142 for (int i=0; i<mRestartingServices.size(); i++) {
8143 ServiceRecord r = mRestartingServices.get(i);
8144 pw.print(" * Restarting "); pw.println(r);
8145 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008146 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008147 needSep = true;
8148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008150 if (mStoppingServices.size() > 0) {
8151 if (needSep) pw.println(" ");
8152 pw.println(" Stopping services:");
8153 for (int i=0; i<mStoppingServices.size(); i++) {
8154 ServiceRecord r = mStoppingServices.get(i);
8155 pw.print(" * Stopping "); pw.println(r);
8156 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008158 needSep = true;
8159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008161 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 if (mServiceConnections.size() > 0) {
8163 if (needSep) pw.println(" ");
8164 pw.println(" Connection bindings to services:");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008165 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008166 = mServiceConnections.values().iterator();
8167 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008168 ArrayList<ConnectionRecord> r = it.next();
8169 for (int i=0; i<r.size(); i++) {
8170 pw.print(" * "); pw.println(r.get(i));
8171 r.get(i).dump(pw, " ");
8172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008174 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 }
8176 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008177
8178 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008179 }
8180
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008181 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8182 int opti, boolean dumpAll) {
8183 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008184
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008185 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008186 if (mProvidersByClass.size() > 0) {
8187 if (needSep) pw.println(" ");
8188 pw.println(" Published content providers (by class):");
Dianne Hackborn860755f2010-06-03 18:47:52 -07008189 Iterator<Map.Entry<String, ContentProviderRecord>> it
8190 = mProvidersByClass.entrySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008191 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008192 Map.Entry<String, ContentProviderRecord> e = it.next();
8193 ContentProviderRecord r = e.getValue();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008194 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008195 r.dump(pw, " ");
8196 }
8197 needSep = true;
8198 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008199
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008200 if (mProvidersByName.size() > 0) {
8201 pw.println(" ");
8202 pw.println(" Authority to provider mappings:");
Dianne Hackborn860755f2010-06-03 18:47:52 -07008203 Iterator<Map.Entry<String, ContentProviderRecord>> it
8204 = mProvidersByName.entrySet().iterator();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008205 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008206 Map.Entry<String, ContentProviderRecord> e = it.next();
8207 ContentProviderRecord r = e.getValue();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008208 pw.print(" "); pw.print(e.getKey()); pw.print(": ");
8209 pw.println(r);
8210 }
8211 needSep = true;
8212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008213 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008214
8215 if (mLaunchingProviders.size() > 0) {
8216 if (needSep) pw.println(" ");
8217 pw.println(" Launching content providers:");
8218 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
8219 pw.print(" Launching #"); pw.print(i); pw.print(": ");
8220 pw.println(mLaunchingProviders.get(i));
8221 }
8222 needSep = true;
8223 }
8224
8225 if (mGrantedUriPermissions.size() > 0) {
8226 pw.println();
8227 pw.println("Granted Uri Permissions:");
8228 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
8229 int uid = mGrantedUriPermissions.keyAt(i);
8230 HashMap<Uri, UriPermission> perms
8231 = mGrantedUriPermissions.valueAt(i);
8232 pw.print(" * UID "); pw.print(uid);
8233 pw.println(" holds:");
8234 for (UriPermission perm : perms.values()) {
8235 pw.print(" "); pw.println(perm);
8236 perm.dump(pw, " ");
8237 }
8238 }
8239 needSep = true;
8240 }
8241
8242 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008243 }
8244
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008245 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8246 int opti, boolean dumpAll) {
8247 boolean needSep = false;
8248
8249 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008250 if (this.mIntentSenderRecords.size() > 0) {
8251 Iterator<WeakReference<PendingIntentRecord>> it
8252 = mIntentSenderRecords.values().iterator();
8253 while (it.hasNext()) {
8254 WeakReference<PendingIntentRecord> ref = it.next();
8255 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008256 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008257 if (rec != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008258 pw.print(" * "); pw.println(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259 rec.dump(pw, " ");
8260 } else {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008261 pw.print(" * "); pw.print(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008262 }
8263 }
8264 }
8265 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008266
8267 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008268 }
8269
8270 private static final void dumpHistoryList(PrintWriter pw, List list,
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008271 String prefix, String label, boolean complete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008272 TaskRecord lastTask = null;
8273 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008274 ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008275 final boolean full = complete || !r.inHistory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 if (lastTask != r.task) {
8277 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008278 pw.print(prefix);
8279 pw.print(full ? "* " : " ");
8280 pw.println(lastTask);
8281 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008282 lastTask.dump(pw, prefix + " ");
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008285 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
8286 pw.print(" #"); pw.print(i); pw.print(": ");
8287 pw.println(r);
8288 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008289 r.dump(pw, prefix + " ");
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008291 }
8292 }
8293
Dianne Hackborn09c916b2009-12-08 14:50:51 -08008294 private static String buildOomTag(String prefix, String space, int val, int base) {
8295 if (val == base) {
8296 if (space == null) return prefix;
8297 return prefix + " ";
8298 }
8299 return prefix + "+" + Integer.toString(val-base);
8300 }
8301
8302 private static final int dumpProcessList(PrintWriter pw,
8303 ActivityManagerService service, List list,
Dianne Hackborn287952c2010-09-22 22:34:31 -07008304 String prefix, String normalLabel, String persistentLabel) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008305 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07008306 final int N = list.size()-1;
8307 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008308 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008309 pw.println(String.format("%s%s #%2d: %s",
8310 prefix, (r.persistent ? persistentLabel : normalLabel),
8311 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312 if (r.persistent) {
8313 numPers++;
8314 }
8315 }
8316 return numPers;
8317 }
8318
Dianne Hackborn287952c2010-09-22 22:34:31 -07008319 private static final void dumpProcessOomList(PrintWriter pw,
8320 ActivityManagerService service, List<ProcessRecord> list,
8321 String prefix, String normalLabel, String persistentLabel,
8322 boolean inclDetails) {
8323
8324 final long curRealtime = SystemClock.elapsedRealtime();
8325 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
8326 final long curUptime = SystemClock.uptimeMillis();
8327 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
8328
8329 final int N = list.size()-1;
8330 for (int i=N; i>=0; i--) {
8331 ProcessRecord r = list.get(i);
8332 String oomAdj;
8333 if (r.setAdj >= EMPTY_APP_ADJ) {
8334 oomAdj = buildOomTag("empty", null, r.setAdj, EMPTY_APP_ADJ);
8335 } else if (r.setAdj >= HIDDEN_APP_MIN_ADJ) {
8336 oomAdj = buildOomTag("bak", " ", r.setAdj, HIDDEN_APP_MIN_ADJ);
8337 } else if (r.setAdj >= HOME_APP_ADJ) {
8338 oomAdj = buildOomTag("home ", null, r.setAdj, HOME_APP_ADJ);
8339 } else if (r.setAdj >= SECONDARY_SERVER_ADJ) {
8340 oomAdj = buildOomTag("svc", " ", r.setAdj, SECONDARY_SERVER_ADJ);
8341 } else if (r.setAdj >= BACKUP_APP_ADJ) {
8342 oomAdj = buildOomTag("bckup", null, r.setAdj, BACKUP_APP_ADJ);
8343 } else if (r.setAdj >= HEAVY_WEIGHT_APP_ADJ) {
8344 oomAdj = buildOomTag("hvy ", null, r.setAdj, HEAVY_WEIGHT_APP_ADJ);
8345 } else if (r.setAdj >= PERCEPTIBLE_APP_ADJ) {
8346 oomAdj = buildOomTag("prcp ", null, r.setAdj, PERCEPTIBLE_APP_ADJ);
8347 } else if (r.setAdj >= VISIBLE_APP_ADJ) {
8348 oomAdj = buildOomTag("vis ", null, r.setAdj, VISIBLE_APP_ADJ);
8349 } else if (r.setAdj >= FOREGROUND_APP_ADJ) {
8350 oomAdj = buildOomTag("fore ", null, r.setAdj, FOREGROUND_APP_ADJ);
8351 } else if (r.setAdj >= CORE_SERVER_ADJ) {
8352 oomAdj = buildOomTag("core ", null, r.setAdj, CORE_SERVER_ADJ);
8353 } else if (r.setAdj >= SYSTEM_ADJ) {
8354 oomAdj = buildOomTag("sys ", null, r.setAdj, SYSTEM_ADJ);
8355 } else {
8356 oomAdj = Integer.toString(r.setAdj);
8357 }
8358 String schedGroup;
8359 switch (r.setSchedGroup) {
8360 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
8361 schedGroup = "B";
8362 break;
8363 case Process.THREAD_GROUP_DEFAULT:
8364 schedGroup = "F";
8365 break;
8366 default:
8367 schedGroup = Integer.toString(r.setSchedGroup);
8368 break;
8369 }
8370 pw.println(String.format("%s%s #%2d: adj=%s/%s %s (%s)",
8371 prefix, (r.persistent ? persistentLabel : normalLabel),
8372 N-i, oomAdj, schedGroup, r.toShortString(), r.adjType));
8373 if (r.adjSource != null || r.adjTarget != null) {
8374 pw.print(prefix);
8375 pw.print(" ");
8376 if (r.adjTarget instanceof ComponentName) {
8377 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
8378 } else if (r.adjTarget != null) {
8379 pw.print(r.adjTarget.toString());
8380 } else {
8381 pw.print("{null}");
8382 }
8383 pw.print("<=");
8384 if (r.adjSource instanceof ProcessRecord) {
8385 pw.print("Proc{");
8386 pw.print(((ProcessRecord)r.adjSource).toShortString());
8387 pw.println("}");
8388 } else if (r.adjSource != null) {
8389 pw.println(r.adjSource.toString());
8390 } else {
8391 pw.println("{null}");
8392 }
8393 }
8394 if (inclDetails) {
8395 pw.print(prefix);
8396 pw.print(" ");
8397 pw.print("oom: max="); pw.print(r.maxAdj);
8398 pw.print(" hidden="); pw.print(r.hiddenAdj);
8399 pw.print(" curRaw="); pw.print(r.curRawAdj);
8400 pw.print(" setRaw="); pw.print(r.setRawAdj);
8401 pw.print(" cur="); pw.print(r.curAdj);
8402 pw.print(" set="); pw.println(r.setAdj);
8403 pw.print(prefix);
8404 pw.print(" ");
8405 pw.print("keeping="); pw.print(r.keeping);
8406 pw.print(" hidden="); pw.print(r.hidden);
8407 pw.print(" empty="); pw.println(r.empty);
8408
8409 if (!r.keeping) {
8410 if (r.lastWakeTime != 0) {
8411 long wtime;
8412 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
8413 synchronized (stats) {
8414 wtime = stats.getProcessWakeTime(r.info.uid,
8415 r.pid, curRealtime);
8416 }
8417 long timeUsed = wtime - r.lastWakeTime;
8418 pw.print(prefix);
8419 pw.print(" ");
8420 pw.print("keep awake over ");
8421 TimeUtils.formatDuration(realtimeSince, pw);
8422 pw.print(" used ");
8423 TimeUtils.formatDuration(timeUsed, pw);
8424 pw.print(" (");
8425 pw.print((timeUsed*100)/realtimeSince);
8426 pw.println("%)");
8427 }
8428 if (r.lastCpuTime != 0) {
8429 long timeUsed = r.curCpuTime - r.lastCpuTime;
8430 pw.print(prefix);
8431 pw.print(" ");
8432 pw.print("run cpu over ");
8433 TimeUtils.formatDuration(uptimeSince, pw);
8434 pw.print(" used ");
8435 TimeUtils.formatDuration(timeUsed, pw);
8436 pw.print(" (");
8437 pw.print((timeUsed*100)/uptimeSince);
8438 pw.println("%)");
8439 }
8440 }
8441 }
8442 }
8443 }
8444
Dianne Hackborn472ad872010-04-07 17:31:48 -07008445 static final void dumpApplicationMemoryUsage(FileDescriptor fd,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008446 PrintWriter pw, List list, String prefix, String[] args) {
Dianne Hackborn6447ca32009-04-07 19:50:08 -07008447 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008448 long uptime = SystemClock.uptimeMillis();
8449 long realtime = SystemClock.elapsedRealtime();
8450
8451 if (isCheckinRequest) {
8452 // short checkin version
8453 pw.println(uptime + "," + realtime);
8454 pw.flush();
8455 } else {
8456 pw.println("Applications Memory Usage (kB):");
8457 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
8458 }
8459 for (int i = list.size() - 1 ; i >= 0 ; i--) {
8460 ProcessRecord r = (ProcessRecord)list.get(i);
8461 if (r.thread != null) {
8462 if (!isCheckinRequest) {
8463 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
8464 pw.flush();
8465 }
8466 try {
8467 r.thread.asBinder().dump(fd, args);
8468 } catch (RemoteException e) {
8469 if (!isCheckinRequest) {
8470 pw.println("Got RemoteException!");
8471 pw.flush();
8472 }
8473 }
8474 }
8475 }
8476 }
8477
8478 /**
8479 * Searches array of arguments for the specified string
8480 * @param args array of argument strings
8481 * @param value value to search for
8482 * @return true if the value is contained in the array
8483 */
8484 private static boolean scanArgs(String[] args, String value) {
8485 if (args != null) {
8486 for (String arg : args) {
8487 if (value.equals(arg)) {
8488 return true;
8489 }
8490 }
8491 }
8492 return false;
8493 }
8494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008495 private final void killServicesLocked(ProcessRecord app,
8496 boolean allowRestart) {
8497 // Report disconnected services.
8498 if (false) {
8499 // XXX we are letting the client link to the service for
8500 // death notifications.
8501 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008502 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008504 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008505 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008506 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008507 = r.connections.values().iterator();
8508 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008509 ArrayList<ConnectionRecord> cl = jt.next();
8510 for (int i=0; i<cl.size(); i++) {
8511 ConnectionRecord c = cl.get(i);
8512 if (c.binding.client != app) {
8513 try {
8514 //c.conn.connected(r.className, null);
8515 } catch (Exception e) {
8516 // todo: this should be asynchronous!
8517 Slog.w(TAG, "Exception thrown disconnected servce "
8518 + r.shortName
8519 + " from app " + app.processName, e);
8520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008521 }
8522 }
8523 }
8524 }
8525 }
8526 }
8527 }
8528
8529 // Clean up any connections this application has to other services.
8530 if (app.connections.size() > 0) {
8531 Iterator<ConnectionRecord> it = app.connections.iterator();
8532 while (it.hasNext()) {
8533 ConnectionRecord r = it.next();
8534 removeConnectionLocked(r, app, null);
8535 }
8536 }
8537 app.connections.clear();
8538
8539 if (app.services.size() != 0) {
8540 // Any services running in the application need to be placed
8541 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008542 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008543 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008544 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008545 synchronized (sr.stats.getBatteryStats()) {
8546 sr.stats.stopLaunchedLocked();
8547 }
8548 sr.app = null;
8549 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008550 if (mStoppingServices.remove(sr)) {
8551 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
8552 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008553
8554 boolean hasClients = sr.bindings.size() > 0;
8555 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 Iterator<IntentBindRecord> bindings
8557 = sr.bindings.values().iterator();
8558 while (bindings.hasNext()) {
8559 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -08008560 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008561 + ": shouldUnbind=" + b.hasBound);
8562 b.binder = null;
8563 b.requested = b.received = b.hasBound = false;
8564 }
8565 }
8566
Dianne Hackborn070783f2010-12-29 16:46:28 -08008567 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
8568 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008569 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008570 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -08008571 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008572 sr.crashCount, sr.shortName, app.pid);
8573 bringDownServiceLocked(sr, true);
8574 } else if (!allowRestart) {
8575 bringDownServiceLocked(sr, true);
8576 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008577 boolean canceled = scheduleServiceRestartLocked(sr, true);
8578
8579 // Should the service remain running? Note that in the
8580 // extreme case of so many attempts to deliver a command
8581 // that it failed, that we also will stop it here.
8582 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
8583 if (sr.pendingStarts.size() == 0) {
8584 sr.startRequested = false;
8585 if (!hasClients) {
8586 // Whoops, no reason to restart!
8587 bringDownServiceLocked(sr, true);
8588 }
8589 }
8590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 }
8592 }
8593
8594 if (!allowRestart) {
8595 app.services.clear();
8596 }
8597 }
8598
Dianne Hackbornde42bb62009-08-05 12:26:15 -07008599 // Make sure we have no more records on the stopping list.
8600 int i = mStoppingServices.size();
8601 while (i > 0) {
8602 i--;
8603 ServiceRecord sr = mStoppingServices.get(i);
8604 if (sr.app == app) {
8605 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008606 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -07008607 }
8608 }
8609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008610 app.executingServices.clear();
8611 }
8612
8613 private final void removeDyingProviderLocked(ProcessRecord proc,
8614 ContentProviderRecord cpr) {
8615 synchronized (cpr) {
8616 cpr.launchingApp = null;
8617 cpr.notifyAll();
8618 }
8619
8620 mProvidersByClass.remove(cpr.info.name);
8621 String names[] = cpr.info.authority.split(";");
8622 for (int j = 0; j < names.length; j++) {
8623 mProvidersByName.remove(names[j]);
8624 }
8625
8626 Iterator<ProcessRecord> cit = cpr.clients.iterator();
8627 while (cit.hasNext()) {
8628 ProcessRecord capp = cit.next();
8629 if (!capp.persistent && capp.thread != null
8630 && capp.pid != 0
8631 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07008632 Slog.i(TAG, "Kill " + capp.processName
8633 + " (pid " + capp.pid + "): provider " + cpr.info.name
8634 + " in dying process " + proc.processName);
8635 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
8636 capp.processName, capp.setAdj, "dying provider " + proc.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008637 Process.killProcess(capp.pid);
8638 }
8639 }
8640
8641 mLaunchingProviders.remove(cpr);
8642 }
8643
8644 /**
8645 * Main code for cleaning up a process when it has gone away. This is
8646 * called both as a result of the process dying, or directly when stopping
8647 * a process when running in single process mode.
8648 */
8649 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
8650 boolean restarting, int index) {
8651 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008652 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008653 }
8654
Dianne Hackborn36124872009-10-08 16:22:03 -07008655 mProcessesToGc.remove(app);
8656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008657 // Dismiss any open dialogs.
8658 if (app.crashDialog != null) {
8659 app.crashDialog.dismiss();
8660 app.crashDialog = null;
8661 }
8662 if (app.anrDialog != null) {
8663 app.anrDialog.dismiss();
8664 app.anrDialog = null;
8665 }
8666 if (app.waitDialog != null) {
8667 app.waitDialog.dismiss();
8668 app.waitDialog = null;
8669 }
8670
8671 app.crashing = false;
8672 app.notResponding = false;
8673
8674 app.resetPackageList();
8675 app.thread = null;
8676 app.forcingToForeground = null;
8677 app.foregroundServices = false;
8678
8679 killServicesLocked(app, true);
8680
8681 boolean restart = false;
8682
8683 int NL = mLaunchingProviders.size();
8684
8685 // Remove published content providers.
8686 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008687 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008689 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690 cpr.provider = null;
8691 cpr.app = null;
8692
8693 // See if someone is waiting for this provider... in which
8694 // case we don't remove it, but just let it restart.
8695 int i = 0;
8696 if (!app.bad) {
8697 for (; i<NL; i++) {
8698 if (mLaunchingProviders.get(i) == cpr) {
8699 restart = true;
8700 break;
8701 }
8702 }
8703 } else {
8704 i = NL;
8705 }
8706
8707 if (i >= NL) {
8708 removeDyingProviderLocked(app, cpr);
8709 NL = mLaunchingProviders.size();
8710 }
8711 }
8712 app.pubProviders.clear();
8713 }
8714
Dianne Hackbornf670ef72009-11-16 13:59:16 -08008715 // Take care of any launching providers waiting for this process.
8716 if (checkAppInLaunchingProvidersLocked(app, false)) {
8717 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08008719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 // Unregister from connected content providers.
8721 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07008722 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 while (it.hasNext()) {
8724 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
8725 cpr.clients.remove(app);
8726 }
8727 app.conProviders.clear();
8728 }
8729
Dianne Hackbornde42bb62009-08-05 12:26:15 -07008730 // At this point there may be remaining entries in mLaunchingProviders
8731 // where we were the only one waiting, so they are no longer of use.
8732 // Look for these and clean up if found.
8733 // XXX Commented out for now. Trying to figure out a way to reproduce
8734 // the actual situation to identify what is actually going on.
8735 if (false) {
8736 for (int i=0; i<NL; i++) {
8737 ContentProviderRecord cpr = (ContentProviderRecord)
8738 mLaunchingProviders.get(i);
8739 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
8740 synchronized (cpr) {
8741 cpr.launchingApp = null;
8742 cpr.notifyAll();
8743 }
8744 }
8745 }
8746 }
8747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008748 skipCurrentReceiverLocked(app);
8749
8750 // Unregister any receivers.
8751 if (app.receivers.size() > 0) {
8752 Iterator<ReceiverList> it = app.receivers.iterator();
8753 while (it.hasNext()) {
8754 removeReceiverLocked(it.next());
8755 }
8756 app.receivers.clear();
8757 }
8758
Christopher Tate181fafa2009-05-14 11:12:14 -07008759 // If the app is undergoing backup, tell the backup manager about it
8760 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008761 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -07008762 try {
8763 IBackupManager bm = IBackupManager.Stub.asInterface(
8764 ServiceManager.getService(Context.BACKUP_SERVICE));
8765 bm.agentDisconnected(app.info.packageName);
8766 } catch (RemoteException e) {
8767 // can't happen; backup manager is local
8768 }
8769 }
8770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771 // If the caller is restarting this app, then leave it in its
8772 // current lists and let the caller take care of it.
8773 if (restarting) {
8774 return;
8775 }
8776
8777 if (!app.persistent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008778 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779 "Removing non-persistent process during cleanup: " + app);
8780 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07008781 if (mHeavyWeightProcess == app) {
8782 mHeavyWeightProcess = null;
8783 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
8784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785 } else if (!app.removed) {
8786 // This app is persistent, so we need to keep its record around.
8787 // If it is not already on the pending app list, add it there
8788 // and start a new process for it.
8789 app.thread = null;
8790 app.forcingToForeground = null;
8791 app.foregroundServices = false;
8792 if (mPersistentStartingProcesses.indexOf(app) < 0) {
8793 mPersistentStartingProcesses.add(app);
8794 restart = true;
8795 }
8796 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008797 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
8798 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 mProcessesOnHold.remove(app);
8800
The Android Open Source Project4df24232009-03-05 14:34:35 -08008801 if (app == mHomeProcess) {
8802 mHomeProcess = null;
8803 }
8804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008805 if (restart) {
8806 // We have components that still need to be running in the
8807 // process, so re-launch it.
8808 mProcessNames.put(app.processName, app.info.uid, app);
8809 startProcessLocked(app, "restart", app.processName);
8810 } else if (app.pid > 0 && app.pid != MY_PID) {
8811 // Goodbye!
8812 synchronized (mPidsSelfLocked) {
8813 mPidsSelfLocked.remove(app.pid);
8814 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
8815 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008816 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008817 }
8818 }
8819
Dianne Hackbornf670ef72009-11-16 13:59:16 -08008820 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
8821 // Look through the content providers we are waiting to have launched,
8822 // and if any run in this process then either schedule a restart of
8823 // the process or kill the client waiting for it if this process has
8824 // gone bad.
8825 int NL = mLaunchingProviders.size();
8826 boolean restart = false;
8827 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008828 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08008829 if (cpr.launchingApp == app) {
8830 if (!alwaysBad && !app.bad) {
8831 restart = true;
8832 } else {
8833 removeDyingProviderLocked(app, cpr);
8834 NL = mLaunchingProviders.size();
8835 }
8836 }
8837 }
8838 return restart;
8839 }
8840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008841 // =========================================================
8842 // SERVICES
8843 // =========================================================
8844
8845 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
8846 ActivityManager.RunningServiceInfo info =
8847 new ActivityManager.RunningServiceInfo();
8848 info.service = r.name;
8849 if (r.app != null) {
8850 info.pid = r.app.pid;
8851 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -07008852 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 info.process = r.processName;
8854 info.foreground = r.isForeground;
8855 info.activeSince = r.createTime;
8856 info.started = r.startRequested;
8857 info.clientCount = r.connections.size();
8858 info.crashCount = r.crashCount;
8859 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07008860 if (r.isForeground) {
8861 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
8862 }
8863 if (r.startRequested) {
8864 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
8865 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008866 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -07008867 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
8868 }
8869 if (r.app != null && r.app.persistent) {
8870 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
8871 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008872
8873 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
8874 for (int i=0; i<connl.size(); i++) {
8875 ConnectionRecord conn = connl.get(i);
8876 if (conn.clientLabel != 0) {
8877 info.clientPackage = conn.binding.client.info.packageName;
8878 info.clientLabel = conn.clientLabel;
8879 return info;
8880 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008881 }
8882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 return info;
8884 }
8885
8886 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
8887 int flags) {
8888 synchronized (this) {
8889 ArrayList<ActivityManager.RunningServiceInfo> res
8890 = new ArrayList<ActivityManager.RunningServiceInfo>();
8891
8892 if (mServices.size() > 0) {
8893 Iterator<ServiceRecord> it = mServices.values().iterator();
8894 while (it.hasNext() && res.size() < maxNum) {
8895 res.add(makeRunningServiceInfoLocked(it.next()));
8896 }
8897 }
8898
8899 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
8900 ServiceRecord r = mRestartingServices.get(i);
8901 ActivityManager.RunningServiceInfo info =
8902 makeRunningServiceInfoLocked(r);
8903 info.restarting = r.nextRestartTime;
8904 res.add(info);
8905 }
8906
8907 return res;
8908 }
8909 }
8910
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008911 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
8912 synchronized (this) {
8913 ServiceRecord r = mServices.get(name);
8914 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008915 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
8916 for (int i=0; i<conn.size(); i++) {
8917 if (conn.get(i).clientIntent != null) {
8918 return conn.get(i).clientIntent;
8919 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008920 }
8921 }
8922 }
8923 }
8924 return null;
8925 }
8926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927 private final ServiceRecord findServiceLocked(ComponentName name,
8928 IBinder token) {
8929 ServiceRecord r = mServices.get(name);
8930 return r == token ? r : null;
8931 }
8932
8933 private final class ServiceLookupResult {
8934 final ServiceRecord record;
8935 final String permission;
8936
8937 ServiceLookupResult(ServiceRecord _record, String _permission) {
8938 record = _record;
8939 permission = _permission;
8940 }
8941 };
8942
8943 private ServiceLookupResult findServiceLocked(Intent service,
8944 String resolvedType) {
8945 ServiceRecord r = null;
8946 if (service.getComponent() != null) {
8947 r = mServices.get(service.getComponent());
8948 }
8949 if (r == null) {
8950 Intent.FilterComparison filter = new Intent.FilterComparison(service);
8951 r = mServicesByIntent.get(filter);
8952 }
8953
8954 if (r == null) {
8955 try {
8956 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008957 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008958 service, resolvedType, 0);
8959 ServiceInfo sInfo =
8960 rInfo != null ? rInfo.serviceInfo : null;
8961 if (sInfo == null) {
8962 return null;
8963 }
8964
8965 ComponentName name = new ComponentName(
8966 sInfo.applicationInfo.packageName, sInfo.name);
8967 r = mServices.get(name);
8968 } catch (RemoteException ex) {
8969 // pm is in same process, this will never happen.
8970 }
8971 }
8972 if (r != null) {
8973 int callingPid = Binder.getCallingPid();
8974 int callingUid = Binder.getCallingUid();
8975 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08008976 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008977 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08008978 if (!r.exported) {
8979 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
8980 + " from pid=" + callingPid
8981 + ", uid=" + callingUid
8982 + " that is not exported from uid " + r.appInfo.uid);
8983 return new ServiceLookupResult(null, "not exported from uid "
8984 + r.appInfo.uid);
8985 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008986 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008987 + " from pid=" + callingPid
8988 + ", uid=" + callingUid
8989 + " requires " + r.permission);
8990 return new ServiceLookupResult(null, r.permission);
8991 }
8992 return new ServiceLookupResult(r, null);
8993 }
8994 return null;
8995 }
8996
8997 private class ServiceRestarter implements Runnable {
8998 private ServiceRecord mService;
8999
9000 void setService(ServiceRecord service) {
9001 mService = service;
9002 }
9003
9004 public void run() {
9005 synchronized(ActivityManagerService.this) {
9006 performServiceRestartLocked(mService);
9007 }
9008 }
9009 }
9010
9011 private ServiceLookupResult retrieveServiceLocked(Intent service,
9012 String resolvedType, int callingPid, int callingUid) {
9013 ServiceRecord r = null;
9014 if (service.getComponent() != null) {
9015 r = mServices.get(service.getComponent());
9016 }
9017 Intent.FilterComparison filter = new Intent.FilterComparison(service);
9018 r = mServicesByIntent.get(filter);
9019 if (r == null) {
9020 try {
9021 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009022 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -07009023 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009024 ServiceInfo sInfo =
9025 rInfo != null ? rInfo.serviceInfo : null;
9026 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009027 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 ": not found");
9029 return null;
9030 }
9031
9032 ComponentName name = new ComponentName(
9033 sInfo.applicationInfo.packageName, sInfo.name);
9034 r = mServices.get(name);
9035 if (r == null) {
9036 filter = new Intent.FilterComparison(service.cloneFilter());
9037 ServiceRestarter res = new ServiceRestarter();
9038 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
9039 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
9040 synchronized (stats) {
9041 ss = stats.getServiceStatsLocked(
9042 sInfo.applicationInfo.uid, sInfo.packageName,
9043 sInfo.name);
9044 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -08009045 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009046 res.setService(r);
9047 mServices.put(name, r);
9048 mServicesByIntent.put(filter, r);
9049
9050 // Make sure this component isn't in the pending list.
9051 int N = mPendingServices.size();
9052 for (int i=0; i<N; i++) {
9053 ServiceRecord pr = mPendingServices.get(i);
9054 if (pr.name.equals(name)) {
9055 mPendingServices.remove(i);
9056 i--;
9057 N--;
9058 }
9059 }
9060 }
9061 } catch (RemoteException ex) {
9062 // pm is in same process, this will never happen.
9063 }
9064 }
9065 if (r != null) {
9066 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009067 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009068 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009069 if (!r.exported) {
9070 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
9071 + " from pid=" + callingPid
9072 + ", uid=" + callingUid
9073 + " that is not exported from uid " + r.appInfo.uid);
9074 return new ServiceLookupResult(null, "not exported from uid "
9075 + r.appInfo.uid);
9076 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08009077 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08009078 + " from pid=" + callingPid
9079 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009080 + " requires " + r.permission);
9081 return new ServiceLookupResult(null, r.permission);
9082 }
9083 return new ServiceLookupResult(r, null);
9084 }
9085 return null;
9086 }
9087
Dianne Hackborn287952c2010-09-22 22:34:31 -07009088 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
9089 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
9090 + why + " of " + r + " in app " + r.app);
9091 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
9092 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009093 long now = SystemClock.uptimeMillis();
9094 if (r.executeNesting == 0 && r.app != null) {
9095 if (r.app.executingServices.size() == 0) {
9096 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
9097 msg.obj = r.app;
9098 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
9099 }
9100 r.app.executingServices.add(r);
9101 }
9102 r.executeNesting++;
9103 r.executingStart = now;
9104 }
9105
9106 private final void sendServiceArgsLocked(ServiceRecord r,
9107 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009108 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 if (N == 0) {
9110 return;
9111 }
9112
Dianne Hackborn39792d22010-08-19 18:01:52 -07009113 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009114 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -07009115 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009116 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
9117 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -08009118 if (si.intent == null && N > 1) {
9119 // If somehow we got a dummy null intent in the middle,
9120 // then skip it. DO NOT skip a null intent when it is
9121 // the only one in the list -- this is to support the
9122 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009123 continue;
9124 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07009125 si.deliveredTime = SystemClock.uptimeMillis();
9126 r.deliveredStarts.add(si);
9127 si.deliveryCount++;
Dianne Hackborn3a28f222011-03-01 12:25:54 -08009128 if (si.targetPermissionUid >= 0 && si.intent != null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07009129 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -07009130 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07009131 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009132 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009133 if (!oomAdjusted) {
9134 oomAdjusted = true;
9135 updateOomAdjLocked(r.app);
9136 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009137 int flags = 0;
9138 if (si.deliveryCount > 0) {
9139 flags |= Service.START_FLAG_RETRY;
9140 }
9141 if (si.doneExecutingCount > 0) {
9142 flags |= Service.START_FLAG_REDELIVERY;
9143 }
9144 r.app.thread.scheduleServiceArgs(r, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009145 } catch (RemoteException e) {
9146 // Remote process gone... we'll let the normal cleanup take
9147 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009148 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009149 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009150 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009151 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009152 break;
9153 }
9154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009155 }
9156
9157 private final boolean requestServiceBindingLocked(ServiceRecord r,
9158 IntentBindRecord i, boolean rebind) {
9159 if (r.app == null || r.app.thread == null) {
9160 // If service is not currently running, can't yet bind.
9161 return false;
9162 }
9163 if ((!i.requested || rebind) && i.apps.size() > 0) {
9164 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009165 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009166 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
9167 if (!rebind) {
9168 i.requested = true;
9169 }
9170 i.hasBound = true;
9171 i.doRebind = false;
9172 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009173 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009174 return false;
9175 }
9176 }
9177 return true;
9178 }
9179
9180 private final void requestServiceBindingsLocked(ServiceRecord r) {
9181 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
9182 while (bindings.hasNext()) {
9183 IntentBindRecord i = bindings.next();
9184 if (!requestServiceBindingLocked(r, i, false)) {
9185 break;
9186 }
9187 }
9188 }
9189
9190 private final void realStartServiceLocked(ServiceRecord r,
9191 ProcessRecord app) throws RemoteException {
9192 if (app.thread == null) {
9193 throw new RemoteException();
9194 }
9195
9196 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -07009197 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009198
9199 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009200 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009201 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009202
9203 boolean created = false;
9204 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07009205 mStringBuilder.setLength(0);
9206 r.intent.getIntent().toShortString(mStringBuilder, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -08009207 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009208 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -07009209 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009210 synchronized (r.stats.getBatteryStats()) {
9211 r.stats.startLaunchedLocked();
9212 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07009213 ensurePackageDexOpt(r.serviceInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009214 app.thread.scheduleCreateService(r, r.serviceInfo);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009215 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009216 created = true;
9217 } finally {
9218 if (!created) {
9219 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009220 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009221 }
9222 }
9223
9224 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009225
9226 // If the service is in the started state, and there are no
9227 // pending arguments, then fake up one so its onStartCommand() will
9228 // be called.
9229 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
9230 r.lastStartId++;
9231 if (r.lastStartId < 1) {
9232 r.lastStartId = 1;
9233 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07009234 r.pendingStarts.add(new ServiceRecord.StartItem(r, r.lastStartId, null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009235 }
9236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009237 sendServiceArgsLocked(r, true);
9238 }
9239
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009240 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
9241 boolean allowCancel) {
9242 boolean canceled = false;
9243
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009244 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009245 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -07009246 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009247
Dianne Hackborn070783f2010-12-29 16:46:28 -08009248 if ((r.serviceInfo.applicationInfo.flags
9249 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
9250 minDuration /= 4;
9251 }
9252
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009253 // Any delivered but not yet finished starts should be put back
9254 // on the pending list.
9255 final int N = r.deliveredStarts.size();
9256 if (N > 0) {
9257 for (int i=N-1; i>=0; i--) {
9258 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -07009259 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009260 if (si.intent == null) {
9261 // We'll generate this again if needed.
9262 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
9263 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
9264 r.pendingStarts.add(0, si);
9265 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
9266 dur *= 2;
9267 if (minDuration < dur) minDuration = dur;
9268 if (resetTime < dur) resetTime = dur;
9269 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009270 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009271 + r.name);
9272 canceled = true;
9273 }
9274 }
9275 r.deliveredStarts.clear();
9276 }
9277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009278 r.totalRestartCount++;
9279 if (r.restartDelay == 0) {
9280 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009281 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009282 } else {
9283 // If it has been a "reasonably long time" since the service
9284 // was started, then reset our restart duration back to
9285 // the beginning, so we don't infinitely increase the duration
9286 // on a service that just occasionally gets killed (which is
9287 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009288 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009289 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009290 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009291 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -08009292 if ((r.serviceInfo.applicationInfo.flags
9293 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
9294 // Services in peristent processes will restart much more
9295 // quickly, since they are pretty important. (Think SystemUI).
9296 r.restartDelay += minDuration/2;
9297 } else {
9298 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
9299 if (r.restartDelay < minDuration) {
9300 r.restartDelay = minDuration;
9301 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303 }
9304 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009305
9306 r.nextRestartTime = now + r.restartDelay;
9307
9308 // Make sure that we don't end up restarting a bunch of services
9309 // all at the same time.
9310 boolean repeat;
9311 do {
9312 repeat = false;
9313 for (int i=mRestartingServices.size()-1; i>=0; i--) {
9314 ServiceRecord r2 = mRestartingServices.get(i);
9315 if (r2 != r && r.nextRestartTime
9316 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
9317 && r.nextRestartTime
9318 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
9319 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
9320 r.restartDelay = r.nextRestartTime - now;
9321 repeat = true;
9322 break;
9323 }
9324 }
9325 } while (repeat);
9326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009327 if (!mRestartingServices.contains(r)) {
9328 mRestartingServices.add(r);
9329 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009330
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009331 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009333 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009334 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009335 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -08009336 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -08009338 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009339 r.shortName, r.restartDelay);
9340
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009341 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009342 }
9343
9344 final void performServiceRestartLocked(ServiceRecord r) {
9345 if (!mRestartingServices.contains(r)) {
9346 return;
9347 }
9348 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
9349 }
9350
9351 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
9352 if (r.restartDelay == 0) {
9353 return false;
9354 }
9355 r.resetRestartCounter();
9356 mRestartingServices.remove(r);
9357 mHandler.removeCallbacks(r.restarter);
9358 return true;
9359 }
9360
9361 private final boolean bringUpServiceLocked(ServiceRecord r,
9362 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009363 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009364 //r.dump(" ");
9365
Dianne Hackborn36124872009-10-08 16:22:03 -07009366 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009367 sendServiceArgsLocked(r, false);
9368 return true;
9369 }
9370
9371 if (!whileRestarting && r.restartDelay > 0) {
9372 // If waiting for a restart, then do nothing.
9373 return true;
9374 }
9375
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009376 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009377
Dianne Hackbornde42bb62009-08-05 12:26:15 -07009378 // We are now bringing the service up, so no longer in the
9379 // restarting state.
9380 mRestartingServices.remove(r);
9381
Dianne Hackborne7f97212011-02-24 14:40:20 -08009382 // Service is now being launched, its package can't be stopped.
9383 try {
9384 AppGlobals.getPackageManager().setPackageStoppedState(
9385 r.packageName, false);
9386 } catch (RemoteException e) {
9387 }
9388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009389 final String appName = r.processName;
9390 ProcessRecord app = getProcessRecordLocked(appName, r.appInfo.uid);
9391 if (app != null && app.thread != null) {
9392 try {
9393 realStartServiceLocked(r, app);
9394 return true;
9395 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009396 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009397 }
9398
9399 // If a dead object exception was thrown -- fall through to
9400 // restart the application.
9401 }
9402
Dianne Hackborn36124872009-10-08 16:22:03 -07009403 // Not running -- get it started, and enqueue this service record
9404 // to be executed when the app comes up.
9405 if (startProcessLocked(appName, r.appInfo, true, intentFlags,
9406 "service", r.name, false) == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009407 Slog.w(TAG, "Unable to launch app "
Dianne Hackborn36124872009-10-08 16:22:03 -07009408 + r.appInfo.packageName + "/"
9409 + r.appInfo.uid + " for service "
9410 + r.intent.getIntent() + ": process is bad");
9411 bringDownServiceLocked(r, true);
9412 return false;
9413 }
9414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009415 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009416 mPendingServices.add(r);
9417 }
Dianne Hackborn36124872009-10-08 16:22:03 -07009418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009419 return true;
9420 }
9421
9422 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009423 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009424 //r.dump(" ");
9425
9426 // Does it still need to run?
9427 if (!force && r.startRequested) {
9428 return;
9429 }
9430 if (r.connections.size() > 0) {
9431 if (!force) {
9432 // XXX should probably keep a count of the number of auto-create
9433 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009434 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009435 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009436 ArrayList<ConnectionRecord> cr = it.next();
9437 for (int i=0; i<cr.size(); i++) {
9438 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
9439 return;
9440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009441 }
9442 }
9443 }
9444
9445 // Report to all of the connections that the service is no longer
9446 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009447 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009448 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009449 ArrayList<ConnectionRecord> c = it.next();
9450 for (int i=0; i<c.size(); i++) {
9451 try {
9452 c.get(i).conn.connected(r.name, null);
9453 } catch (Exception e) {
9454 Slog.w(TAG, "Failure disconnecting service " + r.name +
9455 " to connection " + c.get(i).conn.asBinder() +
9456 " (in " + c.get(i).binding.client.processName + ")", e);
9457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009458 }
9459 }
9460 }
9461
9462 // Tell the service that it has been unbound.
9463 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
9464 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
9465 while (it.hasNext()) {
9466 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -08009467 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009468 + ": hasBound=" + ibr.hasBound);
9469 if (r.app != null && r.app.thread != null && ibr.hasBound) {
9470 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009471 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009472 updateOomAdjLocked(r.app);
9473 ibr.hasBound = false;
9474 r.app.thread.scheduleUnbindService(r,
9475 ibr.intent.getIntent());
9476 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009477 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009478 + r.shortName, e);
9479 serviceDoneExecutingLocked(r, true);
9480 }
9481 }
9482 }
9483 }
9484
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009485 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -08009486 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009487 System.identityHashCode(r), r.shortName,
9488 (r.app != null) ? r.app.pid : -1);
9489
9490 mServices.remove(r.name);
9491 mServicesByIntent.remove(r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009492 r.totalRestartCount = 0;
9493 unscheduleServiceRestartLocked(r);
9494
9495 // Also make sure it is not on the pending list.
9496 int N = mPendingServices.size();
9497 for (int i=0; i<N; i++) {
9498 if (mPendingServices.get(i) == r) {
9499 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009500 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009501 i--;
9502 N--;
9503 }
9504 }
9505
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009506 r.cancelNotification();
9507 r.isForeground = false;
9508 r.foregroundId = 0;
9509 r.foregroundNoti = null;
9510
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009511 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -07009512 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009513 r.pendingStarts.clear();
9514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009515 if (r.app != null) {
9516 synchronized (r.stats.getBatteryStats()) {
9517 r.stats.stopLaunchedLocked();
9518 }
9519 r.app.services.remove(r);
9520 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009521 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009522 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009523 mStoppingServices.add(r);
9524 updateOomAdjLocked(r.app);
9525 r.app.thread.scheduleStopService(r);
9526 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009527 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009528 + r.shortName, e);
9529 serviceDoneExecutingLocked(r, true);
9530 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009531 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009532 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009533 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009534 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009535 }
9536 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009537 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009538 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009539 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -08009540
9541 if (r.bindings.size() > 0) {
9542 r.bindings.clear();
9543 }
9544
9545 if (r.restarter instanceof ServiceRestarter) {
9546 ((ServiceRestarter)r.restarter).setService(null);
9547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009548 }
9549
9550 ComponentName startServiceLocked(IApplicationThread caller,
9551 Intent service, String resolvedType,
9552 int callingPid, int callingUid) {
9553 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009554 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009555 + " type=" + resolvedType + " args=" + service.getExtras());
9556
9557 if (caller != null) {
9558 final ProcessRecord callerApp = getRecordForAppLocked(caller);
9559 if (callerApp == null) {
9560 throw new SecurityException(
9561 "Unable to find app for caller " + caller
9562 + " (pid=" + Binder.getCallingPid()
9563 + ") when starting service " + service);
9564 }
9565 }
9566
9567 ServiceLookupResult res =
9568 retrieveServiceLocked(service, resolvedType,
9569 callingPid, callingUid);
9570 if (res == null) {
9571 return null;
9572 }
9573 if (res.record == null) {
9574 return new ComponentName("!", res.permission != null
9575 ? res.permission : "private to package");
9576 }
9577 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -07009578 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
9579 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009580 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009581 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009582 }
9583 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009584 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009585 r.lastStartId++;
9586 if (r.lastStartId < 1) {
9587 r.lastStartId = 1;
9588 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07009589 r.pendingStarts.add(new ServiceRecord.StartItem(r, r.lastStartId,
9590 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009591 r.lastActivity = SystemClock.uptimeMillis();
9592 synchronized (r.stats.getBatteryStats()) {
9593 r.stats.startRunningLocked();
9594 }
9595 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
9596 return new ComponentName("!", "Service process is bad");
9597 }
9598 return r.name;
9599 }
9600 }
9601
9602 public ComponentName startService(IApplicationThread caller, Intent service,
9603 String resolvedType) {
9604 // Refuse possible leaked file descriptors
9605 if (service != null && service.hasFileDescriptors() == true) {
9606 throw new IllegalArgumentException("File descriptors passed in Intent");
9607 }
9608
9609 synchronized(this) {
9610 final int callingPid = Binder.getCallingPid();
9611 final int callingUid = Binder.getCallingUid();
9612 final long origId = Binder.clearCallingIdentity();
9613 ComponentName res = startServiceLocked(caller, service,
9614 resolvedType, callingPid, callingUid);
9615 Binder.restoreCallingIdentity(origId);
9616 return res;
9617 }
9618 }
9619
9620 ComponentName startServiceInPackage(int uid,
9621 Intent service, String resolvedType) {
9622 synchronized(this) {
9623 final long origId = Binder.clearCallingIdentity();
9624 ComponentName res = startServiceLocked(null, service,
9625 resolvedType, -1, uid);
9626 Binder.restoreCallingIdentity(origId);
9627 return res;
9628 }
9629 }
9630
9631 public int stopService(IApplicationThread caller, Intent service,
9632 String resolvedType) {
9633 // Refuse possible leaked file descriptors
9634 if (service != null && service.hasFileDescriptors() == true) {
9635 throw new IllegalArgumentException("File descriptors passed in Intent");
9636 }
9637
9638 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009639 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009640 + " type=" + resolvedType);
9641
9642 final ProcessRecord callerApp = getRecordForAppLocked(caller);
9643 if (caller != null && callerApp == null) {
9644 throw new SecurityException(
9645 "Unable to find app for caller " + caller
9646 + " (pid=" + Binder.getCallingPid()
9647 + ") when stopping service " + service);
9648 }
9649
9650 // If this service is active, make sure it is stopped.
9651 ServiceLookupResult r = findServiceLocked(service, resolvedType);
9652 if (r != null) {
9653 if (r.record != null) {
9654 synchronized (r.record.stats.getBatteryStats()) {
9655 r.record.stats.stopRunningLocked();
9656 }
9657 r.record.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009658 r.record.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009659 final long origId = Binder.clearCallingIdentity();
9660 bringDownServiceLocked(r.record, false);
9661 Binder.restoreCallingIdentity(origId);
9662 return 1;
9663 }
9664 return -1;
9665 }
9666 }
9667
9668 return 0;
9669 }
9670
9671 public IBinder peekService(Intent service, String resolvedType) {
9672 // Refuse possible leaked file descriptors
9673 if (service != null && service.hasFileDescriptors() == true) {
9674 throw new IllegalArgumentException("File descriptors passed in Intent");
9675 }
9676
9677 IBinder ret = null;
9678
9679 synchronized(this) {
9680 ServiceLookupResult r = findServiceLocked(service, resolvedType);
9681
9682 if (r != null) {
9683 // r.record is null if findServiceLocked() failed the caller permission check
9684 if (r.record == null) {
9685 throw new SecurityException(
9686 "Permission Denial: Accessing service " + r.record.name
9687 + " from pid=" + Binder.getCallingPid()
9688 + ", uid=" + Binder.getCallingUid()
9689 + " requires " + r.permission);
9690 }
9691 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
9692 if (ib != null) {
9693 ret = ib.binder;
9694 }
9695 }
9696 }
9697
9698 return ret;
9699 }
9700
9701 public boolean stopServiceToken(ComponentName className, IBinder token,
9702 int startId) {
9703 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009704 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009705 + " " + token + " startId=" + startId);
9706 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009707 if (r != null) {
9708 if (startId >= 0) {
9709 // Asked to only stop if done with all work. Note that
9710 // to avoid leaks, we will take this as dropping all
9711 // start items up to and including this one.
9712 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
9713 if (si != null) {
9714 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07009715 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
9716 cur.removeUriPermissionsLocked();
9717 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009718 break;
9719 }
9720 }
9721 }
9722
9723 if (r.lastStartId != startId) {
9724 return false;
9725 }
9726
9727 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009728 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009729 + " is last, but have " + r.deliveredStarts.size()
9730 + " remaining args");
9731 }
9732 }
9733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009734 synchronized (r.stats.getBatteryStats()) {
9735 r.stats.stopRunningLocked();
9736 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009737 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009738 }
9739 final long origId = Binder.clearCallingIdentity();
9740 bringDownServiceLocked(r, false);
9741 Binder.restoreCallingIdentity(origId);
9742 return true;
9743 }
9744 }
9745 return false;
9746 }
9747
9748 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009749 int id, Notification notification, boolean removeNotification) {
9750 final long origId = Binder.clearCallingIdentity();
9751 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009752 synchronized(this) {
9753 ServiceRecord r = findServiceLocked(className, token);
9754 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009755 if (id != 0) {
9756 if (notification == null) {
9757 throw new IllegalArgumentException("null notification");
9758 }
9759 if (r.foregroundId != id) {
9760 r.cancelNotification();
9761 r.foregroundId = id;
9762 }
9763 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
9764 r.foregroundNoti = notification;
9765 r.isForeground = true;
9766 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009767 if (r.app != null) {
9768 updateServiceForegroundLocked(r.app, true);
9769 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009770 } else {
9771 if (r.isForeground) {
9772 r.isForeground = false;
9773 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07009774 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009775 updateServiceForegroundLocked(r.app, true);
9776 }
9777 }
9778 if (removeNotification) {
9779 r.cancelNotification();
9780 r.foregroundId = 0;
9781 r.foregroundNoti = null;
9782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009783 }
9784 }
9785 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009786 } finally {
9787 Binder.restoreCallingIdentity(origId);
9788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009789 }
9790
9791 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
9792 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -07009793 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009794 if (sr.isForeground) {
9795 anyForeground = true;
9796 break;
9797 }
9798 }
9799 if (anyForeground != proc.foregroundServices) {
9800 proc.foregroundServices = anyForeground;
9801 if (oomAdj) {
9802 updateOomAdjLocked();
9803 }
9804 }
9805 }
9806
9807 public int bindService(IApplicationThread caller, IBinder token,
9808 Intent service, String resolvedType,
9809 IServiceConnection connection, int flags) {
9810 // Refuse possible leaked file descriptors
9811 if (service != null && service.hasFileDescriptors() == true) {
9812 throw new IllegalArgumentException("File descriptors passed in Intent");
9813 }
9814
9815 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009816 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009817 + " type=" + resolvedType + " conn=" + connection.asBinder()
9818 + " flags=0x" + Integer.toHexString(flags));
9819 final ProcessRecord callerApp = getRecordForAppLocked(caller);
9820 if (callerApp == null) {
9821 throw new SecurityException(
9822 "Unable to find app for caller " + caller
9823 + " (pid=" + Binder.getCallingPid()
9824 + ") when binding service " + service);
9825 }
9826
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009827 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009828 if (token != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009829 int aindex = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009830 if (aindex < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009831 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 return 0;
9833 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009834 activity = (ActivityRecord)mMainStack.mHistory.get(aindex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009835 }
9836
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009837 int clientLabel = 0;
9838 PendingIntent clientIntent = null;
9839
9840 if (callerApp.info.uid == Process.SYSTEM_UID) {
9841 // Hacky kind of thing -- allow system stuff to tell us
9842 // what they are, so we can report this elsewhere for
9843 // others to know why certain services are running.
9844 try {
9845 clientIntent = (PendingIntent)service.getParcelableExtra(
9846 Intent.EXTRA_CLIENT_INTENT);
9847 } catch (RuntimeException e) {
9848 }
9849 if (clientIntent != null) {
9850 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
9851 if (clientLabel != 0) {
9852 // There are no useful extras in the intent, trash them.
9853 // System code calling with this stuff just needs to know
9854 // this will happen.
9855 service = service.cloneFilter();
9856 }
9857 }
9858 }
9859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009860 ServiceLookupResult res =
9861 retrieveServiceLocked(service, resolvedType,
9862 Binder.getCallingPid(), Binder.getCallingUid());
9863 if (res == null) {
9864 return 0;
9865 }
9866 if (res.record == null) {
9867 return -1;
9868 }
9869 ServiceRecord s = res.record;
9870
9871 final long origId = Binder.clearCallingIdentity();
9872
9873 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009874 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009875 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009876 }
9877
9878 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
9879 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009880 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009881
9882 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009883 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
9884 if (clist == null) {
9885 clist = new ArrayList<ConnectionRecord>();
9886 s.connections.put(binder, clist);
9887 }
9888 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009889 b.connections.add(c);
9890 if (activity != null) {
9891 if (activity.connections == null) {
9892 activity.connections = new HashSet<ConnectionRecord>();
9893 }
9894 activity.connections.add(c);
9895 }
9896 b.client.connections.add(c);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009897 clist = mServiceConnections.get(binder);
9898 if (clist == null) {
9899 clist = new ArrayList<ConnectionRecord>();
9900 mServiceConnections.put(binder, clist);
9901 }
9902 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009903
9904 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
9905 s.lastActivity = SystemClock.uptimeMillis();
9906 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
9907 return 0;
9908 }
9909 }
9910
9911 if (s.app != null) {
9912 // This could have made the service more important.
9913 updateOomAdjLocked(s.app);
9914 }
9915
Joe Onorato8a9b2202010-02-26 18:56:32 -08009916 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009917 + ": received=" + b.intent.received
9918 + " apps=" + b.intent.apps.size()
9919 + " doRebind=" + b.intent.doRebind);
9920
9921 if (s.app != null && b.intent.received) {
9922 // Service is already running, so we can immediately
9923 // publish the connection.
9924 try {
9925 c.conn.connected(s.name, b.intent.binder);
9926 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009927 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009928 + " to connection " + c.conn.asBinder()
9929 + " (in " + c.binding.client.processName + ")", e);
9930 }
9931
9932 // If this is the first app connected back to this binding,
9933 // and the service had previously asked to be told when
9934 // rebound, then do so.
9935 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
9936 requestServiceBindingLocked(s, b.intent, true);
9937 }
9938 } else if (!b.intent.requested) {
9939 requestServiceBindingLocked(s, b.intent, false);
9940 }
9941
9942 Binder.restoreCallingIdentity(origId);
9943 }
9944
9945 return 1;
9946 }
9947
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009948 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009949 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009950 IBinder binder = c.conn.asBinder();
9951 AppBindRecord b = c.binding;
9952 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009953 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
9954 if (clist != null) {
9955 clist.remove(c);
9956 if (clist.size() == 0) {
9957 s.connections.remove(binder);
9958 }
9959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009960 b.connections.remove(c);
9961 if (c.activity != null && c.activity != skipAct) {
9962 if (c.activity.connections != null) {
9963 c.activity.connections.remove(c);
9964 }
9965 }
9966 if (b.client != skipApp) {
9967 b.client.connections.remove(c);
9968 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009969 clist = mServiceConnections.get(binder);
9970 if (clist != null) {
9971 clist.remove(c);
9972 if (clist.size() == 0) {
9973 mServiceConnections.remove(binder);
9974 }
9975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009976
9977 if (b.connections.size() == 0) {
9978 b.intent.apps.remove(b.client);
9979 }
9980
Joe Onorato8a9b2202010-02-26 18:56:32 -08009981 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009982 + ": shouldUnbind=" + b.intent.hasBound);
9983 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
9984 && b.intent.hasBound) {
9985 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009986 bumpServiceExecutingLocked(s, "unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009987 updateOomAdjLocked(s.app);
9988 b.intent.hasBound = false;
9989 // Assume the client doesn't want to know about a rebind;
9990 // we will deal with that later if it asks for one.
9991 b.intent.doRebind = false;
9992 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
9993 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009994 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009995 serviceDoneExecutingLocked(s, true);
9996 }
9997 }
9998
9999 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
10000 bringDownServiceLocked(s, false);
10001 }
10002 }
10003
10004 public boolean unbindService(IServiceConnection connection) {
10005 synchronized (this) {
10006 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010007 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010008 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
10009 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010010 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010011 + connection.asBinder());
10012 return false;
10013 }
10014
10015 final long origId = Binder.clearCallingIdentity();
10016
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010017 while (clist.size() > 0) {
10018 ConnectionRecord r = clist.get(0);
10019 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010020
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010021 if (r.binding.service.app != null) {
10022 // This could have made the service less important.
10023 updateOomAdjLocked(r.binding.service.app);
10024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010025 }
10026
10027 Binder.restoreCallingIdentity(origId);
10028 }
10029
10030 return true;
10031 }
10032
10033 public void publishService(IBinder token, Intent intent, IBinder service) {
10034 // Refuse possible leaked file descriptors
10035 if (intent != null && intent.hasFileDescriptors() == true) {
10036 throw new IllegalArgumentException("File descriptors passed in Intent");
10037 }
10038
10039 synchronized(this) {
10040 if (!(token instanceof ServiceRecord)) {
10041 throw new IllegalArgumentException("Invalid service token");
10042 }
10043 ServiceRecord r = (ServiceRecord)token;
10044
10045 final long origId = Binder.clearCallingIdentity();
10046
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010047 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010048 + " " + intent + ": " + service);
10049 if (r != null) {
10050 Intent.FilterComparison filter
10051 = new Intent.FilterComparison(intent);
10052 IntentBindRecord b = r.bindings.get(filter);
10053 if (b != null && !b.received) {
10054 b.binder = service;
10055 b.requested = true;
10056 b.received = true;
10057 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010058 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010059 = r.connections.values().iterator();
10060 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010061 ArrayList<ConnectionRecord> clist = it.next();
10062 for (int i=0; i<clist.size(); i++) {
10063 ConnectionRecord c = clist.get(i);
10064 if (!filter.equals(c.binding.intent.intent)) {
10065 if (DEBUG_SERVICE) Slog.v(
10066 TAG, "Not publishing to: " + c);
10067 if (DEBUG_SERVICE) Slog.v(
10068 TAG, "Bound intent: " + c.binding.intent.intent);
10069 if (DEBUG_SERVICE) Slog.v(
10070 TAG, "Published intent: " + intent);
10071 continue;
10072 }
10073 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
10074 try {
10075 c.conn.connected(r.name, service);
10076 } catch (Exception e) {
10077 Slog.w(TAG, "Failure sending service " + r.name +
10078 " to connection " + c.conn.asBinder() +
10079 " (in " + c.binding.client.processName + ")", e);
10080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010081 }
10082 }
10083 }
10084 }
10085
10086 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
10087
10088 Binder.restoreCallingIdentity(origId);
10089 }
10090 }
10091 }
10092
10093 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10094 // Refuse possible leaked file descriptors
10095 if (intent != null && intent.hasFileDescriptors() == true) {
10096 throw new IllegalArgumentException("File descriptors passed in Intent");
10097 }
10098
10099 synchronized(this) {
10100 if (!(token instanceof ServiceRecord)) {
10101 throw new IllegalArgumentException("Invalid service token");
10102 }
10103 ServiceRecord r = (ServiceRecord)token;
10104
10105 final long origId = Binder.clearCallingIdentity();
10106
10107 if (r != null) {
10108 Intent.FilterComparison filter
10109 = new Intent.FilterComparison(intent);
10110 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010111 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010112 + " at " + b + ": apps="
10113 + (b != null ? b.apps.size() : 0));
10114 if (b != null) {
10115 if (b.apps.size() > 0) {
10116 // Applications have already bound since the last
10117 // unbind, so just rebind right here.
10118 requestServiceBindingLocked(r, b, true);
10119 } else {
10120 // Note to tell the service the next time there is
10121 // a new client.
10122 b.doRebind = true;
10123 }
10124 }
10125
10126 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
10127
10128 Binder.restoreCallingIdentity(origId);
10129 }
10130 }
10131 }
10132
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010133 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010134 synchronized(this) {
10135 if (!(token instanceof ServiceRecord)) {
10136 throw new IllegalArgumentException("Invalid service token");
10137 }
10138 ServiceRecord r = (ServiceRecord)token;
10139 boolean inStopping = mStoppingServices.contains(token);
10140 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010141 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010142 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010143 + " with incorrect token: given " + token
10144 + ", expected " + r);
10145 return;
10146 }
10147
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010148 if (type == 1) {
10149 // This is a call from a service start... take care of
10150 // book-keeping.
10151 r.callStart = true;
10152 switch (res) {
10153 case Service.START_STICKY_COMPATIBILITY:
10154 case Service.START_STICKY: {
10155 // We are done with the associated start arguments.
10156 r.findDeliveredStart(startId, true);
10157 // Don't stop if killed.
10158 r.stopIfKilled = false;
10159 break;
10160 }
10161 case Service.START_NOT_STICKY: {
10162 // We are done with the associated start arguments.
10163 r.findDeliveredStart(startId, true);
10164 if (r.lastStartId == startId) {
10165 // There is no more work, and this service
10166 // doesn't want to hang around if killed.
10167 r.stopIfKilled = true;
10168 }
10169 break;
10170 }
10171 case Service.START_REDELIVER_INTENT: {
10172 // We'll keep this item until they explicitly
10173 // call stop for it, but keep track of the fact
10174 // that it was delivered.
10175 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
10176 if (si != null) {
10177 si.deliveryCount = 0;
10178 si.doneExecutingCount++;
10179 // Don't stop if killed.
10180 r.stopIfKilled = true;
10181 }
10182 break;
10183 }
10184 default:
10185 throw new IllegalArgumentException(
10186 "Unknown service start result: " + res);
10187 }
10188 if (res == Service.START_STICKY_COMPATIBILITY) {
10189 r.callStart = false;
10190 }
10191 }
10192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010193 final long origId = Binder.clearCallingIdentity();
10194 serviceDoneExecutingLocked(r, inStopping);
10195 Binder.restoreCallingIdentity(origId);
10196 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010197 Slog.w(TAG, "Done executing unknown service from pid "
10198 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010199 }
10200 }
10201 }
10202
10203 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010204 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
10205 + ": nesting=" + r.executeNesting
10206 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010207 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010208 r.executeNesting--;
10209 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010210 if (DEBUG_SERVICE) Slog.v(TAG,
10211 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010212 r.app.executingServices.remove(r);
10213 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010214 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
10215 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010216 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
10217 }
10218 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010219 if (DEBUG_SERVICE) Slog.v(TAG,
10220 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010221 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020010222 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010223 }
10224 updateOomAdjLocked(r.app);
10225 }
10226 }
10227
10228 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010229 String anrMessage = null;
10230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010231 synchronized(this) {
10232 if (proc.executingServices.size() == 0 || proc.thread == null) {
10233 return;
10234 }
10235 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
10236 Iterator<ServiceRecord> it = proc.executingServices.iterator();
10237 ServiceRecord timeout = null;
10238 long nextTime = 0;
10239 while (it.hasNext()) {
10240 ServiceRecord sr = it.next();
10241 if (sr.executingStart < maxTime) {
10242 timeout = sr;
10243 break;
10244 }
10245 if (sr.executingStart > nextTime) {
10246 nextTime = sr.executingStart;
10247 }
10248 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010249 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010250 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010251 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010252 } else {
10253 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10254 msg.obj = proc;
10255 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
10256 }
10257 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010258
10259 if (anrMessage != null) {
10260 appNotResponding(proc, null, null, anrMessage);
10261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010262 }
10263
10264 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010265 // BACKUP AND RESTORE
10266 // =========================================================
10267
10268 // Cause the target app to be launched if necessary and its backup agent
10269 // instantiated. The backup agent will invoke backupAgentCreated() on the
10270 // activity manager to announce its creation.
10271 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010272 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010273 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10274
10275 synchronized(this) {
10276 // !!! TODO: currently no check here that we're already bound
10277 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10278 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10279 synchronized (stats) {
10280 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10281 }
10282
Dianne Hackborne7f97212011-02-24 14:40:20 -080010283 // Backup agent is now in use, its package can't be stopped.
10284 try {
10285 AppGlobals.getPackageManager().setPackageStoppedState(
10286 app.packageName, false);
10287 } catch (RemoteException e) {
10288 }
10289
Christopher Tate181fafa2009-05-14 11:12:14 -070010290 BackupRecord r = new BackupRecord(ss, app, backupMode);
10291 ComponentName hostingName = new ComponentName(app.packageName, app.backupAgentName);
10292 // startProcessLocked() returns existing proc's record if it's already running
10293 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070010294 false, 0, "backup", hostingName, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010295 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010296 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010297 return false;
10298 }
10299
10300 r.app = proc;
10301 mBackupTarget = r;
10302 mBackupAppName = app.packageName;
10303
Christopher Tate6fa95972009-06-05 18:43:55 -070010304 // Try not to kill the process during backup
10305 updateOomAdjLocked(proc);
10306
Christopher Tate181fafa2009-05-14 11:12:14 -070010307 // If the process is already attached, schedule the creation of the backup agent now.
10308 // If it is not yet live, this will be done when it attaches to the framework.
10309 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010310 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010311 try {
10312 proc.thread.scheduleCreateBackupAgent(app, backupMode);
10313 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070010314 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070010315 }
10316 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010317 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070010318 }
10319 // Invariants: at this point, the target app process exists and the application
10320 // is either already running or in the process of coming up. mBackupTarget and
10321 // mBackupAppName describe the app, so that when it binds back to the AM we
10322 // know that it's scheduled for a backup-agent operation.
10323 }
10324
10325 return true;
10326 }
10327
10328 // A backup agent has just come up
10329 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010330 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070010331 + " = " + agent);
10332
10333 synchronized(this) {
10334 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010335 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070010336 return;
10337 }
Dianne Hackborn06740692010-09-22 22:46:21 -070010338 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010339
Dianne Hackborn06740692010-09-22 22:46:21 -070010340 long oldIdent = Binder.clearCallingIdentity();
10341 try {
10342 IBackupManager bm = IBackupManager.Stub.asInterface(
10343 ServiceManager.getService(Context.BACKUP_SERVICE));
10344 bm.agentConnected(agentPackageName, agent);
10345 } catch (RemoteException e) {
10346 // can't happen; the backup manager service is local
10347 } catch (Exception e) {
10348 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
10349 e.printStackTrace();
10350 } finally {
10351 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070010352 }
10353 }
10354
10355 // done with this agent
10356 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010357 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070010358 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010359 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070010360 return;
10361 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010362
10363 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070010364 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010365 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070010366 return;
10367 }
10368
Christopher Tate181fafa2009-05-14 11:12:14 -070010369 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010370 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070010371 return;
10372 }
10373
Christopher Tate6fa95972009-06-05 18:43:55 -070010374 ProcessRecord proc = mBackupTarget.app;
10375 mBackupTarget = null;
10376 mBackupAppName = null;
10377
10378 // Not backing this app up any more; reset its OOM adjustment
10379 updateOomAdjLocked(proc);
10380
Christopher Tatec7b31e32009-06-10 15:49:30 -070010381 // If the app crashed during backup, 'thread' will be null here
10382 if (proc.thread != null) {
10383 try {
10384 proc.thread.scheduleDestroyBackupAgent(appInfo);
10385 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010386 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070010387 e.printStackTrace();
10388 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010389 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010390 }
10391 }
10392 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010393 // BROADCASTS
10394 // =========================================================
10395
Josh Bartel7f208742010-02-25 11:01:44 -060010396 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010397 List cur) {
10398 final ContentResolver resolver = mContext.getContentResolver();
10399 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
10400 if (list == null) {
10401 return cur;
10402 }
10403 int N = list.size();
10404 for (int i=0; i<N; i++) {
10405 Intent intent = list.get(i);
10406 if (filter.match(resolver, intent, true, TAG) >= 0) {
10407 if (cur == null) {
10408 cur = new ArrayList<Intent>();
10409 }
10410 cur.add(intent);
10411 }
10412 }
10413 return cur;
10414 }
10415
10416 private final void scheduleBroadcastsLocked() {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010417 if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts: current="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010418 + mBroadcastsScheduled);
10419
10420 if (mBroadcastsScheduled) {
10421 return;
10422 }
10423 mHandler.sendEmptyMessage(BROADCAST_INTENT_MSG);
10424 mBroadcastsScheduled = true;
10425 }
10426
10427 public Intent registerReceiver(IApplicationThread caller,
10428 IIntentReceiver receiver, IntentFilter filter, String permission) {
10429 synchronized(this) {
10430 ProcessRecord callerApp = null;
10431 if (caller != null) {
10432 callerApp = getRecordForAppLocked(caller);
10433 if (callerApp == null) {
10434 throw new SecurityException(
10435 "Unable to find app for caller " + caller
10436 + " (pid=" + Binder.getCallingPid()
10437 + ") when registering receiver " + receiver);
10438 }
10439 }
10440
10441 List allSticky = null;
10442
10443 // Look for any matching sticky broadcasts...
10444 Iterator actions = filter.actionsIterator();
10445 if (actions != null) {
10446 while (actions.hasNext()) {
10447 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060010448 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010449 }
10450 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060010451 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010452 }
10453
10454 // The first sticky in the list is returned directly back to
10455 // the client.
10456 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
10457
Joe Onorato8a9b2202010-02-26 18:56:32 -080010458 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010459 + ": " + sticky);
10460
10461 if (receiver == null) {
10462 return sticky;
10463 }
10464
10465 ReceiverList rl
10466 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
10467 if (rl == null) {
10468 rl = new ReceiverList(this, callerApp,
10469 Binder.getCallingPid(),
10470 Binder.getCallingUid(), receiver);
10471 if (rl.app != null) {
10472 rl.app.receivers.add(rl);
10473 } else {
10474 try {
10475 receiver.asBinder().linkToDeath(rl, 0);
10476 } catch (RemoteException e) {
10477 return sticky;
10478 }
10479 rl.linkedToDeath = true;
10480 }
10481 mRegisteredReceivers.put(receiver.asBinder(), rl);
10482 }
10483 BroadcastFilter bf = new BroadcastFilter(filter, rl, permission);
10484 rl.add(bf);
10485 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010486 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010487 }
10488 mReceiverResolver.addFilter(bf);
10489
10490 // Enqueue broadcasts for all existing stickies that match
10491 // this filter.
10492 if (allSticky != null) {
10493 ArrayList receivers = new ArrayList();
10494 receivers.add(bf);
10495
10496 int N = allSticky.size();
10497 for (int i=0; i<N; i++) {
10498 Intent intent = (Intent)allSticky.get(i);
10499 BroadcastRecord r = new BroadcastRecord(intent, null,
10500 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080010501 false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010502 if (mParallelBroadcasts.size() == 0) {
10503 scheduleBroadcastsLocked();
10504 }
10505 mParallelBroadcasts.add(r);
10506 }
10507 }
10508
10509 return sticky;
10510 }
10511 }
10512
10513 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010514 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010515
10516 boolean doNext = false;
10517
10518 synchronized(this) {
10519 ReceiverList rl
10520 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
10521 if (rl != null) {
10522 if (rl.curBroadcast != null) {
10523 BroadcastRecord r = rl.curBroadcast;
10524 doNext = finishReceiverLocked(
10525 receiver.asBinder(), r.resultCode, r.resultData,
10526 r.resultExtras, r.resultAbort, true);
10527 }
10528
10529 if (rl.app != null) {
10530 rl.app.receivers.remove(rl);
10531 }
10532 removeReceiverLocked(rl);
10533 if (rl.linkedToDeath) {
10534 rl.linkedToDeath = false;
10535 rl.receiver.asBinder().unlinkToDeath(rl, 0);
10536 }
10537 }
10538 }
10539
10540 if (!doNext) {
10541 return;
10542 }
10543
10544 final long origId = Binder.clearCallingIdentity();
10545 processNextBroadcast(false);
10546 trimApplications();
10547 Binder.restoreCallingIdentity(origId);
10548 }
10549
10550 void removeReceiverLocked(ReceiverList rl) {
10551 mRegisteredReceivers.remove(rl.receiver.asBinder());
10552 int N = rl.size();
10553 for (int i=0; i<N; i++) {
10554 mReceiverResolver.removeFilter(rl.get(i));
10555 }
10556 }
10557
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070010558 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
10559 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
10560 ProcessRecord r = mLruProcesses.get(i);
10561 if (r.thread != null) {
10562 try {
10563 r.thread.dispatchPackageBroadcast(cmd, packages);
10564 } catch (RemoteException ex) {
10565 }
10566 }
10567 }
10568 }
10569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010570 private final int broadcastIntentLocked(ProcessRecord callerApp,
10571 String callerPackage, Intent intent, String resolvedType,
10572 IIntentReceiver resultTo, int resultCode, String resultData,
10573 Bundle map, String requiredPermission,
10574 boolean ordered, boolean sticky, int callingPid, int callingUid) {
10575 intent = new Intent(intent);
10576
Dianne Hackborne7f97212011-02-24 14:40:20 -080010577 // By default broadcasts do not go to stopped apps.
10578 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
10579
Joe Onorato8a9b2202010-02-26 18:56:32 -080010580 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010581 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
10582 + " ordered=" + ordered);
10583 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010584 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010585 }
10586
10587 // Handle special intents: if this broadcast is from the package
10588 // manager about a package being removed, we need to remove all of
10589 // its activities from the history stack.
10590 final boolean uidRemoved = intent.ACTION_UID_REMOVED.equals(
10591 intent.getAction());
10592 if (intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
10593 || intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010594 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010595 || uidRemoved) {
10596 if (checkComponentPermission(
10597 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010598 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010599 == PackageManager.PERMISSION_GRANTED) {
10600 if (uidRemoved) {
10601 final Bundle intentExtras = intent.getExtras();
10602 final int uid = intentExtras != null
10603 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
10604 if (uid >= 0) {
10605 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
10606 synchronized (bs) {
10607 bs.removeUidStatsLocked(uid);
10608 }
10609 }
10610 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010611 // If resources are unvailble just force stop all
10612 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010613 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010614 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
10615 if (list != null && (list.length > 0)) {
10616 for (String pkg : list) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080010617 forceStopPackageLocked(pkg, -1, false, true, true);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010618 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070010619 sendPackageBroadcastLocked(
10620 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010621 }
10622 } else {
10623 Uri data = intent.getData();
10624 String ssp;
10625 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
10626 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
10627 forceStopPackageLocked(ssp,
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080010628 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070010629 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070010630 if (intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
10631 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
10632 new String[] {ssp});
10633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010634 }
10635 }
10636 }
10637 } else {
10638 String msg = "Permission Denial: " + intent.getAction()
10639 + " broadcast from " + callerPackage + " (pid=" + callingPid
10640 + ", uid=" + callingUid + ")"
10641 + " requires "
10642 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010643 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010644 throw new SecurityException(msg);
10645 }
10646 }
10647
10648 /*
10649 * If this is the time zone changed action, queue up a message that will reset the timezone
10650 * of all currently running processes. This message will get queued up before the broadcast
10651 * happens.
10652 */
10653 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
10654 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
10655 }
10656
Robert Greenwalt03595d02010-11-02 14:08:23 -070010657 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
10658 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
10659 }
10660
Robert Greenwalt434203a2010-10-11 16:00:27 -070010661 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
10662 ProxyProperties proxy = intent.getParcelableExtra("proxy");
10663 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
10664 }
10665
Dianne Hackborn854060af2009-07-09 18:14:31 -070010666 /*
10667 * Prevent non-system code (defined here to be non-persistent
10668 * processes) from sending protected broadcasts.
10669 */
10670 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
10671 || callingUid == Process.SHELL_UID || callingUid == 0) {
10672 // Always okay.
10673 } else if (callerApp == null || !callerApp.persistent) {
10674 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010675 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070010676 intent.getAction())) {
10677 String msg = "Permission Denial: not allowed to send broadcast "
10678 + intent.getAction() + " from pid="
10679 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010680 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070010681 throw new SecurityException(msg);
10682 }
10683 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010684 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070010685 return BROADCAST_SUCCESS;
10686 }
10687 }
10688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010689 // Add to the sticky list if requested.
10690 if (sticky) {
10691 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
10692 callingPid, callingUid)
10693 != PackageManager.PERMISSION_GRANTED) {
10694 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
10695 + callingPid + ", uid=" + callingUid
10696 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010697 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010698 throw new SecurityException(msg);
10699 }
10700 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010701 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010702 + " and enforce permission " + requiredPermission);
10703 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
10704 }
10705 if (intent.getComponent() != null) {
10706 throw new SecurityException(
10707 "Sticky broadcasts can't target a specific component");
10708 }
10709 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
10710 if (list == null) {
10711 list = new ArrayList<Intent>();
10712 mStickyBroadcasts.put(intent.getAction(), list);
10713 }
10714 int N = list.size();
10715 int i;
10716 for (i=0; i<N; i++) {
10717 if (intent.filterEquals(list.get(i))) {
10718 // This sticky already exists, replace it.
10719 list.set(i, new Intent(intent));
10720 break;
10721 }
10722 }
10723 if (i >= N) {
10724 list.add(new Intent(intent));
10725 }
10726 }
10727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010728 // Figure out who all will receive this broadcast.
10729 List receivers = null;
10730 List<BroadcastFilter> registeredReceivers = null;
10731 try {
10732 if (intent.getComponent() != null) {
10733 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010734 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070010735 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010736 if (ai != null) {
10737 receivers = new ArrayList();
10738 ResolveInfo ri = new ResolveInfo();
10739 ri.activityInfo = ai;
10740 receivers.add(ri);
10741 }
10742 } else {
10743 // Need to resolve the intent to interested receivers...
10744 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
10745 == 0) {
10746 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010747 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010748 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010749 }
Mihai Preda074edef2009-05-18 17:13:31 +020010750 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010751 }
10752 } catch (RemoteException ex) {
10753 // pm is in same process, this will never happen.
10754 }
10755
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010756 final boolean replacePending =
10757 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
10758
Joe Onorato8a9b2202010-02-26 18:56:32 -080010759 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010760 + " replacePending=" + replacePending);
10761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010762 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
10763 if (!ordered && NR > 0) {
10764 // If we are not serializing this broadcast, then send the
10765 // registered receivers separately so they don't wait for the
10766 // components to be launched.
10767 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
10768 callerPackage, callingPid, callingUid, requiredPermission,
10769 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080010770 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010771 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010772 TAG, "Enqueueing parallel broadcast " + r
10773 + ": prev had " + mParallelBroadcasts.size());
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010774 boolean replaced = false;
10775 if (replacePending) {
10776 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
10777 if (intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010778 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010779 "***** DROPPING PARALLEL: " + intent);
10780 mParallelBroadcasts.set(i, r);
10781 replaced = true;
10782 break;
10783 }
10784 }
10785 }
10786 if (!replaced) {
10787 mParallelBroadcasts.add(r);
10788 scheduleBroadcastsLocked();
10789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010790 registeredReceivers = null;
10791 NR = 0;
10792 }
10793
10794 // Merge into one list.
10795 int ir = 0;
10796 if (receivers != null) {
10797 // A special case for PACKAGE_ADDED: do not allow the package
10798 // being added to see this broadcast. This prevents them from
10799 // using this as a back door to get run as soon as they are
10800 // installed. Maybe in the future we want to have a special install
10801 // broadcast or such for apps, but we'd like to deliberately make
10802 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010803 String skipPackages[] = null;
10804 if (intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
10805 || intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
10806 || intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
10807 Uri data = intent.getData();
10808 if (data != null) {
10809 String pkgName = data.getSchemeSpecificPart();
10810 if (pkgName != null) {
10811 skipPackages = new String[] { pkgName };
10812 }
10813 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010814 } else if (intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010815 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070010816 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010817 if (skipPackages != null && (skipPackages.length > 0)) {
10818 for (String skipPackage : skipPackages) {
10819 if (skipPackage != null) {
10820 int NT = receivers.size();
10821 for (int it=0; it<NT; it++) {
10822 ResolveInfo curt = (ResolveInfo)receivers.get(it);
10823 if (curt.activityInfo.packageName.equals(skipPackage)) {
10824 receivers.remove(it);
10825 it--;
10826 NT--;
10827 }
10828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010829 }
10830 }
10831 }
10832
10833 int NT = receivers != null ? receivers.size() : 0;
10834 int it = 0;
10835 ResolveInfo curt = null;
10836 BroadcastFilter curr = null;
10837 while (it < NT && ir < NR) {
10838 if (curt == null) {
10839 curt = (ResolveInfo)receivers.get(it);
10840 }
10841 if (curr == null) {
10842 curr = registeredReceivers.get(ir);
10843 }
10844 if (curr.getPriority() >= curt.priority) {
10845 // Insert this broadcast record into the final list.
10846 receivers.add(it, curr);
10847 ir++;
10848 curr = null;
10849 it++;
10850 NT++;
10851 } else {
10852 // Skip to the next ResolveInfo in the final list.
10853 it++;
10854 curt = null;
10855 }
10856 }
10857 }
10858 while (ir < NR) {
10859 if (receivers == null) {
10860 receivers = new ArrayList();
10861 }
10862 receivers.add(registeredReceivers.get(ir));
10863 ir++;
10864 }
10865
10866 if ((receivers != null && receivers.size() > 0)
10867 || resultTo != null) {
10868 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
10869 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080010870 receivers, resultTo, resultCode, resultData, map, ordered,
10871 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010872 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010873 TAG, "Enqueueing ordered broadcast " + r
10874 + ": prev had " + mOrderedBroadcasts.size());
10875 if (DEBUG_BROADCAST) {
10876 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010877 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010878 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010879 boolean replaced = false;
10880 if (replacePending) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010881 for (int i=mOrderedBroadcasts.size()-1; i>0; i--) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010882 if (intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010883 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010884 "***** DROPPING ORDERED: " + intent);
10885 mOrderedBroadcasts.set(i, r);
10886 replaced = true;
10887 break;
10888 }
10889 }
10890 }
10891 if (!replaced) {
10892 mOrderedBroadcasts.add(r);
10893 scheduleBroadcastsLocked();
10894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010895 }
10896
10897 return BROADCAST_SUCCESS;
10898 }
10899
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010900 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010901 // Refuse possible leaked file descriptors
10902 if (intent != null && intent.hasFileDescriptors() == true) {
10903 throw new IllegalArgumentException("File descriptors passed in Intent");
10904 }
10905
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010906 int flags = intent.getFlags();
10907
10908 if (!mProcessesReady) {
10909 // if the caller really truly claims to know what they're doing, go
10910 // ahead and allow the broadcast without launching any receivers
10911 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
10912 intent = new Intent(intent);
10913 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
10914 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
10915 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
10916 + " before boot completion");
10917 throw new IllegalStateException("Cannot broadcast before boot completed");
10918 }
10919 }
10920
10921 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
10922 throw new IllegalArgumentException(
10923 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
10924 }
10925
10926 return intent;
10927 }
10928
10929 public final int broadcastIntent(IApplicationThread caller,
10930 Intent intent, String resolvedType, IIntentReceiver resultTo,
10931 int resultCode, String resultData, Bundle map,
10932 String requiredPermission, boolean serialized, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010933 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010934 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070010935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010936 final ProcessRecord callerApp = getRecordForAppLocked(caller);
10937 final int callingPid = Binder.getCallingPid();
10938 final int callingUid = Binder.getCallingUid();
10939 final long origId = Binder.clearCallingIdentity();
10940 int res = broadcastIntentLocked(callerApp,
10941 callerApp != null ? callerApp.info.packageName : null,
10942 intent, resolvedType, resultTo,
10943 resultCode, resultData, map, requiredPermission, serialized,
10944 sticky, callingPid, callingUid);
10945 Binder.restoreCallingIdentity(origId);
10946 return res;
10947 }
10948 }
10949
10950 int broadcastIntentInPackage(String packageName, int uid,
10951 Intent intent, String resolvedType, IIntentReceiver resultTo,
10952 int resultCode, String resultData, Bundle map,
10953 String requiredPermission, boolean serialized, boolean sticky) {
10954 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010955 intent = verifyBroadcastLocked(intent);
10956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010957 final long origId = Binder.clearCallingIdentity();
10958 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
10959 resultTo, resultCode, resultData, map, requiredPermission,
10960 serialized, sticky, -1, uid);
10961 Binder.restoreCallingIdentity(origId);
10962 return res;
10963 }
10964 }
10965
10966 public final void unbroadcastIntent(IApplicationThread caller,
10967 Intent intent) {
10968 // Refuse possible leaked file descriptors
10969 if (intent != null && intent.hasFileDescriptors() == true) {
10970 throw new IllegalArgumentException("File descriptors passed in Intent");
10971 }
10972
10973 synchronized(this) {
10974 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
10975 != PackageManager.PERMISSION_GRANTED) {
10976 String msg = "Permission Denial: unbroadcastIntent() from pid="
10977 + Binder.getCallingPid()
10978 + ", uid=" + Binder.getCallingUid()
10979 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010980 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010981 throw new SecurityException(msg);
10982 }
10983 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
10984 if (list != null) {
10985 int N = list.size();
10986 int i;
10987 for (i=0; i<N; i++) {
10988 if (intent.filterEquals(list.get(i))) {
10989 list.remove(i);
10990 break;
10991 }
10992 }
10993 }
10994 }
10995 }
10996
10997 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
10998 String resultData, Bundle resultExtras, boolean resultAbort,
10999 boolean explicit) {
11000 if (mOrderedBroadcasts.size() == 0) {
11001 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011002 Slog.w(TAG, "finishReceiver called but no pending broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011003 }
11004 return false;
11005 }
11006 BroadcastRecord r = mOrderedBroadcasts.get(0);
11007 if (r.receiver == null) {
11008 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011009 Slog.w(TAG, "finishReceiver called but none active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011010 }
11011 return false;
11012 }
11013 if (r.receiver != receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011014 Slog.w(TAG, "finishReceiver called but active receiver is different");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011015 return false;
11016 }
11017 int state = r.state;
11018 r.state = r.IDLE;
11019 if (state == r.IDLE) {
11020 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011021 Slog.w(TAG, "finishReceiver called but state is IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011022 }
11023 }
11024 r.receiver = null;
11025 r.intent.setComponent(null);
11026 if (r.curApp != null) {
11027 r.curApp.curReceiver = null;
11028 }
11029 if (r.curFilter != null) {
11030 r.curFilter.receiverList.curBroadcast = null;
11031 }
11032 r.curFilter = null;
11033 r.curApp = null;
11034 r.curComponent = null;
11035 r.curReceiver = null;
11036 mPendingBroadcast = null;
11037
11038 r.resultCode = resultCode;
11039 r.resultData = resultData;
11040 r.resultExtras = resultExtras;
11041 r.resultAbort = resultAbort;
11042
11043 // We will process the next receiver right now if this is finishing
11044 // an app receiver (which is always asynchronous) or after we have
11045 // come back from calling a receiver.
11046 return state == BroadcastRecord.APP_RECEIVE
11047 || state == BroadcastRecord.CALL_DONE_RECEIVE;
11048 }
11049
11050 public void finishReceiver(IBinder who, int resultCode, String resultData,
11051 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011052 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011053
11054 // Refuse possible leaked file descriptors
11055 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11056 throw new IllegalArgumentException("File descriptors passed in Bundle");
11057 }
11058
11059 boolean doNext;
11060
11061 final long origId = Binder.clearCallingIdentity();
11062
11063 synchronized(this) {
11064 doNext = finishReceiverLocked(
11065 who, resultCode, resultData, resultExtras, resultAbort, true);
11066 }
11067
11068 if (doNext) {
11069 processNextBroadcast(false);
11070 }
11071 trimApplications();
11072
11073 Binder.restoreCallingIdentity(origId);
11074 }
11075
Jeff Brown4d94a762010-09-23 11:33:28 -070011076 private final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011077 if (r.nextReceiver > 0) {
11078 Object curReceiver = r.receivers.get(r.nextReceiver-1);
11079 if (curReceiver instanceof BroadcastFilter) {
11080 BroadcastFilter bf = (BroadcastFilter) curReceiver;
Doug Zongker2bec3d42009-12-04 12:52:44 -080011081 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011082 System.identityHashCode(r),
11083 r.intent.getAction(),
11084 r.nextReceiver - 1,
11085 System.identityHashCode(bf));
11086 } else {
Doug Zongker2bec3d42009-12-04 12:52:44 -080011087 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011088 System.identityHashCode(r),
11089 r.intent.getAction(),
11090 r.nextReceiver - 1,
11091 ((ResolveInfo)curReceiver).toString());
11092 }
11093 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011094 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011095 + r);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011096 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011097 System.identityHashCode(r),
11098 r.intent.getAction(),
11099 r.nextReceiver,
11100 "NONE");
11101 }
11102 }
11103
Jeff Brown4d94a762010-09-23 11:33:28 -070011104 private final void setBroadcastTimeoutLocked(long timeoutTime) {
11105 if (! mPendingBroadcastTimeoutMessage) {
11106 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
11107 mHandler.sendMessageAtTime(msg, timeoutTime);
11108 mPendingBroadcastTimeoutMessage = true;
11109 }
11110 }
11111
11112 private final void cancelBroadcastTimeoutLocked() {
11113 if (mPendingBroadcastTimeoutMessage) {
11114 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG);
11115 mPendingBroadcastTimeoutMessage = false;
11116 }
11117 }
11118
11119 private final void broadcastTimeoutLocked(boolean fromMsg) {
11120 if (fromMsg) {
11121 mPendingBroadcastTimeoutMessage = false;
11122 }
11123
11124 if (mOrderedBroadcasts.size() == 0) {
11125 return;
11126 }
11127
11128 long now = SystemClock.uptimeMillis();
11129 BroadcastRecord r = mOrderedBroadcasts.get(0);
11130 if (fromMsg) {
11131 if (mDidDexOpt) {
11132 // Delay timeouts until dexopt finishes.
11133 mDidDexOpt = false;
11134 long timeoutTime = SystemClock.uptimeMillis() + BROADCAST_TIMEOUT;
11135 setBroadcastTimeoutLocked(timeoutTime);
11136 return;
11137 }
11138 if (! mProcessesReady) {
11139 // Only process broadcast timeouts if the system is ready. That way
11140 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
11141 // to do heavy lifting for system up.
11142 return;
11143 }
11144
11145 long timeoutTime = r.receiverTime + BROADCAST_TIMEOUT;
11146 if (timeoutTime > now) {
11147 // We can observe premature timeouts because we do not cancel and reset the
11148 // broadcast timeout message after each receiver finishes. Instead, we set up
11149 // an initial timeout then kick it down the road a little further as needed
11150 // when it expires.
11151 if (DEBUG_BROADCAST) Slog.v(TAG,
11152 "Premature timeout @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
11153 + timeoutTime);
11154 setBroadcastTimeoutLocked(timeoutTime);
11155 return;
11156 }
11157 }
11158
11159 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
11160 + ", started " + (now - r.receiverTime) + "ms ago");
11161 r.receiverTime = now;
11162 r.anrCount++;
11163
11164 // Current receiver has passed its expiration date.
11165 if (r.nextReceiver <= 0) {
11166 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
11167 return;
11168 }
11169
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011170 ProcessRecord app = null;
11171 String anrMessage = null;
11172
Jeff Brown4d94a762010-09-23 11:33:28 -070011173 Object curReceiver = r.receivers.get(r.nextReceiver-1);
11174 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
11175 logBroadcastReceiverDiscardLocked(r);
11176 if (curReceiver instanceof BroadcastFilter) {
11177 BroadcastFilter bf = (BroadcastFilter)curReceiver;
11178 if (bf.receiverList.pid != 0
11179 && bf.receiverList.pid != MY_PID) {
11180 synchronized (this.mPidsSelfLocked) {
11181 app = this.mPidsSelfLocked.get(
11182 bf.receiverList.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011184 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011185 } else {
11186 app = r.curApp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011187 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011188
Jeff Brown4d94a762010-09-23 11:33:28 -070011189 if (app != null) {
11190 anrMessage = "Broadcast of " + r.intent.toString();
11191 }
11192
11193 if (mPendingBroadcast == r) {
11194 mPendingBroadcast = null;
11195 }
11196
11197 // Move on to the next receiver.
11198 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
11199 r.resultExtras, r.resultAbort, true);
11200 scheduleBroadcastsLocked();
11201
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011202 if (anrMessage != null) {
Jeff Brown4d94a762010-09-23 11:33:28 -070011203 // Post the ANR to the handler since we do not want to process ANRs while
11204 // potentially holding our lock.
11205 mHandler.post(new AppNotResponding(app, anrMessage));
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011207 }
11208
11209 private final void processCurBroadcastLocked(BroadcastRecord r,
11210 ProcessRecord app) throws RemoteException {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011211 if (DEBUG_BROADCAST) Slog.v(TAG,
11212 "Process cur broadcast " + r + " for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011213 if (app.thread == null) {
11214 throw new RemoteException();
11215 }
11216 r.receiver = app.thread.asBinder();
11217 r.curApp = app;
11218 app.curReceiver = r;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011219 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011220
11221 // Tell the application to launch this receiver.
11222 r.intent.setComponent(r.curComponent);
11223
11224 boolean started = false;
11225 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011226 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011227 "Delivering to component " + r.curComponent
11228 + ": " + r);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011229 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011230 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
11231 r.resultCode, r.resultData, r.resultExtras, r.ordered);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011232 if (DEBUG_BROADCAST) Slog.v(TAG,
11233 "Process cur broadcast " + r + " DELIVERED for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011234 started = true;
11235 } finally {
11236 if (!started) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011237 if (DEBUG_BROADCAST) Slog.v(TAG,
11238 "Process cur broadcast " + r + ": NOT STARTED!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011239 r.receiver = null;
11240 r.curApp = null;
11241 app.curReceiver = null;
11242 }
11243 }
11244
11245 }
11246
Jeff Brown4d94a762010-09-23 11:33:28 -070011247 static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011248 Intent intent, int resultCode, String data, Bundle extras,
11249 boolean ordered, boolean sticky) throws RemoteException {
Jeff Brown4d94a762010-09-23 11:33:28 -070011250 // Send the intent to the receiver asynchronously using one-way binder calls.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011251 if (app != null && app.thread != null) {
11252 // If we have an app thread, do the call through that so it is
11253 // correctly ordered with other one-way calls.
11254 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011255 data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256 } else {
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011257 receiver.performReceive(intent, resultCode, data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011258 }
11259 }
11260
Jeff Brown4d94a762010-09-23 11:33:28 -070011261 private final void deliverToRegisteredReceiverLocked(BroadcastRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011262 BroadcastFilter filter, boolean ordered) {
11263 boolean skip = false;
11264 if (filter.requiredPermission != null) {
11265 int perm = checkComponentPermission(filter.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011266 r.callingPid, r.callingUid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011267 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011268 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011269 + r.intent.toString()
11270 + " from " + r.callerPackage + " (pid="
11271 + r.callingPid + ", uid=" + r.callingUid + ")"
11272 + " requires " + filter.requiredPermission
11273 + " due to registered receiver " + filter);
11274 skip = true;
11275 }
11276 }
11277 if (r.requiredPermission != null) {
11278 int perm = checkComponentPermission(r.requiredPermission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011279 filter.receiverList.pid, filter.receiverList.uid, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011280 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011281 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282 + r.intent.toString()
11283 + " to " + filter.receiverList.app
11284 + " (pid=" + filter.receiverList.pid
11285 + ", uid=" + filter.receiverList.uid + ")"
11286 + " requires " + r.requiredPermission
11287 + " due to sender " + r.callerPackage
11288 + " (uid " + r.callingUid + ")");
11289 skip = true;
11290 }
11291 }
11292
11293 if (!skip) {
11294 // If this is not being sent as an ordered broadcast, then we
11295 // don't want to touch the fields that keep track of the current
11296 // state of ordered broadcasts.
11297 if (ordered) {
11298 r.receiver = filter.receiverList.receiver.asBinder();
11299 r.curFilter = filter;
11300 filter.receiverList.curBroadcast = r;
11301 r.state = BroadcastRecord.CALL_IN_RECEIVE;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011302 if (filter.receiverList.app != null) {
11303 // Bump hosting application to no longer be in background
11304 // scheduling class. Note that we can't do that if there
11305 // isn't an app... but we can only be in that case for
11306 // things that directly call the IActivityManager API, which
11307 // are already core system stuff so don't matter for this.
11308 r.curApp = filter.receiverList.app;
11309 filter.receiverList.app.curReceiver = r;
11310 updateOomAdjLocked();
11311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011312 }
11313 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011314 if (DEBUG_BROADCAST_LIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011315 int seq = r.intent.getIntExtra("seq", -1);
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011316 Slog.i(TAG, "Delivering to " + filter
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011317 + " (seq=" + seq + "): " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011318 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011319 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011320 new Intent(r.intent), r.resultCode,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011321 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011322 if (ordered) {
11323 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
11324 }
11325 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011326 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011327 if (ordered) {
11328 r.receiver = null;
11329 r.curFilter = null;
11330 filter.receiverList.curBroadcast = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011331 if (filter.receiverList.app != null) {
11332 filter.receiverList.app.curReceiver = null;
11333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011334 }
11335 }
11336 }
11337 }
11338
Dianne Hackborn12527f92009-11-11 17:39:50 -080011339 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
11340 if (r.callingUid < 0) {
11341 // This was from a registerReceiver() call; ignore it.
11342 return;
11343 }
11344 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
11345 MAX_BROADCAST_HISTORY-1);
11346 r.finishTime = SystemClock.uptimeMillis();
11347 mBroadcastHistory[0] = r;
11348 }
11349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011350 private final void processNextBroadcast(boolean fromMsg) {
11351 synchronized(this) {
11352 BroadcastRecord r;
11353
Joe Onorato8a9b2202010-02-26 18:56:32 -080011354 if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011355 + mParallelBroadcasts.size() + " broadcasts, "
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011356 + mOrderedBroadcasts.size() + " ordered broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011357
11358 updateCpuStats();
11359
11360 if (fromMsg) {
11361 mBroadcastsScheduled = false;
11362 }
11363
11364 // First, deliver any non-serialized broadcasts right away.
11365 while (mParallelBroadcasts.size() > 0) {
11366 r = mParallelBroadcasts.remove(0);
Dianne Hackborn12527f92009-11-11 17:39:50 -080011367 r.dispatchTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011368 final int N = r.receivers.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011369 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011370 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011371 for (int i=0; i<N; i++) {
11372 Object target = r.receivers.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011373 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011374 "Delivering non-ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011375 + target + ": " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070011376 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011377 }
Dianne Hackborn12527f92009-11-11 17:39:50 -080011378 addBroadcastToHistoryLocked(r);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011379 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011380 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011381 }
11382
11383 // Now take care of the next serialized one...
11384
11385 // If we are waiting for a process to come up to handle the next
11386 // broadcast, then do nothing at this point. Just in case, we
11387 // check that the process we're waiting for still exists.
11388 if (mPendingBroadcast != null) {
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070011389 if (DEBUG_BROADCAST_LIGHT) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011390 Slog.v(TAG, "processNextBroadcast: waiting for "
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070011391 + mPendingBroadcast.curApp);
11392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011393
11394 boolean isDead;
11395 synchronized (mPidsSelfLocked) {
11396 isDead = (mPidsSelfLocked.get(mPendingBroadcast.curApp.pid) == null);
11397 }
11398 if (!isDead) {
11399 // It's still alive, so keep waiting
11400 return;
11401 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011402 Slog.w(TAG, "pending app " + mPendingBroadcast.curApp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011403 + " died before responding to broadcast");
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011404 mPendingBroadcast.state = BroadcastRecord.IDLE;
11405 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011406 mPendingBroadcast = null;
11407 }
11408 }
11409
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011410 boolean looped = false;
11411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011412 do {
11413 if (mOrderedBroadcasts.size() == 0) {
11414 // No more broadcasts pending, so all done!
11415 scheduleAppGcsLocked();
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011416 if (looped) {
11417 // If we had finished the last ordered broadcast, then
11418 // make sure all processes have correct oom and sched
11419 // adjustments.
11420 updateOomAdjLocked();
11421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011422 return;
11423 }
11424 r = mOrderedBroadcasts.get(0);
11425 boolean forceReceive = false;
11426
11427 // Ensure that even if something goes awry with the timeout
11428 // detection, we catch "hung" broadcasts here, discard them,
Jeff Hamiltonacf84742010-05-25 22:10:18 -050011429 // and continue to make progress.
11430 //
11431 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
Jeff Brown4d94a762010-09-23 11:33:28 -070011432 // receivers don't get executed with timeouts. They're intended for
Jeff Hamiltonacf84742010-05-25 22:10:18 -050011433 // one time heavy lifting after system upgrades and can take
11434 // significant amounts of time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011435 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011436 if (mProcessesReady && r.dispatchTime > 0) {
Jeff Hamiltonacf84742010-05-25 22:10:18 -050011437 long now = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011438 if ((numReceivers > 0) &&
11439 (now > r.dispatchTime + (2*BROADCAST_TIMEOUT*numReceivers))) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011440 Slog.w(TAG, "Hung broadcast discarded after timeout failure:"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011441 + " now=" + now
11442 + " dispatchTime=" + r.dispatchTime
Dianne Hackborn12527f92009-11-11 17:39:50 -080011443 + " startTime=" + r.receiverTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011444 + " intent=" + r.intent
11445 + " numReceivers=" + numReceivers
11446 + " nextReceiver=" + r.nextReceiver
11447 + " state=" + r.state);
Jeff Brown4d94a762010-09-23 11:33:28 -070011448 broadcastTimeoutLocked(false); // forcibly finish this broadcast
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 forceReceive = true;
11450 r.state = BroadcastRecord.IDLE;
11451 }
11452 }
11453
11454 if (r.state != BroadcastRecord.IDLE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011455 if (DEBUG_BROADCAST) Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011456 "processNextBroadcast() called when not idle (state="
11457 + r.state + ")");
11458 return;
11459 }
11460
11461 if (r.receivers == null || r.nextReceiver >= numReceivers
11462 || r.resultAbort || forceReceive) {
11463 // No more receivers for this broadcast! Send the final
11464 // result if requested...
11465 if (r.resultTo != null) {
11466 try {
11467 if (DEBUG_BROADCAST) {
11468 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011469 Slog.i(TAG, "Finishing broadcast " + r.intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011470 + " seq=" + seq + " app=" + r.callerApp);
11471 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011472 performReceiveLocked(r.callerApp, r.resultTo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 new Intent(r.intent), r.resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011474 r.resultData, r.resultExtras, false, false);
Johannes Carlssonb5a86542010-10-27 10:08:10 +020011475 // Set this to null so that the reference
11476 // (local and remote) isnt kept in the mBroadcastHistory.
11477 r.resultTo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011478 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011479 Slog.w(TAG, "Failure sending broadcast result of " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011480 }
11481 }
11482
Joe Onorato8a9b2202010-02-26 18:56:32 -080011483 if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
Jeff Brown4d94a762010-09-23 11:33:28 -070011484 cancelBroadcastTimeoutLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011485
Joe Onorato8a9b2202010-02-26 18:56:32 -080011486 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011487 + r);
11488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 // ... and on to the next...
Dianne Hackborn12527f92009-11-11 17:39:50 -080011490 addBroadcastToHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011491 mOrderedBroadcasts.remove(0);
11492 r = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011493 looped = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011494 continue;
11495 }
11496 } while (r == null);
11497
11498 // Get the next receiver...
11499 int recIdx = r.nextReceiver++;
11500
11501 // Keep track of when this receiver started, and make sure there
11502 // is a timeout message pending to kill it if need be.
Dianne Hackborn12527f92009-11-11 17:39:50 -080011503 r.receiverTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011504 if (recIdx == 0) {
Dianne Hackborn12527f92009-11-11 17:39:50 -080011505 r.dispatchTime = r.receiverTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011506
Joe Onorato8a9b2202010-02-26 18:56:32 -080011507 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011508 + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070011509 }
11510 if (! mPendingBroadcastTimeoutMessage) {
11511 long timeoutTime = r.receiverTime + BROADCAST_TIMEOUT;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011512 if (DEBUG_BROADCAST) Slog.v(TAG,
Jeff Brown4d94a762010-09-23 11:33:28 -070011513 "Submitting BROADCAST_TIMEOUT_MSG for " + r + " at " + timeoutTime);
11514 setBroadcastTimeoutLocked(timeoutTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011515 }
11516
11517 Object nextReceiver = r.receivers.get(recIdx);
11518 if (nextReceiver instanceof BroadcastFilter) {
11519 // Simple case: this is a registered receiver who gets
11520 // a direct call.
11521 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011522 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011523 "Delivering ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011524 + filter + ": " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070011525 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011526 if (r.receiver == null || !r.ordered) {
11527 // The receiver has already finished, so schedule to
11528 // process the next one.
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011529 if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing: ordered="
11530 + r.ordered + " receiver=" + r.receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011531 r.state = BroadcastRecord.IDLE;
11532 scheduleBroadcastsLocked();
11533 }
11534 return;
11535 }
11536
11537 // Hard case: need to instantiate the receiver, possibly
11538 // starting its application process to host it.
11539
11540 ResolveInfo info =
11541 (ResolveInfo)nextReceiver;
11542
11543 boolean skip = false;
11544 int perm = checkComponentPermission(info.activityInfo.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011545 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
11546 info.activityInfo.exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011547 if (perm != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011548 if (!info.activityInfo.exported) {
11549 Slog.w(TAG, "Permission Denial: broadcasting "
11550 + r.intent.toString()
11551 + " from " + r.callerPackage + " (pid=" + r.callingPid
11552 + ", uid=" + r.callingUid + ")"
11553 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
11554 + " due to receiver " + info.activityInfo.packageName
11555 + "/" + info.activityInfo.name);
11556 } else {
11557 Slog.w(TAG, "Permission Denial: broadcasting "
11558 + r.intent.toString()
11559 + " from " + r.callerPackage + " (pid=" + r.callingPid
11560 + ", uid=" + r.callingUid + ")"
11561 + " requires " + info.activityInfo.permission
11562 + " due to receiver " + info.activityInfo.packageName
11563 + "/" + info.activityInfo.name);
11564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011565 skip = true;
11566 }
11567 if (r.callingUid != Process.SYSTEM_UID &&
11568 r.requiredPermission != null) {
11569 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011570 perm = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011571 checkPermission(r.requiredPermission,
11572 info.activityInfo.applicationInfo.packageName);
11573 } catch (RemoteException e) {
11574 perm = PackageManager.PERMISSION_DENIED;
11575 }
11576 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011577 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011578 + r.intent + " to "
11579 + info.activityInfo.applicationInfo.packageName
11580 + " requires " + r.requiredPermission
11581 + " due to sender " + r.callerPackage
11582 + " (uid " + r.callingUid + ")");
11583 skip = true;
11584 }
11585 }
11586 if (r.curApp != null && r.curApp.crashing) {
11587 // If the target process is crashing, just skip it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011588 if (DEBUG_BROADCAST) Slog.v(TAG,
11589 "Skipping deliver ordered " + r + " to " + r.curApp
11590 + ": process crashing");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011591 skip = true;
11592 }
11593
11594 if (skip) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011595 if (DEBUG_BROADCAST) Slog.v(TAG,
11596 "Skipping delivery of ordered " + r + " for whatever reason");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011597 r.receiver = null;
11598 r.curFilter = null;
11599 r.state = BroadcastRecord.IDLE;
11600 scheduleBroadcastsLocked();
11601 return;
11602 }
11603
11604 r.state = BroadcastRecord.APP_RECEIVE;
11605 String targetProcess = info.activityInfo.processName;
11606 r.curComponent = new ComponentName(
11607 info.activityInfo.applicationInfo.packageName,
11608 info.activityInfo.name);
11609 r.curReceiver = info.activityInfo;
11610
Dianne Hackborne7f97212011-02-24 14:40:20 -080011611 // Broadcast is being executed, its package can't be stopped.
11612 try {
11613 AppGlobals.getPackageManager().setPackageStoppedState(
11614 r.curComponent.getPackageName(), false);
11615 } catch (RemoteException e) {
11616 }
11617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011618 // Is this receiver's application already running?
11619 ProcessRecord app = getProcessRecordLocked(targetProcess,
11620 info.activityInfo.applicationInfo.uid);
11621 if (app != null && app.thread != null) {
11622 try {
11623 processCurBroadcastLocked(r, app);
11624 return;
11625 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011626 Slog.w(TAG, "Exception when sending broadcast to "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011627 + r.curComponent, e);
11628 }
11629
11630 // If a dead object exception was thrown -- fall through to
11631 // restart the application.
11632 }
11633
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011634 // Not running -- get it started, to be executed when the app comes up.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011635 if (DEBUG_BROADCAST) Slog.v(TAG,
11636 "Need to start app " + targetProcess + " for broadcast " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011637 if ((r.curApp=startProcessLocked(targetProcess,
11638 info.activityInfo.applicationInfo, true,
11639 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011640 "broadcast", r.curComponent,
11641 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0))
11642 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011643 // Ah, this recipient is unavailable. Finish it if necessary,
11644 // and mark the broadcast record as ready for the next.
Joe Onorato8a9b2202010-02-26 18:56:32 -080011645 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011646 + info.activityInfo.applicationInfo.packageName + "/"
11647 + info.activityInfo.applicationInfo.uid + " for broadcast "
11648 + r.intent + ": process is bad");
Jeff Brown4d94a762010-09-23 11:33:28 -070011649 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011650 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
11651 r.resultExtras, r.resultAbort, true);
11652 scheduleBroadcastsLocked();
11653 r.state = BroadcastRecord.IDLE;
11654 return;
11655 }
11656
11657 mPendingBroadcast = r;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011658 mPendingBroadcastRecvIndex = recIdx;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011659 }
11660 }
11661
11662 // =========================================================
11663 // INSTRUMENTATION
11664 // =========================================================
11665
11666 public boolean startInstrumentation(ComponentName className,
11667 String profileFile, int flags, Bundle arguments,
11668 IInstrumentationWatcher watcher) {
11669 // Refuse possible leaked file descriptors
11670 if (arguments != null && arguments.hasFileDescriptors()) {
11671 throw new IllegalArgumentException("File descriptors passed in Bundle");
11672 }
11673
11674 synchronized(this) {
11675 InstrumentationInfo ii = null;
11676 ApplicationInfo ai = null;
11677 try {
11678 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011679 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011680 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011681 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011682 } catch (PackageManager.NameNotFoundException e) {
11683 }
11684 if (ii == null) {
11685 reportStartInstrumentationFailure(watcher, className,
11686 "Unable to find instrumentation info for: " + className);
11687 return false;
11688 }
11689 if (ai == null) {
11690 reportStartInstrumentationFailure(watcher, className,
11691 "Unable to find instrumentation target package: " + ii.targetPackage);
11692 return false;
11693 }
11694
11695 int match = mContext.getPackageManager().checkSignatures(
11696 ii.targetPackage, ii.packageName);
11697 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11698 String msg = "Permission Denial: starting instrumentation "
11699 + className + " from pid="
11700 + Binder.getCallingPid()
11701 + ", uid=" + Binder.getCallingPid()
11702 + " not allowed because package " + ii.packageName
11703 + " does not have a signature matching the target "
11704 + ii.targetPackage;
11705 reportStartInstrumentationFailure(watcher, className, msg);
11706 throw new SecurityException(msg);
11707 }
11708
11709 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080011710 forceStopPackageLocked(ii.targetPackage, -1, true, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011711 ProcessRecord app = addAppLocked(ai);
11712 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011713 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011714 app.instrumentationProfileFile = profileFile;
11715 app.instrumentationArguments = arguments;
11716 app.instrumentationWatcher = watcher;
11717 app.instrumentationResultClass = className;
11718 Binder.restoreCallingIdentity(origId);
11719 }
11720
11721 return true;
11722 }
11723
11724 /**
11725 * Report errors that occur while attempting to start Instrumentation. Always writes the
11726 * error to the logs, but if somebody is watching, send the report there too. This enables
11727 * the "am" command to report errors with more information.
11728 *
11729 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11730 * @param cn The component name of the instrumentation.
11731 * @param report The error report.
11732 */
11733 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11734 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011735 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011736 try {
11737 if (watcher != null) {
11738 Bundle results = new Bundle();
11739 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11740 results.putString("Error", report);
11741 watcher.instrumentationStatus(cn, -1, results);
11742 }
11743 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011744 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011745 }
11746 }
11747
11748 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11749 if (app.instrumentationWatcher != null) {
11750 try {
11751 // NOTE: IInstrumentationWatcher *must* be oneway here
11752 app.instrumentationWatcher.instrumentationFinished(
11753 app.instrumentationClass,
11754 resultCode,
11755 results);
11756 } catch (RemoteException e) {
11757 }
11758 }
11759 app.instrumentationWatcher = null;
11760 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011761 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011762 app.instrumentationProfileFile = null;
11763 app.instrumentationArguments = null;
11764
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080011765 forceStopPackageLocked(app.processName, -1, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011766 }
11767
11768 public void finishInstrumentation(IApplicationThread target,
11769 int resultCode, Bundle results) {
11770 // Refuse possible leaked file descriptors
11771 if (results != null && results.hasFileDescriptors()) {
11772 throw new IllegalArgumentException("File descriptors passed in Intent");
11773 }
11774
11775 synchronized(this) {
11776 ProcessRecord app = getRecordForAppLocked(target);
11777 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011778 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011779 return;
11780 }
11781 final long origId = Binder.clearCallingIdentity();
11782 finishInstrumentationLocked(app, resultCode, results);
11783 Binder.restoreCallingIdentity(origId);
11784 }
11785 }
11786
11787 // =========================================================
11788 // CONFIGURATION
11789 // =========================================================
11790
11791 public ConfigurationInfo getDeviceConfigurationInfo() {
11792 ConfigurationInfo config = new ConfigurationInfo();
11793 synchronized (this) {
11794 config.reqTouchScreen = mConfiguration.touchscreen;
11795 config.reqKeyboardType = mConfiguration.keyboard;
11796 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011797 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
11798 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011799 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
11800 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011801 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
11802 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011803 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
11804 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070011805 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011806 }
11807 return config;
11808 }
11809
11810 public Configuration getConfiguration() {
11811 Configuration ci;
11812 synchronized(this) {
11813 ci = new Configuration(mConfiguration);
11814 }
11815 return ci;
11816 }
11817
11818 public void updateConfiguration(Configuration values) {
11819 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11820 "updateConfiguration()");
11821
11822 synchronized(this) {
11823 if (values == null && mWindowManager != null) {
11824 // sentinel: fetch the current configuration from the window manager
11825 values = mWindowManager.computeNewConfiguration();
11826 }
11827
11828 final long origId = Binder.clearCallingIdentity();
11829 updateConfigurationLocked(values, null);
11830 Binder.restoreCallingIdentity(origId);
11831 }
11832 }
11833
11834 /**
11835 * Do either or both things: (1) change the current configuration, and (2)
11836 * make sure the given activity is running with the (now) current
11837 * configuration. Returns true if the activity has been left running, or
11838 * false if <var>starting</var> is being destroyed to match the new
11839 * configuration.
11840 */
11841 public boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011842 ActivityRecord starting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011843 int changes = 0;
11844
11845 boolean kept = true;
11846
11847 if (values != null) {
11848 Configuration newConfig = new Configuration(mConfiguration);
11849 changes = newConfig.updateFrom(values);
11850 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011851 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011852 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011853 }
11854
Doug Zongker2bec3d42009-12-04 12:52:44 -080011855 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856
11857 if (values.locale != null) {
11858 saveLocaleLocked(values.locale,
11859 !values.locale.equals(mConfiguration.locale),
11860 values.userSetLocale);
11861 }
11862
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011863 mConfigurationSeq++;
11864 if (mConfigurationSeq <= 0) {
11865 mConfigurationSeq = 1;
11866 }
11867 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011868 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011869 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011870
11871 AttributeCache ac = AttributeCache.instance();
11872 if (ac != null) {
11873 ac.updateConfiguration(mConfiguration);
11874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011875
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011876 if (Settings.System.hasInterestingConfigurationChanges(changes)) {
11877 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
11878 msg.obj = new Configuration(mConfiguration);
11879 mHandler.sendMessage(msg);
11880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011881
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011882 for (int i=mLruProcesses.size()-1; i>=0; i--) {
11883 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011884 try {
11885 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011886 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011887 + app.processName + " new config " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011888 app.thread.scheduleConfigurationChanged(mConfiguration);
11889 }
11890 } catch (Exception e) {
11891 }
11892 }
11893 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011894 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
11895 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
11897 null, false, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011898 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
11899 broadcastIntentLocked(null, null,
11900 new Intent(Intent.ACTION_LOCALE_CHANGED),
11901 null, null, 0, null, null,
11902 null, false, false, MY_PID, Process.SYSTEM_UID);
11903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011904 }
11905 }
11906
11907 if (changes != 0 && starting == null) {
11908 // If the configuration changed, and the caller is not already
11909 // in the process of starting an activity, then find the top
11910 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011911 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011912 }
11913
11914 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011915 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080011916 // And we need to make sure at this point that all other activities
11917 // are made visible with the correct configuration.
11918 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011919 }
11920
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011921 if (values != null && mWindowManager != null) {
11922 mWindowManager.setNewConfiguration(mConfiguration);
11923 }
11924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011925 return kept;
11926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011927
11928 /**
11929 * Save the locale. You must be inside a synchronized (this) block.
11930 */
11931 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
11932 if(isDiff) {
11933 SystemProperties.set("user.language", l.getLanguage());
11934 SystemProperties.set("user.region", l.getCountry());
11935 }
11936
11937 if(isPersist) {
11938 SystemProperties.set("persist.sys.language", l.getLanguage());
11939 SystemProperties.set("persist.sys.country", l.getCountry());
11940 SystemProperties.set("persist.sys.localevar", l.getVariant());
11941 }
11942 }
11943
11944 // =========================================================
11945 // LIFETIME MANAGEMENT
11946 // =========================================================
11947
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011948 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
11949 ProcessRecord TOP_APP, boolean recursed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011950 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011951 // This adjustment has already been computed. If we are calling
11952 // from the top, we may have already computed our adjustment with
11953 // an earlier hidden adjustment that isn't really for us... if
11954 // so, use the new hidden adjustment.
11955 if (!recursed && app.hidden) {
11956 app.curAdj = hiddenAdj;
11957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011958 return app.curAdj;
11959 }
11960
11961 if (app.thread == null) {
11962 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011963 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011964 return (app.curAdj=EMPTY_APP_ADJ);
11965 }
11966
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011967 if (app.maxAdj <= FOREGROUND_APP_ADJ) {
11968 // The max adjustment doesn't allow this app to be anything
11969 // below foreground, so it is not worth doing work for it.
11970 app.adjType = "fixed";
11971 app.adjSeq = mAdjSeq;
11972 app.curRawAdj = app.maxAdj;
Dianne Hackborn287952c2010-09-22 22:34:31 -070011973 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011974 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
11975 return (app.curAdj=app.maxAdj);
11976 }
11977
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011978 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011979 app.adjSource = null;
11980 app.adjTarget = null;
Dianne Hackborn287952c2010-09-22 22:34:31 -070011981 app.keeping = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011982 app.empty = false;
11983 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984
The Android Open Source Project4df24232009-03-05 14:34:35 -080011985 // Determine the importance of the process, starting with most
11986 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011987 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011988 int schedGroup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011989 int N;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011990 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011991 // The last app on the list is the foreground app.
11992 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011993 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011994 app.adjType = "top-activity";
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011995 } else if (app.instrumentationClass != null) {
11996 // Don't want to kill running instrumentation.
11997 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011998 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011999 app.adjType = "instrumentation";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012000 } else if (app.curReceiver != null ||
12001 (mPendingBroadcast != null && mPendingBroadcast.curApp == app)) {
12002 // An app that is currently receiving a broadcast also
12003 // counts as being in the foreground.
12004 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012005 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012006 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012007 } else if (app.executingServices.size() > 0) {
12008 // An app that is currently executing a service callback also
12009 // counts as being in the foreground.
12010 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012011 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012012 app.adjType = "exec-service";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012013 } else if ((N=app.activities.size()) != 0) {
12014 // This app is in the background with paused activities.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012015 app.hidden = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012016 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012017 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012018 app.adjType = "bg-activities";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012019 N = app.activities.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012020 for (int j=0; j<N; j++) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080012021 ActivityRecord r = app.activities.get(j);
12022 if (r.visible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012023 // This app has a visible activity!
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012024 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012025 adj = VISIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012026 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012027 app.adjType = "visible";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012028 break;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080012029 } else if (r.state == ActivityState.PAUSING
12030 || r.state == ActivityState.PAUSED
12031 || r.state == ActivityState.STOPPING) {
12032 adj = PERCEPTIBLE_APP_ADJ;
12033 app.adjType = "stopping";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012034 }
12035 }
12036 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012037 // A very not-needed process. If this is lower in the lru list,
12038 // we will push it in to the empty bucket.
12039 app.hidden = true;
12040 app.empty = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012041 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012042 adj = hiddenAdj;
12043 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012044 }
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012045
12046 if (adj > PERCEPTIBLE_APP_ADJ) {
12047 if (app.foregroundServices) {
12048 // The user is aware of this app, so make it visible.
12049 adj = PERCEPTIBLE_APP_ADJ;
12050 schedGroup = Process.THREAD_GROUP_DEFAULT;
12051 app.adjType = "foreground-service";
12052 } else if (app.forcingToForeground != null) {
12053 // The user is aware of this app, so make it visible.
12054 adj = PERCEPTIBLE_APP_ADJ;
12055 schedGroup = Process.THREAD_GROUP_DEFAULT;
12056 app.adjType = "force-foreground";
12057 app.adjSource = app.forcingToForeground;
12058 }
12059 }
12060
12061 if (adj > HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
12062 // We don't want to kill the current heavy-weight process.
12063 adj = HEAVY_WEIGHT_APP_ADJ;
12064 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12065 app.adjType = "heavy";
12066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012067
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012068 if (adj > HOME_APP_ADJ && app == mHomeProcess) {
12069 // This process is hosting what we currently consider to be the
12070 // home app, so we don't want to let it go into the background.
12071 adj = HOME_APP_ADJ;
12072 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12073 app.adjType = "home";
12074 }
12075
Joe Onorato8a9b2202010-02-26 18:56:32 -080012076 //Slog.i(TAG, "OOM " + app + ": initial adj=" + adj);
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012077
The Android Open Source Project4df24232009-03-05 14:34:35 -080012078 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012079 // there are applications dependent on our services or providers, but
12080 // this gives us a baseline and makes sure we don't get into an
12081 // infinite recursion.
12082 app.adjSeq = mAdjSeq;
12083 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012084
Christopher Tate6fa95972009-06-05 18:43:55 -070012085 if (mBackupTarget != null && app == mBackupTarget.app) {
12086 // If possible we want to avoid killing apps while they're being backed up
12087 if (adj > BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012088 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Christopher Tate6fa95972009-06-05 18:43:55 -070012089 adj = BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012090 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012091 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012092 }
12093 }
12094
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012095 if (app.services.size() != 0 && (adj > FOREGROUND_APP_ADJ
12096 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012097 final long now = SystemClock.uptimeMillis();
12098 // This process is more important if the top activity is
12099 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012100 Iterator<ServiceRecord> jt = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012101 while (jt.hasNext() && adj > FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012102 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012103 if (s.startRequested) {
12104 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
12105 // This service has seen some activity within
12106 // recent memory, so we will keep its process ahead
12107 // of the background processes.
12108 if (adj > SECONDARY_SERVER_ADJ) {
12109 adj = SECONDARY_SERVER_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012110 app.adjType = "started-services";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012111 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012112 }
12113 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012114 // If we have let the service slide into the background
12115 // state, still have some text describing what it is doing
12116 // even though the service no longer has an impact.
12117 if (adj > SECONDARY_SERVER_ADJ) {
12118 app.adjType = "started-bg-services";
12119 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012120 // Don't kill this process because it is doing work; it
12121 // has said it is doing work.
12122 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012123 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012124 if (s.connections.size() > 0 && (adj > FOREGROUND_APP_ADJ
12125 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012126 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012127 = s.connections.values().iterator();
12128 while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012129 ArrayList<ConnectionRecord> clist = kt.next();
12130 for (int i=0; i<clist.size() && adj > FOREGROUND_APP_ADJ; i++) {
12131 // XXX should compute this based on the max of
12132 // all connected clients.
12133 ConnectionRecord cr = clist.get(i);
12134 if (cr.binding.client == app) {
12135 // Binding to ourself is not interesting.
12136 continue;
12137 }
12138 if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
12139 ProcessRecord client = cr.binding.client;
12140 int myHiddenAdj = hiddenAdj;
12141 if (myHiddenAdj > client.hiddenAdj) {
12142 if (client.hiddenAdj >= VISIBLE_APP_ADJ) {
12143 myHiddenAdj = client.hiddenAdj;
12144 } else {
12145 myHiddenAdj = VISIBLE_APP_ADJ;
12146 }
12147 }
12148 int clientAdj = computeOomAdjLocked(
12149 client, myHiddenAdj, TOP_APP, true);
12150 if (adj > clientAdj) {
12151 adj = clientAdj >= VISIBLE_APP_ADJ
12152 ? clientAdj : VISIBLE_APP_ADJ;
12153 if (!client.hidden) {
12154 app.hidden = false;
12155 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012156 if (client.keeping) {
12157 app.keeping = true;
12158 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012159 app.adjType = "service";
12160 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12161 .REASON_SERVICE_IN_USE;
12162 app.adjSource = cr.binding.client;
12163 app.adjTarget = s.name;
12164 }
12165 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12166 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12167 schedGroup = Process.THREAD_GROUP_DEFAULT;
12168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012169 }
12170 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012171 ActivityRecord a = cr.activity;
12172 //if (a != null) {
12173 // Slog.i(TAG, "Connection to " + a ": state=" + a.state);
12174 //}
12175 if (a != null && adj > FOREGROUND_APP_ADJ &&
12176 (a.state == ActivityState.RESUMED
12177 || a.state == ActivityState.PAUSING)) {
12178 adj = FOREGROUND_APP_ADJ;
12179 schedGroup = Process.THREAD_GROUP_DEFAULT;
12180 app.hidden = false;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012181 app.adjType = "service";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012182 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12183 .REASON_SERVICE_IN_USE;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012184 app.adjSource = a;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012185 app.adjTarget = s.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012187 }
12188 }
12189 }
12190 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012191
Dianne Hackborn287952c2010-09-22 22:34:31 -070012192 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012193 // would like to avoid killing it unless it would prevent the current
12194 // application from running. By default we put the process in
12195 // with the rest of the background processes; as we scan through
12196 // its services we may bump it up from there.
12197 if (adj > hiddenAdj) {
12198 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012199 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012200 app.adjType = "bg-services";
12201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012202 }
12203
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012204 if (app.pubProviders.size() != 0 && (adj > FOREGROUND_APP_ADJ
12205 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012206 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012207 while (jt.hasNext() && (adj > FOREGROUND_APP_ADJ
12208 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012209 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012210 if (cpr.clients.size() != 0) {
12211 Iterator<ProcessRecord> kt = cpr.clients.iterator();
12212 while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
12213 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070012214 if (client == app) {
12215 // Being our own client is not interesting.
12216 continue;
12217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012218 int myHiddenAdj = hiddenAdj;
12219 if (myHiddenAdj > client.hiddenAdj) {
12220 if (client.hiddenAdj > FOREGROUND_APP_ADJ) {
12221 myHiddenAdj = client.hiddenAdj;
12222 } else {
12223 myHiddenAdj = FOREGROUND_APP_ADJ;
12224 }
12225 }
12226 int clientAdj = computeOomAdjLocked(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012227 client, myHiddenAdj, TOP_APP, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012228 if (adj > clientAdj) {
12229 adj = clientAdj > FOREGROUND_APP_ADJ
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012230 ? clientAdj : FOREGROUND_APP_ADJ;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012231 if (!client.hidden) {
12232 app.hidden = false;
12233 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012234 if (client.keeping) {
12235 app.keeping = true;
12236 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012237 app.adjType = "provider";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012238 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12239 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012240 app.adjSource = client;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012241 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012242 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012243 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12244 schedGroup = Process.THREAD_GROUP_DEFAULT;
12245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012246 }
12247 }
12248 // If the provider has external (non-framework) process
12249 // dependencies, ensure that its adjustment is at least
12250 // FOREGROUND_APP_ADJ.
12251 if (cpr.externals != 0) {
12252 if (adj > FOREGROUND_APP_ADJ) {
12253 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012254 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012255 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012256 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012257 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012258 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012259 }
12260 }
12261 }
12262 }
12263
12264 app.curRawAdj = adj;
12265
Joe Onorato8a9b2202010-02-26 18:56:32 -080012266 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012267 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12268 if (adj > app.maxAdj) {
12269 adj = app.maxAdj;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012270 if (app.maxAdj <= PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012271 schedGroup = Process.THREAD_GROUP_DEFAULT;
12272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012273 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012274 if (adj < HIDDEN_APP_MIN_ADJ) {
12275 app.keeping = true;
12276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012277
12278 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012279 app.curSchedGroup = schedGroup;
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012281 return adj;
12282 }
12283
12284 /**
12285 * Ask a given process to GC right now.
12286 */
12287 final void performAppGcLocked(ProcessRecord app) {
12288 try {
12289 app.lastRequestedGc = SystemClock.uptimeMillis();
12290 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012291 if (app.reportLowMemory) {
12292 app.reportLowMemory = false;
12293 app.thread.scheduleLowMemory();
12294 } else {
12295 app.thread.processInBackground();
12296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012297 }
12298 } catch (Exception e) {
12299 // whatever.
12300 }
12301 }
12302
12303 /**
12304 * Returns true if things are idle enough to perform GCs.
12305 */
Josh Bartel7f208742010-02-25 11:01:44 -060012306 private final boolean canGcNowLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012307 return mParallelBroadcasts.size() == 0
12308 && mOrderedBroadcasts.size() == 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012309 && (mSleeping || (mMainStack.mResumedActivity != null &&
12310 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012311 }
12312
12313 /**
12314 * Perform GCs on all processes that are waiting for it, but only
12315 * if things are idle.
12316 */
12317 final void performAppGcsLocked() {
12318 final int N = mProcessesToGc.size();
12319 if (N <= 0) {
12320 return;
12321 }
Josh Bartel7f208742010-02-25 11:01:44 -060012322 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012323 while (mProcessesToGc.size() > 0) {
12324 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012325 if (proc.curRawAdj > PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012326 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
12327 <= SystemClock.uptimeMillis()) {
12328 // To avoid spamming the system, we will GC processes one
12329 // at a time, waiting a few seconds between each.
12330 performAppGcLocked(proc);
12331 scheduleAppGcsLocked();
12332 return;
12333 } else {
12334 // It hasn't been long enough since we last GCed this
12335 // process... put it in the list to wait for its time.
12336 addProcessToGcListLocked(proc);
12337 break;
12338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012339 }
12340 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012341
12342 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012343 }
12344 }
12345
12346 /**
12347 * If all looks good, perform GCs on all processes waiting for them.
12348 */
12349 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060012350 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012351 performAppGcsLocked();
12352 return;
12353 }
12354 // Still not idle, wait some more.
12355 scheduleAppGcsLocked();
12356 }
12357
12358 /**
12359 * Schedule the execution of all pending app GCs.
12360 */
12361 final void scheduleAppGcsLocked() {
12362 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012363
12364 if (mProcessesToGc.size() > 0) {
12365 // Schedule a GC for the time to the next process.
12366 ProcessRecord proc = mProcessesToGc.get(0);
12367 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
12368
12369 long when = mProcessesToGc.get(0).lastRequestedGc + GC_MIN_INTERVAL;
12370 long now = SystemClock.uptimeMillis();
12371 if (when < (now+GC_TIMEOUT)) {
12372 when = now + GC_TIMEOUT;
12373 }
12374 mHandler.sendMessageAtTime(msg, when);
12375 }
12376 }
12377
12378 /**
12379 * Add a process to the array of processes waiting to be GCed. Keeps the
12380 * list in sorted order by the last GC time. The process can't already be
12381 * on the list.
12382 */
12383 final void addProcessToGcListLocked(ProcessRecord proc) {
12384 boolean added = false;
12385 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
12386 if (mProcessesToGc.get(i).lastRequestedGc <
12387 proc.lastRequestedGc) {
12388 added = true;
12389 mProcessesToGc.add(i+1, proc);
12390 break;
12391 }
12392 }
12393 if (!added) {
12394 mProcessesToGc.add(0, proc);
12395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012396 }
12397
12398 /**
12399 * Set up to ask a process to GC itself. This will either do it
12400 * immediately, or put it on the list of processes to gc the next
12401 * time things are idle.
12402 */
12403 final void scheduleAppGcLocked(ProcessRecord app) {
12404 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012405 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012406 return;
12407 }
12408 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012409 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012410 scheduleAppGcsLocked();
12411 }
12412 }
12413
Dianne Hackborn287952c2010-09-22 22:34:31 -070012414 final void checkExcessivePowerUsageLocked(boolean doKills) {
12415 updateCpuStatsNow();
12416
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012417 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012418 boolean doWakeKills = doKills;
12419 boolean doCpuKills = doKills;
12420 if (mLastPowerCheckRealtime == 0) {
12421 doWakeKills = false;
12422 }
12423 if (mLastPowerCheckUptime == 0) {
12424 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012425 }
12426 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012427 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012428 }
12429 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012430 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
12431 final long curUptime = SystemClock.uptimeMillis();
12432 final long uptimeSince = curUptime - mLastPowerCheckUptime;
12433 mLastPowerCheckRealtime = curRealtime;
12434 mLastPowerCheckUptime = curUptime;
12435 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
12436 doWakeKills = false;
12437 }
12438 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
12439 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012440 }
12441 int i = mLruProcesses.size();
12442 while (i > 0) {
12443 i--;
12444 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012445 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012446 long wtime;
12447 synchronized (stats) {
12448 wtime = stats.getProcessWakeTime(app.info.uid,
12449 app.pid, curRealtime);
12450 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012451 long wtimeUsed = wtime - app.lastWakeTime;
12452 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
12453 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012454 StringBuilder sb = new StringBuilder(128);
12455 sb.append("Wake for ");
12456 app.toShortString(sb);
12457 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012458 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012459 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012460 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012461 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012462 sb.append((wtimeUsed*100)/realtimeSince);
12463 sb.append("%)");
12464 Slog.i(TAG, sb.toString());
12465 sb.setLength(0);
12466 sb.append("CPU for ");
12467 app.toShortString(sb);
12468 sb.append(": over ");
12469 TimeUtils.formatDuration(uptimeSince, sb);
12470 sb.append(" used ");
12471 TimeUtils.formatDuration(cputimeUsed, sb);
12472 sb.append(" (");
12473 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012474 sb.append("%)");
12475 Slog.i(TAG, sb.toString());
12476 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012477 // If a process has held a wake lock for more
12478 // than 50% of the time during this period,
12479 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070012480 if (doWakeKills && realtimeSince > 0
12481 && ((wtimeUsed*100)/realtimeSince) >= 50) {
12482 synchronized (stats) {
12483 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
12484 realtimeSince, wtimeUsed);
12485 }
12486 Slog.w(TAG, "Excessive wake lock in " + app.processName
12487 + " (pid " + app.pid + "): held " + wtimeUsed
12488 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012489 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12490 app.processName, app.setAdj, "excessive wake lock");
12491 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012492 } else if (doCpuKills && uptimeSince > 0
12493 && ((cputimeUsed*100)/uptimeSince) >= 50) {
12494 synchronized (stats) {
12495 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
12496 uptimeSince, cputimeUsed);
12497 }
12498 Slog.w(TAG, "Excessive CPU in " + app.processName
12499 + " (pid " + app.pid + "): used " + cputimeUsed
12500 + " during " + uptimeSince);
12501 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12502 app.processName, app.setAdj, "excessive cpu");
12503 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012504 } else {
12505 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012506 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012507 }
12508 }
12509 }
12510 }
12511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012512 private final boolean updateOomAdjLocked(
12513 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP) {
12514 app.hiddenAdj = hiddenAdj;
12515
12516 if (app.thread == null) {
12517 return true;
12518 }
12519
Dianne Hackborn287952c2010-09-22 22:34:31 -070012520 final boolean wasKeeping = app.keeping;
12521
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012522 int adj = computeOomAdjLocked(app, hiddenAdj, TOP_APP, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012523
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012524 if ((app.pid != 0 && app.pid != MY_PID) || Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012525 if (app.curRawAdj != app.setRawAdj) {
12526 if (app.curRawAdj > FOREGROUND_APP_ADJ
12527 && app.setRawAdj <= FOREGROUND_APP_ADJ) {
12528 // If this app is transitioning from foreground to
12529 // non-foreground, have it do a gc.
12530 scheduleAppGcLocked(app);
12531 } else if (app.curRawAdj >= HIDDEN_APP_MIN_ADJ
12532 && app.setRawAdj < HIDDEN_APP_MIN_ADJ) {
12533 // Likewise do a gc when an app is moving in to the
12534 // background (such as a service stopping).
12535 scheduleAppGcLocked(app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012536 }
12537
12538 if (wasKeeping && !app.keeping) {
12539 // This app is no longer something we want to keep. Note
12540 // its current wake lock time to later know to kill it if
12541 // it is not behaving well.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012542 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12543 synchronized (stats) {
12544 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
12545 app.pid, SystemClock.elapsedRealtime());
12546 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012547 app.lastCpuTime = app.curCpuTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012548 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012550 app.setRawAdj = app.curRawAdj;
12551 }
12552 if (adj != app.setAdj) {
12553 if (Process.setOomAdj(app.pid, adj)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012554 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012555 TAG, "Set app " + app.processName +
12556 " oom adj to " + adj);
12557 app.setAdj = adj;
12558 } else {
12559 return false;
12560 }
12561 }
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012562 if (app.setSchedGroup != app.curSchedGroup) {
12563 app.setSchedGroup = app.curSchedGroup;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012564 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012565 "Setting process group of " + app.processName
12566 + " to " + app.curSchedGroup);
12567 if (true) {
San Mehat9438de22009-06-10 09:11:28 -070012568 long oldId = Binder.clearCallingIdentity();
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012569 try {
12570 Process.setProcessGroup(app.pid, app.curSchedGroup);
12571 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012572 Slog.w(TAG, "Failed setting process group of " + app.pid
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012573 + " to " + app.curSchedGroup);
San Mehat9438de22009-06-10 09:11:28 -070012574 e.printStackTrace();
12575 } finally {
12576 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012577 }
12578 }
12579 if (false) {
12580 if (app.thread != null) {
12581 try {
12582 app.thread.setSchedulingGroup(app.curSchedGroup);
12583 } catch (RemoteException e) {
12584 }
12585 }
12586 }
12587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012588 }
12589
12590 return true;
12591 }
12592
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012593 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012594 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012595 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012596 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012597 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012598 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012599 }
12600 }
12601 return resumedActivity;
12602 }
12603
12604 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012605 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012606 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12607 int curAdj = app.curAdj;
12608 final boolean wasHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
12609 && app.curAdj <= HIDDEN_APP_MAX_ADJ;
12610
12611 mAdjSeq++;
12612
12613 final boolean res = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP);
12614 if (res) {
12615 final boolean nowHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
12616 && app.curAdj <= HIDDEN_APP_MAX_ADJ;
12617 if (nowHidden != wasHidden) {
12618 // Changed to/from hidden state, so apps after it in the LRU
12619 // list may also be changed.
12620 updateOomAdjLocked();
12621 }
12622 }
12623 return res;
12624 }
12625
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012626 final boolean updateOomAdjLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012627 boolean didOomAdj = true;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012628 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12630
12631 if (false) {
12632 RuntimeException e = new RuntimeException();
12633 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012634 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012635 }
12636
12637 mAdjSeq++;
12638
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012639 // Let's determine how many processes we have running vs.
12640 // how many slots we have for background processes; we may want
12641 // to put multiple processes in a slot of there are enough of
12642 // them.
12643 int numSlots = HIDDEN_APP_MAX_ADJ - HIDDEN_APP_MIN_ADJ + 1;
12644 int factor = (mLruProcesses.size()-4)/numSlots;
12645 if (factor < 1) factor = 1;
12646 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070012647 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012649 // First try updating the OOM adjustment for each of the
12650 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012651 int i = mLruProcesses.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012652 int curHiddenAdj = HIDDEN_APP_MIN_ADJ;
12653 while (i > 0) {
12654 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012655 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012656 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012657 if (updateOomAdjLocked(app, curHiddenAdj, TOP_APP)) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012658 if (curHiddenAdj < EMPTY_APP_ADJ
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012659 && app.curAdj == curHiddenAdj) {
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012660 step++;
12661 if (step >= factor) {
12662 step = 0;
12663 curHiddenAdj++;
12664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012665 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070012666 if (app.curAdj >= HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn149427c2010-04-23 14:20:03 -070012667 if (!app.killedBackground) {
12668 numHidden++;
12669 if (numHidden > MAX_HIDDEN_APPS) {
Dianne Hackborn906497c2010-05-10 15:57:38 -070012670 Slog.i(TAG, "No longer want " + app.processName
12671 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackborn149427c2010-04-23 14:20:03 -070012672 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12673 app.processName, app.setAdj, "too many background");
12674 app.killedBackground = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -070012675 Process.killProcessQuiet(app.pid);
Dianne Hackborn149427c2010-04-23 14:20:03 -070012676 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070012677 }
12678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012679 } else {
12680 didOomAdj = false;
12681 }
12682 }
12683
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012684 // If we return false, we will fall back on killing processes to
12685 // have a fixed limit. Do this if a limit has been requested; else
12686 // only return false if one of the adjustments failed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012687 return ENFORCE_PROCESS_LIMIT || mProcessLimit > 0 ? false : didOomAdj;
12688 }
12689
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012690 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012691 synchronized (this) {
12692 int i;
12693
12694 // First remove any unused application processes whose package
12695 // has been removed.
12696 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
12697 final ProcessRecord app = mRemovedProcesses.get(i);
12698 if (app.activities.size() == 0
12699 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012700 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012701 TAG, "Exiting empty application process "
12702 + app.processName + " ("
12703 + (app.thread != null ? app.thread.asBinder() : null)
12704 + ")\n");
12705 if (app.pid > 0 && app.pid != MY_PID) {
12706 Process.killProcess(app.pid);
12707 } else {
12708 try {
12709 app.thread.scheduleExit();
12710 } catch (Exception e) {
12711 // Ignore exceptions.
12712 }
12713 }
12714 cleanUpApplicationRecordLocked(app, false, -1);
12715 mRemovedProcesses.remove(i);
12716
12717 if (app.persistent) {
12718 if (app.persistent) {
12719 addAppLocked(app.info);
12720 }
12721 }
12722 }
12723 }
12724
12725 // Now try updating the OOM adjustment for each of the
12726 // application processes based on their current state.
12727 // If the setOomAdj() API is not supported, then go with our
12728 // back-up plan...
12729 if (!updateOomAdjLocked()) {
12730
12731 // Count how many processes are running services.
12732 int numServiceProcs = 0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012733 for (i=mLruProcesses.size()-1; i>=0; i--) {
12734 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012735
12736 if (app.persistent || app.services.size() != 0
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -070012737 || app.curReceiver != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012738 // Don't count processes holding services against our
12739 // maximum process count.
Joe Onorato8a9b2202010-02-26 18:56:32 -080012740 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012741 TAG, "Not trimming app " + app + " with services: "
12742 + app.services);
12743 numServiceProcs++;
12744 }
12745 }
12746
12747 int curMaxProcs = mProcessLimit;
12748 if (curMaxProcs <= 0) curMaxProcs = MAX_PROCESSES;
12749 if (mAlwaysFinishActivities) {
12750 curMaxProcs = 1;
12751 }
12752 curMaxProcs += numServiceProcs;
12753
12754 // Quit as many processes as we can to get down to the desired
12755 // process count. First remove any processes that no longer
12756 // have activites running in them.
12757 for ( i=0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012758 i<mLruProcesses.size()
12759 && mLruProcesses.size() > curMaxProcs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012760 i++) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012761 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012762 // Quit an application only if it is not currently
12763 // running any activities.
12764 if (!app.persistent && app.activities.size() == 0
12765 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012766 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012767 TAG, "Exiting empty application process "
12768 + app.processName + " ("
12769 + (app.thread != null ? app.thread.asBinder() : null)
12770 + ")\n");
12771 if (app.pid > 0 && app.pid != MY_PID) {
12772 Process.killProcess(app.pid);
12773 } else {
12774 try {
12775 app.thread.scheduleExit();
12776 } catch (Exception e) {
12777 // Ignore exceptions.
12778 }
12779 }
12780 // todo: For now we assume the application is not buggy
12781 // or evil, and will quit as a result of our request.
12782 // Eventually we need to drive this off of the death
12783 // notification, and kill the process if it takes too long.
12784 cleanUpApplicationRecordLocked(app, false, i);
12785 i--;
12786 }
12787 }
12788
12789 // If we still have too many processes, now from the least
12790 // recently used process we start finishing activities.
Joe Onorato8a9b2202010-02-26 18:56:32 -080012791 if (Config.LOGV) Slog.v(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012792 TAG, "*** NOW HAVE " + mLruProcesses.size() +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012793 " of " + curMaxProcs + " processes");
12794 for ( i=0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012795 i<mLruProcesses.size()
12796 && mLruProcesses.size() > curMaxProcs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012797 i++) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012798 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012799 // Quit the application only if we have a state saved for
12800 // all of its activities.
12801 boolean canQuit = !app.persistent && app.curReceiver == null
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -070012802 && app.services.size() == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012803 int NUMA = app.activities.size();
12804 int j;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012805 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012806 TAG, "Looking to quit " + app.processName);
12807 for (j=0; j<NUMA && canQuit; j++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012808 ActivityRecord r = app.activities.get(j);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012809 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012810 TAG, " " + r.intent.getComponent().flattenToShortString()
12811 + ": frozen=" + r.haveState + ", visible=" + r.visible);
12812 canQuit = (r.haveState || !r.stateNotNeeded)
12813 && !r.visible && r.stopped;
12814 }
12815 if (canQuit) {
12816 // Finish all of the activities, and then the app itself.
12817 for (j=0; j<NUMA; j++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012818 ActivityRecord r = app.activities.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012819 if (!r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012820 r.stack.destroyActivityLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012821 }
12822 r.resultTo = null;
12823 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080012824 Slog.i(TAG, "Exiting application process "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012825 + app.processName + " ("
12826 + (app.thread != null ? app.thread.asBinder() : null)
12827 + ")\n");
12828 if (app.pid > 0 && app.pid != MY_PID) {
12829 Process.killProcess(app.pid);
12830 } else {
12831 try {
12832 app.thread.scheduleExit();
12833 } catch (Exception e) {
12834 // Ignore exceptions.
12835 }
12836 }
12837 // todo: For now we assume the application is not buggy
12838 // or evil, and will quit as a result of our request.
12839 // Eventually we need to drive this off of the death
12840 // notification, and kill the process if it takes too long.
12841 cleanUpApplicationRecordLocked(app, false, i);
12842 i--;
12843 //dump();
12844 }
12845 }
12846
12847 }
12848
12849 int curMaxActivities = MAX_ACTIVITIES;
12850 if (mAlwaysFinishActivities) {
12851 curMaxActivities = 1;
12852 }
12853
12854 // Finally, if there are too many activities now running, try to
12855 // finish as many as we can to get back down to the limit.
12856 for ( i=0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012857 i<mMainStack.mLRUActivities.size()
12858 && mMainStack.mLRUActivities.size() > curMaxActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012859 i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012860 final ActivityRecord r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012861 = (ActivityRecord)mMainStack.mLRUActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012862
12863 // We can finish this one if we have its icicle saved and
12864 // it is not persistent.
12865 if ((r.haveState || !r.stateNotNeeded) && !r.visible
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -070012866 && r.stopped && !r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012867 final int origSize = mMainStack.mLRUActivities.size();
12868 r.stack.destroyActivityLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869
12870 // This will remove it from the LRU list, so keep
12871 // our index at the same value. Note that this check to
12872 // see if the size changes is just paranoia -- if
12873 // something unexpected happens, we don't want to end up
12874 // in an infinite loop.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012875 if (origSize > mMainStack.mLRUActivities.size()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012876 i--;
12877 }
12878 }
12879 }
12880 }
12881 }
12882
12883 /** This method sends the specified signal to each of the persistent apps */
12884 public void signalPersistentProcesses(int sig) throws RemoteException {
12885 if (sig != Process.SIGNAL_USR1) {
12886 throw new SecurityException("Only SIGNAL_USR1 is allowed");
12887 }
12888
12889 synchronized (this) {
12890 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
12891 != PackageManager.PERMISSION_GRANTED) {
12892 throw new SecurityException("Requires permission "
12893 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
12894 }
12895
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012896 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12897 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012898 if (r.thread != null && r.persistent) {
12899 Process.sendSignal(r.pid, sig);
12900 }
12901 }
12902 }
12903 }
12904
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012905 public boolean profileControl(String process, boolean start,
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012906 String path, ParcelFileDescriptor fd) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012907
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012908 try {
12909 synchronized (this) {
12910 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
12911 // its own permission.
12912 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
12913 != PackageManager.PERMISSION_GRANTED) {
12914 throw new SecurityException("Requires permission "
12915 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012916 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012917
12918 if (start && fd == null) {
12919 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012920 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012921
12922 ProcessRecord proc = null;
12923 try {
12924 int pid = Integer.parseInt(process);
12925 synchronized (mPidsSelfLocked) {
12926 proc = mPidsSelfLocked.get(pid);
12927 }
12928 } catch (NumberFormatException e) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012929 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012930
12931 if (proc == null) {
12932 HashMap<String, SparseArray<ProcessRecord>> all
12933 = mProcessNames.getMap();
12934 SparseArray<ProcessRecord> procs = all.get(process);
12935 if (procs != null && procs.size() > 0) {
12936 proc = procs.valueAt(0);
12937 }
12938 }
12939
12940 if (proc == null || proc.thread == null) {
12941 throw new IllegalArgumentException("Unknown process: " + process);
12942 }
12943
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080012944 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
12945 if (!isDebuggable) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012946 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
12947 throw new SecurityException("Process not debuggable: " + proc);
12948 }
12949 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012950
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012951 proc.thread.profilerControl(start, path, fd);
12952 fd = null;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012953 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012954 }
12955 } catch (RemoteException e) {
12956 throw new IllegalStateException("Process disappeared");
12957 } finally {
12958 if (fd != null) {
12959 try {
12960 fd.close();
12961 } catch (IOException e) {
12962 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012963 }
12964 }
12965 }
Andy McFadden824c5102010-07-09 16:26:57 -070012966
12967 public boolean dumpHeap(String process, boolean managed,
12968 String path, ParcelFileDescriptor fd) throws RemoteException {
12969
12970 try {
12971 synchronized (this) {
12972 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
12973 // its own permission (same as profileControl).
12974 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
12975 != PackageManager.PERMISSION_GRANTED) {
12976 throw new SecurityException("Requires permission "
12977 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
12978 }
12979
12980 if (fd == null) {
12981 throw new IllegalArgumentException("null fd");
12982 }
12983
12984 ProcessRecord proc = null;
12985 try {
12986 int pid = Integer.parseInt(process);
12987 synchronized (mPidsSelfLocked) {
12988 proc = mPidsSelfLocked.get(pid);
12989 }
12990 } catch (NumberFormatException e) {
12991 }
12992
12993 if (proc == null) {
12994 HashMap<String, SparseArray<ProcessRecord>> all
12995 = mProcessNames.getMap();
12996 SparseArray<ProcessRecord> procs = all.get(process);
12997 if (procs != null && procs.size() > 0) {
12998 proc = procs.valueAt(0);
12999 }
13000 }
13001
13002 if (proc == null || proc.thread == null) {
13003 throw new IllegalArgumentException("Unknown process: " + process);
13004 }
13005
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013006 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13007 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013008 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13009 throw new SecurityException("Process not debuggable: " + proc);
13010 }
13011 }
13012
13013 proc.thread.dumpHeap(managed, path, fd);
13014 fd = null;
13015 return true;
13016 }
13017 } catch (RemoteException e) {
13018 throw new IllegalStateException("Process disappeared");
13019 } finally {
13020 if (fd != null) {
13021 try {
13022 fd.close();
13023 } catch (IOException e) {
13024 }
13025 }
13026 }
13027 }
13028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013029 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13030 public void monitor() {
13031 synchronized (this) { }
13032 }
13033}