blob: b308f697dc5a611830a941e61f885cc7cbd06f64 [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;
27import com.android.server.WindowManagerService;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070028import com.android.server.am.ActivityStack.ActivityState;
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;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700132import java.net.InetSocketAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133import java.util.ArrayList;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700134import java.util.Collections;
135import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.util.HashMap;
137import java.util.HashSet;
138import java.util.Iterator;
139import java.util.List;
140import java.util.Locale;
141import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700142import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700143import java.util.concurrent.atomic.AtomicBoolean;
144import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700146public final class ActivityManagerService extends ActivityManagerNative
147 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 static final String TAG = "ActivityManager";
149 static final boolean DEBUG = false;
150 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
151 static final boolean DEBUG_SWITCH = localLOGV || false;
152 static final boolean DEBUG_TASKS = localLOGV || false;
153 static final boolean DEBUG_PAUSE = localLOGV || false;
154 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
155 static final boolean DEBUG_TRANSITION = localLOGV || false;
156 static final boolean DEBUG_BROADCAST = localLOGV || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700157 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700159 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 static final boolean DEBUG_VISBILITY = localLOGV || false;
161 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700162 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800163 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700165 static final boolean DEBUG_RESULTS = localLOGV || false;
Christopher Tate436344a2009-09-30 16:17:37 -0700166 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700167 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700168 static final boolean DEBUG_POWER = localLOGV || false;
169 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 static final boolean VALIDATE_TOKENS = false;
171 static final boolean SHOW_ACTIVITY_START_TIME = true;
172
173 // Control over CPU and battery monitoring.
174 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
175 static final boolean MONITOR_CPU_USAGE = true;
176 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
177 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
178 static final boolean MONITOR_THREAD_CPU_USAGE = false;
179
Dianne Hackborn1655be42009-05-08 14:29:01 -0700180 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700181 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 private static final String SYSTEM_SECURE = "ro.secure";
184
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();
1328 m.mContext = context;
1329 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001330 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331
1332 m.mBatteryStatsService.publish(context);
1333 m.mUsageStatsService.publish(context);
1334
1335 synchronized (thr) {
1336 thr.mReady = true;
1337 thr.notifyAll();
1338 }
1339
1340 m.startRunning(null, null, null, null);
1341
1342 return context;
1343 }
1344
1345 public static ActivityManagerService self() {
1346 return mSelf;
1347 }
1348
1349 static class AThread extends Thread {
1350 ActivityManagerService mService;
1351 boolean mReady = false;
1352
1353 public AThread() {
1354 super("ActivityManager");
1355 }
1356
1357 public void run() {
1358 Looper.prepare();
1359
1360 android.os.Process.setThreadPriority(
1361 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001362 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363
1364 ActivityManagerService m = new ActivityManagerService();
1365
1366 synchronized (this) {
1367 mService = m;
1368 notifyAll();
1369 }
1370
1371 synchronized (this) {
1372 while (!mReady) {
1373 try {
1374 wait();
1375 } catch (InterruptedException e) {
1376 }
1377 }
1378 }
1379
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001380 // For debug builds, log event loop stalls to dropbox for analysis.
1381 if (StrictMode.conditionallyEnableDebugLogging()) {
1382 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1383 }
1384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 Looper.loop();
1386 }
1387 }
1388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 static class MemBinder extends Binder {
1390 ActivityManagerService mActivityManagerService;
1391 MemBinder(ActivityManagerService activityManagerService) {
1392 mActivityManagerService = activityManagerService;
1393 }
1394
1395 @Override
1396 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1397 ActivityManagerService service = mActivityManagerService;
1398 ArrayList<ProcessRecord> procs;
1399 synchronized (mActivityManagerService) {
1400 if (args != null && args.length > 0
1401 && args[0].charAt(0) != '-') {
1402 procs = new ArrayList<ProcessRecord>();
1403 int pid = -1;
1404 try {
1405 pid = Integer.parseInt(args[0]);
1406 } catch (NumberFormatException e) {
1407
1408 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001409 for (int i=service.mLruProcesses.size()-1; i>=0; i--) {
1410 ProcessRecord proc = service.mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 if (proc.pid == pid) {
1412 procs.add(proc);
1413 } else if (proc.processName.equals(args[0])) {
1414 procs.add(proc);
1415 }
1416 }
1417 if (procs.size() <= 0) {
1418 pw.println("No process found for: " + args[0]);
1419 return;
1420 }
1421 } else {
Dianne Hackborn472ad872010-04-07 17:31:48 -07001422 procs = new ArrayList<ProcessRecord>(service.mLruProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
1424 }
1425 dumpApplicationMemoryUsage(fd, pw, procs, " ", args);
1426 }
1427 }
1428
1429 static class CpuBinder extends Binder {
1430 ActivityManagerService mActivityManagerService;
1431 CpuBinder(ActivityManagerService activityManagerService) {
1432 mActivityManagerService = activityManagerService;
1433 }
1434
1435 @Override
1436 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1437 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001438 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1439 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1440 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 }
1442 }
1443 }
1444
1445 private ActivityManagerService() {
1446 String v = System.getenv("ANDROID_SIMPLE_PROCESS_MANAGEMENT");
1447 if (v != null && Integer.getInteger(v) != 0) {
1448 mSimpleProcessManagement = true;
1449 }
1450 v = System.getenv("ANDROID_DEBUG_APP");
1451 if (v != null) {
1452 mSimpleProcessManagement = true;
1453 }
1454
Joe Onorato8a9b2202010-02-26 18:56:32 -08001455 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 File dataDir = Environment.getDataDirectory();
1458 File systemDir = new File(dataDir, "system");
1459 systemDir.mkdirs();
1460 mBatteryStatsService = new BatteryStatsService(new File(
1461 systemDir, "batterystats.bin").toString());
1462 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001463 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001464 mOnBattery = DEBUG_POWER ? true
1465 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001466 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001468 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001469 systemDir, "usagestats").toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470
Jack Palevichb90d28c2009-07-22 15:35:24 -07001471 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1472 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1473
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001474 mConfiguration.setToDefaults();
1475 mConfiguration.locale = Locale.getDefault();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 mProcessStats.init();
1477
1478 // Add ourself to the Watchdog monitors.
1479 Watchdog.getInstance().addMonitor(this);
1480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 mProcessStatsThread = new Thread("ProcessStats") {
1482 public void run() {
1483 while (true) {
1484 try {
1485 try {
1486 synchronized(this) {
1487 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001488 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001490 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 // + ", write delay=" + nextWriteDelay);
1492 if (nextWriteDelay < nextCpuDelay) {
1493 nextCpuDelay = nextWriteDelay;
1494 }
1495 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001496 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 this.wait(nextCpuDelay);
1498 }
1499 }
1500 } catch (InterruptedException e) {
1501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 updateCpuStatsNow();
1503 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001504 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 }
1506 }
1507 }
1508 };
1509 mProcessStatsThread.start();
1510 }
1511
1512 @Override
1513 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1514 throws RemoteException {
1515 try {
1516 return super.onTransact(code, data, reply, flags);
1517 } catch (RuntimeException e) {
1518 // The activity manager only throws security exceptions, so let's
1519 // log all others.
1520 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001521 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 }
1523 throw e;
1524 }
1525 }
1526
1527 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001528 final long now = SystemClock.uptimeMillis();
1529 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1530 return;
1531 }
1532 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1533 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 mProcessStatsThread.notify();
1535 }
1536 }
1537 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 void updateCpuStatsNow() {
1540 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001541 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 final long now = SystemClock.uptimeMillis();
1543 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001546 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1547 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 haveNewCpuStats = true;
1549 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001550 //Slog.i(TAG, mProcessStats.printCurrentState());
1551 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 // + mProcessStats.getTotalCpuPercent() + "%");
1553
Joe Onorato8a9b2202010-02-26 18:56:32 -08001554 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 if ("true".equals(SystemProperties.get("events.cpu"))) {
1556 int user = mProcessStats.getLastUserTime();
1557 int system = mProcessStats.getLastSystemTime();
1558 int iowait = mProcessStats.getLastIoWaitTime();
1559 int irq = mProcessStats.getLastIrqTime();
1560 int softIrq = mProcessStats.getLastSoftIrqTime();
1561 int idle = mProcessStats.getLastIdleTime();
1562
1563 int total = user + system + iowait + irq + softIrq + idle;
1564 if (total == 0) total = 1;
1565
Doug Zongker2bec3d42009-12-04 12:52:44 -08001566 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 ((user+system+iowait+irq+softIrq) * 100) / total,
1568 (user * 100) / total,
1569 (system * 100) / total,
1570 (iowait * 100) / total,
1571 (irq * 100) / total,
1572 (softIrq * 100) / total);
1573 }
1574 }
1575
Amith Yamasanie43530a2009-08-21 13:11:37 -07001576 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001577 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001578 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 synchronized(mPidsSelfLocked) {
1580 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001581 if (mOnBattery) {
1582 int perc = bstats.startAddingCpuLocked();
1583 int totalUTime = 0;
1584 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001585 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001587 ProcessStats.Stats st = mProcessStats.getStats(i);
1588 if (!st.working) {
1589 continue;
1590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001592 int otherUTime = (st.rel_utime*perc)/100;
1593 int otherSTime = (st.rel_stime*perc)/100;
1594 totalUTime += otherUTime;
1595 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 if (pr != null) {
1597 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001598 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1599 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001600 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001601 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001602 } else {
1603 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001604 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001605 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001606 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1607 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001608 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 }
1611 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001612 bstats.finishAddingCpuLocked(perc, totalUTime,
1613 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 }
1615 }
1616 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1619 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001620 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 }
1622 }
1623 }
1624 }
1625
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001626 @Override
1627 public void batteryNeedsCpuUpdate() {
1628 updateCpuStatsNow();
1629 }
1630
1631 @Override
1632 public void batteryPowerChanged(boolean onBattery) {
1633 // When plugging in, update the CPU stats first before changing
1634 // the plug state.
1635 updateCpuStatsNow();
1636 synchronized (this) {
1637 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001638 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001639 }
1640 }
1641 }
1642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 /**
1644 * Initialize the application bind args. These are passed to each
1645 * process when the bindApplication() IPC is sent to the process. They're
1646 * lazily setup to make sure the services are running when they're asked for.
1647 */
1648 private HashMap<String, IBinder> getCommonServicesLocked() {
1649 if (mAppBindArgs == null) {
1650 mAppBindArgs = new HashMap<String, IBinder>();
1651
1652 // Setup the application init args
1653 mAppBindArgs.put("package", ServiceManager.getService("package"));
1654 mAppBindArgs.put("window", ServiceManager.getService("window"));
1655 mAppBindArgs.put(Context.ALARM_SERVICE,
1656 ServiceManager.getService(Context.ALARM_SERVICE));
1657 }
1658 return mAppBindArgs;
1659 }
1660
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001661 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 if (mFocusedActivity != r) {
1663 mFocusedActivity = r;
1664 mWindowManager.setFocusedApp(r, true);
1665 }
1666 }
1667
Dianne Hackborn906497c2010-05-10 15:57:38 -07001668 private final void updateLruProcessInternalLocked(ProcessRecord app,
1669 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001671 int lrui = mLruProcesses.indexOf(app);
1672 if (lrui >= 0) mLruProcesses.remove(lrui);
1673
1674 int i = mLruProcesses.size()-1;
1675 int skipTop = 0;
1676
Dianne Hackborn906497c2010-05-10 15:57:38 -07001677 app.lruSeq = mLruSeq;
1678
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001679 // compute the new weight for this process.
1680 if (updateActivityTime) {
1681 app.lastActivityTime = SystemClock.uptimeMillis();
1682 }
1683 if (app.activities.size() > 0) {
1684 // If this process has activities, we more strongly want to keep
1685 // it around.
1686 app.lruWeight = app.lastActivityTime;
1687 } else if (app.pubProviders.size() > 0) {
1688 // If this process contains content providers, we want to keep
1689 // it a little more strongly.
1690 app.lruWeight = app.lastActivityTime - CONTENT_APP_IDLE_OFFSET;
1691 // Also don't let it kick out the first few "real" hidden processes.
1692 skipTop = MIN_HIDDEN_APPS;
1693 } else {
1694 // If this process doesn't have activities, we less strongly
1695 // want to keep it around, and generally want to avoid getting
1696 // in front of any very recently used activities.
1697 app.lruWeight = app.lastActivityTime - EMPTY_APP_IDLE_OFFSET;
1698 // Also don't let it kick out the first few "real" hidden processes.
1699 skipTop = MIN_HIDDEN_APPS;
1700 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001701
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001702 while (i >= 0) {
1703 ProcessRecord p = mLruProcesses.get(i);
1704 // If this app shouldn't be in front of the first N background
1705 // apps, then skip over that many that are currently hidden.
1706 if (skipTop > 0 && p.setAdj >= HIDDEN_APP_MIN_ADJ) {
1707 skipTop--;
1708 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001709 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001710 mLruProcesses.add(i+1, app);
1711 break;
1712 }
1713 i--;
1714 }
1715 if (i < 0) {
1716 mLruProcesses.add(0, app);
1717 }
1718
Dianne Hackborn906497c2010-05-10 15:57:38 -07001719 // If the app is currently using a content provider or service,
1720 // bump those processes as well.
1721 if (app.connections.size() > 0) {
1722 for (ConnectionRecord cr : app.connections) {
1723 if (cr.binding != null && cr.binding.service != null
1724 && cr.binding.service.app != null
1725 && cr.binding.service.app.lruSeq != mLruSeq) {
1726 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1727 updateActivityTime, i+1);
1728 }
1729 }
1730 }
1731 if (app.conProviders.size() > 0) {
1732 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
1733 if (cpr.app != null && cpr.app.lruSeq != mLruSeq) {
1734 updateLruProcessInternalLocked(cpr.app, oomAdj,
1735 updateActivityTime, i+1);
1736 }
1737 }
1738 }
1739
Joe Onorato8a9b2202010-02-26 18:56:32 -08001740 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 if (oomAdj) {
1742 updateOomAdjLocked();
1743 }
1744 }
1745
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001746 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001747 boolean oomAdj, boolean updateActivityTime) {
1748 mLruSeq++;
1749 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1750 }
1751
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001752 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 String processName, int uid) {
1754 if (uid == Process.SYSTEM_UID) {
1755 // The system gets to run in any process. If there are multiple
1756 // processes with the same uid, just pick the first (this
1757 // should never happen).
1758 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1759 processName);
1760 return procs != null ? procs.valueAt(0) : null;
1761 }
1762 ProcessRecord proc = mProcessNames.get(processName, uid);
1763 return proc;
1764 }
1765
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001766 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001767 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001768 try {
1769 if (pm.performDexOpt(packageName)) {
1770 mDidDexOpt = true;
1771 }
1772 } catch (RemoteException e) {
1773 }
1774 }
1775
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001776 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 int transit = mWindowManager.getPendingAppTransition();
1778 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1779 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1780 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1781 }
1782
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001783 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001785 String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 ProcessRecord app = getProcessRecordLocked(processName, info.uid);
1787 // We don't have to do anything more if:
1788 // (1) There is an existing application record; and
1789 // (2) The caller doesn't think it is dead, OR there is no thread
1790 // object attached to it so we know it couldn't have crashed; and
1791 // (3) There is a pid assigned to it, so it is either starting or
1792 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001793 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 + " app=" + app + " knownToBeDead=" + knownToBeDead
1795 + " thread=" + (app != null ? app.thread : null)
1796 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001797 if (app != null && app.pid > 0) {
1798 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001799 // We already have the app running, or are waiting for it to
1800 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001801 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001802 return app;
1803 } else {
1804 // An application record is attached to a previous process,
1805 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001806 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001807 handleAppDiedLocked(app, true);
1808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 String hostingNameStr = hostingName != null
1812 ? hostingName.flattenToShortString() : null;
1813
1814 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1815 // If we are in the background, then check to see if this process
1816 // is bad. If so, we will just silently fail.
1817 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001818 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1819 + "/" + info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 return null;
1821 }
1822 } else {
1823 // When the user is explicitly starting a process, then clear its
1824 // crash count so that we won't make it bad until they see at
1825 // least one crash dialog again, and make the process good again
1826 // if it had been bad.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001827 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
1828 + "/" + info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 mProcessCrashTimes.remove(info.processName, info.uid);
1830 if (mBadProcesses.get(info.processName, info.uid) != null) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08001831 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 info.processName);
1833 mBadProcesses.remove(info.processName, info.uid);
1834 if (app != null) {
1835 app.bad = false;
1836 }
1837 }
1838 }
1839
1840 if (app == null) {
1841 app = newProcessRecordLocked(null, info, processName);
1842 mProcessNames.put(processName, info.uid, app);
1843 } else {
1844 // If this is a new package in the process, add the package to the list
1845 app.addPackage(info.packageName);
1846 }
1847
1848 // If the system is not ready yet, then hold off on starting this
1849 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001850 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001851 && !isAllowedWhileBooting(info)
1852 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 if (!mProcessesOnHold.contains(app)) {
1854 mProcessesOnHold.add(app);
1855 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001856 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 return app;
1858 }
1859
1860 startProcessLocked(app, hostingType, hostingNameStr);
1861 return (app.pid != 0) ? app : null;
1862 }
1863
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001864 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1865 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1866 }
1867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 private final void startProcessLocked(ProcessRecord app,
1869 String hostingType, String hostingNameStr) {
1870 if (app.pid > 0 && app.pid != MY_PID) {
1871 synchronized (mPidsSelfLocked) {
1872 mPidsSelfLocked.remove(app.pid);
1873 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1874 }
1875 app.pid = 0;
1876 }
1877
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001878 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1879 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 mProcessesOnHold.remove(app);
1881
1882 updateCpuStats();
1883
1884 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1885 mProcDeaths[0] = 0;
1886
1887 try {
1888 int uid = app.info.uid;
1889 int[] gids = null;
1890 try {
1891 gids = mContext.getPackageManager().getPackageGids(
1892 app.info.packageName);
1893 } catch (PackageManager.NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001894 Slog.w(TAG, "Unable to retrieve gids", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 }
1896 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1897 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1898 && mTopComponent != null
1899 && app.processName.equals(mTopComponent.getPackageName())) {
1900 uid = 0;
1901 }
1902 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1903 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1904 uid = 0;
1905 }
1906 }
1907 int debugFlags = 0;
1908 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1909 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
1910 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001911 // Run the app in safe mode if its manifest requests so or the
1912 // system is booted in safe mode.
1913 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1914 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001915 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1918 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1919 }
1920 if ("1".equals(SystemProperties.get("debug.assert"))) {
1921 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1922 }
1923 int pid = Process.start("android.app.ActivityThread",
1924 mSimpleProcessManagement ? app.processName : null, uid, uid,
1925 gids, debugFlags, null);
1926 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1927 synchronized (bs) {
1928 if (bs.isOnBattery()) {
1929 app.batteryStats.incStartsLocked();
1930 }
1931 }
1932
Doug Zongker2bec3d42009-12-04 12:52:44 -08001933 EventLog.writeEvent(EventLogTags.AM_PROC_START, pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 app.processName, hostingType,
1935 hostingNameStr != null ? hostingNameStr : "");
1936
1937 if (app.persistent) {
Christopher Tatec27181c2010-06-30 14:41:09 -07001938 Watchdog.getInstance().processStarted(app.processName, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 }
1940
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07001941 StringBuilder buf = mStringBuilder;
1942 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 buf.append("Start proc ");
1944 buf.append(app.processName);
1945 buf.append(" for ");
1946 buf.append(hostingType);
1947 if (hostingNameStr != null) {
1948 buf.append(" ");
1949 buf.append(hostingNameStr);
1950 }
1951 buf.append(": pid=");
1952 buf.append(pid);
1953 buf.append(" uid=");
1954 buf.append(uid);
1955 buf.append(" gids={");
1956 if (gids != null) {
1957 for (int gi=0; gi<gids.length; gi++) {
1958 if (gi != 0) buf.append(", ");
1959 buf.append(gids[gi]);
1960
1961 }
1962 }
1963 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001964 Slog.i(TAG, buf.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 if (pid == 0 || pid == MY_PID) {
1966 // Processes are being emulated with threads.
1967 app.pid = MY_PID;
1968 app.removed = false;
1969 mStartingProcesses.add(app);
1970 } else if (pid > 0) {
1971 app.pid = pid;
1972 app.removed = false;
1973 synchronized (mPidsSelfLocked) {
1974 this.mPidsSelfLocked.put(pid, app);
1975 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1976 msg.obj = app;
1977 mHandler.sendMessageDelayed(msg, PROC_START_TIMEOUT);
1978 }
1979 } else {
1980 app.pid = 0;
1981 RuntimeException e = new RuntimeException(
1982 "Failure starting process " + app.processName
1983 + ": returned pid=" + pid);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001984 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 }
1986 } catch (RuntimeException e) {
1987 // XXX do better error recovery.
1988 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001989 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
1991 }
1992
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001993 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 if (resumed) {
1995 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
1996 } else {
1997 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
1998 }
1999 }
2000
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002001 boolean startHomeActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002002 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2003 && mTopAction == null) {
2004 // We are running in factory test mode, but unable to find
2005 // the factory test app, so just sit around displaying the
2006 // error message and don't try to start anything.
2007 return false;
2008 }
2009 Intent intent = new Intent(
2010 mTopAction,
2011 mTopData != null ? Uri.parse(mTopData) : null);
2012 intent.setComponent(mTopComponent);
2013 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2014 intent.addCategory(Intent.CATEGORY_HOME);
2015 }
2016 ActivityInfo aInfo =
2017 intent.resolveActivityInfo(mContext.getPackageManager(),
2018 STOCK_PM_FLAGS);
2019 if (aInfo != null) {
2020 intent.setComponent(new ComponentName(
2021 aInfo.applicationInfo.packageName, aInfo.name));
2022 // Don't do this if the home app is currently being
2023 // instrumented.
2024 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2025 aInfo.applicationInfo.uid);
2026 if (app == null || app.instrumentationClass == null) {
2027 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002028 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002029 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002030 }
2031 }
2032
2033
2034 return true;
2035 }
2036
2037 /**
2038 * Starts the "new version setup screen" if appropriate.
2039 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002040 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002041 // Only do this once per boot.
2042 if (mCheckedForSetup) {
2043 return;
2044 }
2045
2046 // We will show this screen if the current one is a different
2047 // version than the last one shown, and we are not running in
2048 // low-level factory test mode.
2049 final ContentResolver resolver = mContext.getContentResolver();
2050 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2051 Settings.Secure.getInt(resolver,
2052 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2053 mCheckedForSetup = true;
2054
2055 // See if we should be showing the platform update setup UI.
2056 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2057 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2058 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2059
2060 // We don't allow third party apps to replace this.
2061 ResolveInfo ri = null;
2062 for (int i=0; ris != null && i<ris.size(); i++) {
2063 if ((ris.get(i).activityInfo.applicationInfo.flags
2064 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2065 ri = ris.get(i);
2066 break;
2067 }
2068 }
2069
2070 if (ri != null) {
2071 String vers = ri.activityInfo.metaData != null
2072 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2073 : null;
2074 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2075 vers = ri.activityInfo.applicationInfo.metaData.getString(
2076 Intent.METADATA_SETUP_VERSION);
2077 }
2078 String lastVers = Settings.Secure.getString(
2079 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2080 if (vers != null && !vers.equals(lastVers)) {
2081 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2082 intent.setComponent(new ComponentName(
2083 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002084 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002085 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002086 }
2087 }
2088 }
2089 }
2090
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002091 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002092 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002093
2094 final int identHash = System.identityHashCode(r);
2095 updateUsageStats(r, true);
2096
2097 int i = mWatchers.beginBroadcast();
2098 while (i > 0) {
2099 i--;
2100 IActivityWatcher w = mWatchers.getBroadcastItem(i);
2101 if (w != null) {
2102 try {
2103 w.activityResuming(identHash);
2104 } catch (RemoteException e) {
2105 }
2106 }
2107 }
2108 mWatchers.finishBroadcast();
2109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002111 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002112 final int N = mPendingActivityLaunches.size();
2113 if (N <= 0) {
2114 return;
2115 }
2116 for (int i=0; i<N; i++) {
2117 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002118 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002119 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
2120 doResume && i == (N-1));
2121 }
2122 mPendingActivityLaunches.clear();
2123 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002124
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002125 public final int startActivity(IApplicationThread caller,
2126 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2127 int grantedMode, IBinder resultTo,
2128 String resultWho, int requestCode, boolean onlyIfNeeded,
2129 boolean debug) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002130 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002131 grantedUriPermissions, grantedMode, resultTo, resultWho,
2132 requestCode, onlyIfNeeded, debug, null, null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002133 }
2134
2135 public final WaitResult startActivityAndWait(IApplicationThread caller,
2136 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2137 int grantedMode, IBinder resultTo,
2138 String resultWho, int requestCode, boolean onlyIfNeeded,
2139 boolean debug) {
2140 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002141 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002142 grantedUriPermissions, grantedMode, resultTo, resultWho,
2143 requestCode, onlyIfNeeded, debug, res, null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002144 return res;
2145 }
2146
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002147 public final int startActivityWithConfig(IApplicationThread caller,
2148 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2149 int grantedMode, IBinder resultTo,
2150 String resultWho, int requestCode, boolean onlyIfNeeded,
2151 boolean debug, Configuration config) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002152 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002153 grantedUriPermissions, grantedMode, resultTo, resultWho,
2154 requestCode, onlyIfNeeded, debug, null, config);
2155 }
2156
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002157 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002158 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002159 IBinder resultTo, String resultWho, int requestCode,
2160 int flagsMask, int flagsValues) {
2161 // Refuse possible leaked file descriptors
2162 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2163 throw new IllegalArgumentException("File descriptors passed in Intent");
2164 }
2165
2166 IIntentSender sender = intent.getTarget();
2167 if (!(sender instanceof PendingIntentRecord)) {
2168 throw new IllegalArgumentException("Bad PendingIntent object");
2169 }
2170
2171 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002172
2173 synchronized (this) {
2174 // If this is coming from the currently resumed activity, it is
2175 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002176 if (mMainStack.mResumedActivity != null
2177 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002178 Binder.getCallingUid()) {
2179 mAppSwitchesAllowedTime = 0;
2180 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002181 }
2182
2183 return pir.sendInner(0, fillInIntent, resolvedType,
2184 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
2185 }
2186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 public boolean startNextMatchingActivity(IBinder callingActivity,
2188 Intent intent) {
2189 // Refuse possible leaked file descriptors
2190 if (intent != null && intent.hasFileDescriptors() == true) {
2191 throw new IllegalArgumentException("File descriptors passed in Intent");
2192 }
2193
2194 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002195 int index = mMainStack.indexOfTokenLocked(callingActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 if (index < 0) {
2197 return false;
2198 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002199 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 if (r.app == null || r.app.thread == null) {
2201 // The caller is not running... d'oh!
2202 return false;
2203 }
2204 intent = new Intent(intent);
2205 // The caller is not allowed to change the data.
2206 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2207 // And we are resetting to find the next component...
2208 intent.setComponent(null);
2209
2210 ActivityInfo aInfo = null;
2211 try {
2212 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002213 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002215 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216
2217 // Look for the original activity in the list...
2218 final int N = resolves != null ? resolves.size() : 0;
2219 for (int i=0; i<N; i++) {
2220 ResolveInfo rInfo = resolves.get(i);
2221 if (rInfo.activityInfo.packageName.equals(r.packageName)
2222 && rInfo.activityInfo.name.equals(r.info.name)) {
2223 // We found the current one... the next matching is
2224 // after it.
2225 i++;
2226 if (i<N) {
2227 aInfo = resolves.get(i).activityInfo;
2228 }
2229 break;
2230 }
2231 }
2232 } catch (RemoteException e) {
2233 }
2234
2235 if (aInfo == null) {
2236 // Nobody who is next!
2237 return false;
2238 }
2239
2240 intent.setComponent(new ComponentName(
2241 aInfo.applicationInfo.packageName, aInfo.name));
2242 intent.setFlags(intent.getFlags()&~(
2243 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2244 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2245 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2246 Intent.FLAG_ACTIVITY_NEW_TASK));
2247
2248 // Okay now we need to start the new activity, replacing the
2249 // currently running activity. This is a little tricky because
2250 // we want to start the new one as if the current one is finished,
2251 // but not finish the current one first so that there is no flicker.
2252 // And thus...
2253 final boolean wasFinishing = r.finishing;
2254 r.finishing = true;
2255
2256 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002257 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 final String resultWho = r.resultWho;
2259 final int requestCode = r.requestCode;
2260 r.resultTo = null;
2261 if (resultTo != null) {
2262 resultTo.removeResultsLocked(r, resultWho, requestCode);
2263 }
2264
2265 final long origId = Binder.clearCallingIdentity();
2266 // XXX we are not dealing with propagating grantedUriPermissions...
2267 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002268 int res = mMainStack.startActivityLocked(r.app.thread, intent,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 r.resolvedType, null, 0, aInfo, resultTo, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002270 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 Binder.restoreCallingIdentity(origId);
2272
2273 r.finishing = wasFinishing;
2274 if (res != START_SUCCESS) {
2275 return false;
2276 }
2277 return true;
2278 }
2279 }
2280
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002281 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 Intent intent, String resolvedType, IBinder resultTo,
2283 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002284
2285 // This is so super not safe, that only the system (or okay root)
2286 // can do it.
2287 final int callingUid = Binder.getCallingUid();
2288 if (callingUid != 0 && callingUid != Process.myUid()) {
2289 throw new SecurityException(
2290 "startActivityInPackage only available to the system");
2291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002293 return mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
2294 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false, null, null);
2295 }
2296
2297 public final int startActivities(IApplicationThread caller,
2298 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2299 return mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo);
2300 }
2301
2302 public final int startActivitiesInPackage(int uid,
2303 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2304
2305 // This is so super not safe, that only the system (or okay root)
2306 // can do it.
2307 final int callingUid = Binder.getCallingUid();
2308 if (callingUid != 0 && callingUid != Process.myUid()) {
2309 throw new SecurityException(
2310 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 }
2312
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002313 return mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 }
2315
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002316 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002318 // Quick case: check if the top-most recent task is the same.
2319 if (N > 0 && mRecentTasks.get(0) == task) {
2320 return;
2321 }
2322 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 for (int i=0; i<N; i++) {
2324 TaskRecord tr = mRecentTasks.get(i);
2325 if ((task.affinity != null && task.affinity.equals(tr.affinity))
2326 || (task.intent != null && task.intent.filterEquals(tr.intent))) {
2327 mRecentTasks.remove(i);
2328 i--;
2329 N--;
2330 if (task.intent == null) {
2331 // If the new recent task we are adding is not fully
2332 // specified, then replace it with the existing recent task.
2333 task = tr;
2334 }
2335 }
2336 }
2337 if (N >= MAX_RECENT_TASKS) {
2338 mRecentTasks.remove(N-1);
2339 }
2340 mRecentTasks.add(0, task);
2341 }
2342
2343 public void setRequestedOrientation(IBinder token,
2344 int requestedOrientation) {
2345 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002346 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 if (index < 0) {
2348 return;
2349 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002350 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 final long origId = Binder.clearCallingIdentity();
2352 mWindowManager.setAppOrientation(r, requestedOrientation);
2353 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002354 mConfiguration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 r.mayFreezeScreenLocked(r.app) ? r : null);
2356 if (config != null) {
2357 r.frozenBeforeDestroy = true;
2358 if (!updateConfigurationLocked(config, r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002359 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 }
2361 }
2362 Binder.restoreCallingIdentity(origId);
2363 }
2364 }
2365
2366 public int getRequestedOrientation(IBinder token) {
2367 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002368 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 if (index < 0) {
2370 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2371 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002372 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 return mWindowManager.getAppOrientation(r);
2374 }
2375 }
2376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 /**
2378 * This is the internal entry point for handling Activity.finish().
2379 *
2380 * @param token The Binder token referencing the Activity we want to finish.
2381 * @param resultCode Result code, if any, from this Activity.
2382 * @param resultData Result data (Intent), if any, from this Activity.
2383 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002384 * @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 -08002385 */
2386 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2387 // Refuse possible leaked file descriptors
2388 if (resultData != null && resultData.hasFileDescriptors() == true) {
2389 throw new IllegalArgumentException("File descriptors passed in Intent");
2390 }
2391
2392 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002393 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002395 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 if (next != null) {
2397 // ask watcher if this is allowed
2398 boolean resumeOK = true;
2399 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002400 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002402 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 }
2404
2405 if (!resumeOK) {
2406 return false;
2407 }
2408 }
2409 }
2410 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002411 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 resultData, "app-request");
2413 Binder.restoreCallingIdentity(origId);
2414 return res;
2415 }
2416 }
2417
Dianne Hackborn860755f2010-06-03 18:47:52 -07002418 public final void finishHeavyWeightApp() {
2419 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2420 != PackageManager.PERMISSION_GRANTED) {
2421 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2422 + Binder.getCallingPid()
2423 + ", uid=" + Binder.getCallingUid()
2424 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2425 Slog.w(TAG, msg);
2426 throw new SecurityException(msg);
2427 }
2428
2429 synchronized(this) {
2430 if (mHeavyWeightProcess == null) {
2431 return;
2432 }
2433
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002434 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002435 mHeavyWeightProcess.activities);
2436 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002437 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002438 if (!r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002439 int index = mMainStack.indexOfTokenLocked(r);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002440 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002441 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002442 null, "finish-heavy");
2443 }
2444 }
2445 }
2446
2447 mHeavyWeightProcess = null;
2448 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2449 }
2450 }
2451
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002452 public void crashApplication(int uid, int initialPid, String packageName,
2453 String message) {
2454 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2455 != PackageManager.PERMISSION_GRANTED) {
2456 String msg = "Permission Denial: crashApplication() from pid="
2457 + Binder.getCallingPid()
2458 + ", uid=" + Binder.getCallingUid()
2459 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2460 Slog.w(TAG, msg);
2461 throw new SecurityException(msg);
2462 }
2463
2464 synchronized(this) {
2465 ProcessRecord proc = null;
2466
2467 // Figure out which process to kill. We don't trust that initialPid
2468 // still has any relation to current pids, so must scan through the
2469 // list.
2470 synchronized (mPidsSelfLocked) {
2471 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2472 ProcessRecord p = mPidsSelfLocked.valueAt(i);
2473 if (p.info.uid != uid) {
2474 continue;
2475 }
2476 if (p.pid == initialPid) {
2477 proc = p;
2478 break;
2479 }
2480 for (String str : p.pkgList) {
2481 if (str.equals(packageName)) {
2482 proc = p;
2483 }
2484 }
2485 }
2486 }
2487
2488 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002489 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002490 + " initialPid=" + initialPid
2491 + " packageName=" + packageName);
2492 return;
2493 }
2494
2495 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002496 if (proc.pid == Process.myPid()) {
2497 Log.w(TAG, "crashApplication: trying to crash self!");
2498 return;
2499 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002500 long ident = Binder.clearCallingIdentity();
2501 try {
2502 proc.thread.scheduleCrash(message);
2503 } catch (RemoteException e) {
2504 }
2505 Binder.restoreCallingIdentity(ident);
2506 }
2507 }
2508 }
2509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 public final void finishSubActivity(IBinder token, String resultWho,
2511 int requestCode) {
2512 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002513 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 if (index < 0) {
2515 return;
2516 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002517 ActivityRecord self = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518
2519 final long origId = Binder.clearCallingIdentity();
2520
2521 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002522 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2523 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 if (r.resultTo == self && r.requestCode == requestCode) {
2525 if ((r.resultWho == null && resultWho == null) ||
2526 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002527 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 Activity.RESULT_CANCELED, null, "request-sub");
2529 }
2530 }
2531 }
2532
2533 Binder.restoreCallingIdentity(origId);
2534 }
2535 }
2536
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002537 public boolean willActivityBeVisible(IBinder token) {
2538 synchronized(this) {
2539 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002540 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2541 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002542 if (r == token) {
2543 return true;
2544 }
2545 if (r.fullscreen && !r.finishing) {
2546 return false;
2547 }
2548 }
2549 return true;
2550 }
2551 }
2552
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002553 public void overridePendingTransition(IBinder token, String packageName,
2554 int enterAnim, int exitAnim) {
2555 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002556 int index = mMainStack.indexOfTokenLocked(token);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002557 if (index < 0) {
2558 return;
2559 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002560 ActivityRecord self = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002561
2562 final long origId = Binder.clearCallingIdentity();
2563
2564 if (self.state == ActivityState.RESUMED
2565 || self.state == ActivityState.PAUSING) {
2566 mWindowManager.overridePendingAppTransition(packageName,
2567 enterAnim, exitAnim);
2568 }
2569
2570 Binder.restoreCallingIdentity(origId);
2571 }
2572 }
2573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 * Main function for removing an existing process from the activity manager
2576 * as a result of that process going away. Clears out all connections
2577 * to the process.
2578 */
2579 private final void handleAppDiedLocked(ProcessRecord app,
2580 boolean restarting) {
2581 cleanUpApplicationRecordLocked(app, restarting, -1);
2582 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002583 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 }
2585
2586 // Just in case...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002587 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2588 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2589 mMainStack.mPausingActivity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002591 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2592 mMainStack.mLastPausedActivity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 }
2594
2595 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002596 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597
2598 boolean atTop = true;
2599 boolean hasVisibleActivities = false;
2600
2601 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002602 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002603 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 TAG, "Removing app " + app + " from history with " + i + " entries");
2605 while (i > 0) {
2606 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002607 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002608 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2610 if (r.app == app) {
2611 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002612 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 TAG, "Removing this entry! frozen=" + r.haveState
2614 + " finishing=" + r.finishing);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002615 mMainStack.mHistory.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616
2617 r.inHistory = false;
2618 mWindowManager.removeAppToken(r);
2619 if (VALIDATE_TOKENS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002620 mWindowManager.validateAppTokens(mMainStack.mHistory);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002622 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623
2624 } else {
2625 // We have the current state for this activity, so
2626 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002627 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 TAG, "Keeping entry, setting app to null");
2629 if (r.visible) {
2630 hasVisibleActivities = true;
2631 }
2632 r.app = null;
2633 r.nowVisible = false;
2634 if (!r.haveState) {
2635 r.icicle = null;
2636 }
2637 }
2638
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002639 r.stack.cleanUpActivityLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 r.state = ActivityState.STOPPED;
2641 }
2642 atTop = false;
2643 }
2644
2645 app.activities.clear();
2646
2647 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002648 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 + " running instrumentation " + app.instrumentationClass);
2650 Bundle info = new Bundle();
2651 info.putString("shortMsg", "Process crashed.");
2652 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2653 }
2654
2655 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002656 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 // If there was nothing to resume, and we are not already
2658 // restarting this process, but there is a visible activity that
2659 // is hosted by the process... then make sure all visible
2660 // activities are running, taking care of restarting this
2661 // process.
2662 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002663 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 }
2665 }
2666 }
2667 }
2668
2669 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2670 IBinder threadBinder = thread.asBinder();
2671
2672 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002673 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2674 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2676 return i;
2677 }
2678 }
2679 return -1;
2680 }
2681
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002682 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 IApplicationThread thread) {
2684 if (thread == null) {
2685 return null;
2686 }
2687
2688 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002689 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 }
2691
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002692 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 IApplicationThread thread) {
2694
2695 mProcDeaths[0]++;
2696
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002697 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2698 synchronized (stats) {
2699 stats.noteProcessDiedLocked(app.info.uid, pid);
2700 }
2701
Magnus Edlund7bb25812010-02-24 15:45:06 +01002702 // Clean up already done if the process has been re-started.
2703 if (app.pid == pid && app.thread != null &&
2704 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002705 if (!app.killedBackground) {
2706 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2707 + ") has died.");
2708 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002709 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002710 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 TAG, "Dying app: " + app + ", pid: " + pid
2712 + ", thread: " + thread.asBinder());
2713 boolean doLowMem = app.instrumentationClass == null;
2714 handleAppDiedLocked(app, false);
2715
2716 if (doLowMem) {
2717 // If there are no longer any background processes running,
2718 // and the app that died was not running instrumentation,
2719 // then tell everyone we are now low on memory.
2720 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002721 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2722 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 if (rec.thread != null && rec.setAdj >= HIDDEN_APP_MIN_ADJ) {
2724 haveBg = true;
2725 break;
2726 }
2727 }
2728
2729 if (!haveBg) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002730 Slog.i(TAG, "Low Memory: No more background processes.");
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002731 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002732 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002733 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2734 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002735 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002736 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2737 // The low memory report is overriding any current
2738 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002739 // heavy/important/visible/foreground processes first.
2740 if (rec.setAdj <= HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002741 rec.lastRequestedGc = 0;
2742 } else {
2743 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002745 rec.reportLowMemory = true;
2746 rec.lastLowMemory = now;
2747 mProcessesToGc.remove(rec);
2748 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 }
2750 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002751 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 }
2753 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002754 } else if (app.pid != pid) {
2755 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002756 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002757 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002758 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002759 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002760 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 + thread.asBinder());
2762 }
2763 }
2764
Dan Egnor42471dd2010-01-07 17:25:22 -08002765 /**
2766 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002767 * @param clearTraces causes the dump file to be erased prior to the new
2768 * traces being written, if true; when false, the new traces will be
2769 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002770 * @param firstPids of dalvik VM processes to dump stack traces for first
2771 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002772 * @return file containing stack traces, or null if no dump file is configured
2773 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002774 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2775 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002776 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2777 if (tracesPath == null || tracesPath.length() == 0) {
2778 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002780
2781 File tracesFile = new File(tracesPath);
2782 try {
2783 File tracesDir = tracesFile.getParentFile();
2784 if (!tracesDir.exists()) tracesFile.mkdirs();
2785 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2786
Christopher Tate6ee412d2010-05-28 12:01:56 -07002787 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002788 tracesFile.createNewFile();
2789 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2790 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002791 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002792 return null;
2793 }
2794
2795 // Use a FileObserver to detect when traces finish writing.
2796 // The order of traces is considered important to maintain for legibility.
2797 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2798 public synchronized void onEvent(int event, String path) { notify(); }
2799 };
2800
2801 try {
2802 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002803
2804 // First collect all of the stacks of the most important pids.
2805 try {
2806 int num = firstPids.size();
2807 for (int i = 0; i < num; i++) {
2808 synchronized (observer) {
2809 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2810 observer.wait(200); // Wait for write-close, give up after 200msec
2811 }
2812 }
2813 } catch (InterruptedException e) {
2814 Log.wtf(TAG, e);
2815 }
2816
2817 // Next measure CPU usage.
2818 if (processStats != null) {
2819 processStats.init();
2820 System.gc();
2821 processStats.update();
2822 try {
2823 synchronized (processStats) {
2824 processStats.wait(500); // measure over 1/2 second.
2825 }
2826 } catch (InterruptedException e) {
2827 }
2828 processStats.update();
2829
2830 // We'll take the stack crawls of just the top apps using CPU.
2831 final int N = processStats.countWorkingStats();
2832 int numProcs = 0;
2833 for (int i=0; i<N && numProcs<5; i++) {
2834 ProcessStats.Stats stats = processStats.getWorkingStats(i);
2835 if (lastPids.indexOfKey(stats.pid) >= 0) {
2836 numProcs++;
2837 try {
2838 synchronized (observer) {
2839 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
2840 observer.wait(200); // Wait for write-close, give up after 200msec
2841 }
2842 } catch (InterruptedException e) {
2843 Log.wtf(TAG, e);
2844 }
2845
2846 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002847 }
2848 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002849
2850 return tracesFile;
2851
Dan Egnor42471dd2010-01-07 17:25:22 -08002852 } finally {
2853 observer.stopWatching();
2854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 }
2856
Jeff Brown4d94a762010-09-23 11:33:28 -07002857 private final class AppNotResponding implements Runnable {
2858 private final ProcessRecord mApp;
2859 private final String mAnnotation;
2860
2861 public AppNotResponding(ProcessRecord app, String annotation) {
2862 mApp = app;
2863 mAnnotation = annotation;
2864 }
2865
2866 @Override
2867 public void run() {
2868 appNotResponding(mApp, null, null, mAnnotation);
2869 }
2870 }
2871
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002872 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
2873 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002874 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
2875 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
2876
Dianne Hackborn287952c2010-09-22 22:34:31 -07002877 if (mController != null) {
2878 try {
2879 // 0 == continue, -1 = kill process immediately
2880 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
2881 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
2882 } catch (RemoteException e) {
2883 mController = null;
2884 }
2885 }
2886
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002887 long anrTime = SystemClock.uptimeMillis();
2888 if (MONITOR_CPU_USAGE) {
2889 updateCpuStatsNow();
2890 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002891
2892 synchronized (this) {
2893 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
2894 if (mShuttingDown) {
2895 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
2896 return;
2897 } else if (app.notResponding) {
2898 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
2899 return;
2900 } else if (app.crashing) {
2901 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
2902 return;
2903 }
2904
2905 // In case we come through here for the same app before completing
2906 // this one, mark as anring now so we will bail out.
2907 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08002908
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002909 // Log the ANR to the event log.
2910 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
2911 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08002912
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002913 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002914 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002915
2916 int parentPid = app.pid;
2917 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002918 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002919
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002920 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08002921
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002922 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
2923 ProcessRecord r = mLruProcesses.get(i);
2924 if (r != null && r.thread != null) {
2925 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002926 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
2927 if (r.persistent) {
2928 firstPids.add(pid);
2929 } else {
2930 lastPids.put(pid, Boolean.TRUE);
2931 }
2932 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 }
2935 }
2936
Dan Egnor42471dd2010-01-07 17:25:22 -08002937 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002938 StringBuilder info = mStringBuilder;
2939 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08002940 info.append("ANR in ").append(app.processName);
2941 if (activity != null && activity.shortComponentName != null) {
2942 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07002943 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08002944 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08002946 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002948 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08002949 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951
Dianne Hackborn287952c2010-09-22 22:34:31 -07002952 final ProcessStats processStats = new ProcessStats(true);
2953
2954 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
2955
Dan Egnor42471dd2010-01-07 17:25:22 -08002956 String cpuInfo = null;
2957 if (MONITOR_CPU_USAGE) {
2958 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002959 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002960 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002961 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002962 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08002963 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 }
2965
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002966 info.append(processStats.printCurrentState(anrTime));
2967
Joe Onorato8a9b2202010-02-26 18:56:32 -08002968 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08002969 if (tracesFile == null) {
2970 // There is no trace file, so dump (only) the alleged culprit's threads to the log
2971 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
2972 }
2973
2974 addErrorToDropBox("anr", app, activity, parent, annotation, cpuInfo, tracesFile, null);
2975
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002976 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08002978 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
2979 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002981 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
2982 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 }
2984 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002985 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 }
2987 }
2988
Dan Egnor42471dd2010-01-07 17:25:22 -08002989 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
2990 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
2991 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002992
2993 synchronized (this) {
2994 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
2995 Process.killProcess(app.pid);
2996 return;
2997 }
2998
2999 // Set the app's notResponding state, and look up the errorReportReceiver
3000 makeAppNotRespondingLocked(app,
3001 activity != null ? activity.shortComponentName : null,
3002 annotation != null ? "ANR " + annotation : "ANR",
3003 info.toString());
3004
3005 // Bring up the infamous App Not Responding dialog
3006 Message msg = Message.obtain();
3007 HashMap map = new HashMap();
3008 msg.what = SHOW_NOT_RESPONDING_MSG;
3009 msg.obj = map;
3010 map.put("app", app);
3011 if (activity != null) {
3012 map.put("activity", activity);
3013 }
3014
3015 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 }
3018
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003019 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3020 if (!mLaunchWarningShown) {
3021 mLaunchWarningShown = true;
3022 mHandler.post(new Runnable() {
3023 @Override
3024 public void run() {
3025 synchronized (ActivityManagerService.this) {
3026 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3027 d.show();
3028 mHandler.postDelayed(new Runnable() {
3029 @Override
3030 public void run() {
3031 synchronized (ActivityManagerService.this) {
3032 d.dismiss();
3033 mLaunchWarningShown = false;
3034 }
3035 }
3036 }, 4000);
3037 }
3038 }
3039 });
3040 }
3041 }
3042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 public boolean clearApplicationUserData(final String packageName,
3044 final IPackageDataObserver observer) {
3045 int uid = Binder.getCallingUid();
3046 int pid = Binder.getCallingPid();
3047 long callingId = Binder.clearCallingIdentity();
3048 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003049 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 int pkgUid = -1;
3051 synchronized(this) {
3052 try {
3053 pkgUid = pm.getPackageUid(packageName);
3054 } catch (RemoteException e) {
3055 }
3056 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003057 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 return false;
3059 }
3060 if (uid == pkgUid || checkComponentPermission(
3061 android.Manifest.permission.CLEAR_APP_USER_DATA,
3062 pid, uid, -1)
3063 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003064 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 } else {
3066 throw new SecurityException(pid+" does not have permission:"+
3067 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3068 "for process:"+packageName);
3069 }
3070 }
3071
3072 try {
3073 //clear application user data
3074 pm.clearApplicationUserData(packageName, observer);
3075 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3076 Uri.fromParts("package", packageName, null));
3077 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003078 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
3079 null, null, 0, null, null, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 } catch (RemoteException e) {
3081 }
3082 } finally {
3083 Binder.restoreCallingIdentity(callingId);
3084 }
3085 return true;
3086 }
3087
Dianne Hackborn03abb812010-01-04 18:43:19 -08003088 public void killBackgroundProcesses(final String packageName) {
3089 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3090 != PackageManager.PERMISSION_GRANTED &&
3091 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3092 != PackageManager.PERMISSION_GRANTED) {
3093 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 + Binder.getCallingPid()
3095 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003096 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003097 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 throw new SecurityException(msg);
3099 }
3100
3101 long callingId = Binder.clearCallingIdentity();
3102 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003103 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 int pkgUid = -1;
3105 synchronized(this) {
3106 try {
3107 pkgUid = pm.getPackageUid(packageName);
3108 } catch (RemoteException e) {
3109 }
3110 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003111 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 return;
3113 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003114 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003115 SECONDARY_SERVER_ADJ, false, true);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003116 }
3117 } finally {
3118 Binder.restoreCallingIdentity(callingId);
3119 }
3120 }
3121
3122 public void forceStopPackage(final String packageName) {
3123 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3124 != PackageManager.PERMISSION_GRANTED) {
3125 String msg = "Permission Denial: forceStopPackage() from pid="
3126 + Binder.getCallingPid()
3127 + ", uid=" + Binder.getCallingUid()
3128 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003129 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003130 throw new SecurityException(msg);
3131 }
3132
3133 long callingId = Binder.clearCallingIdentity();
3134 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003135 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003136 int pkgUid = -1;
3137 synchronized(this) {
3138 try {
3139 pkgUid = pm.getPackageUid(packageName);
3140 } catch (RemoteException e) {
3141 }
3142 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003143 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003144 return;
3145 }
3146 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 }
3148 } finally {
3149 Binder.restoreCallingIdentity(callingId);
3150 }
3151 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003152
3153 /*
3154 * The pkg name and uid have to be specified.
3155 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3156 */
3157 public void killApplicationWithUid(String pkg, int uid) {
3158 if (pkg == null) {
3159 return;
3160 }
3161 // Make sure the uid is valid.
3162 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003163 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003164 return;
3165 }
3166 int callerUid = Binder.getCallingUid();
3167 // Only the system server can kill an application
3168 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003169 // Post an aysnc message to kill the application
3170 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3171 msg.arg1 = uid;
3172 msg.arg2 = 0;
3173 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003174 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003175 } else {
3176 throw new SecurityException(callerUid + " cannot kill pkg: " +
3177 pkg);
3178 }
3179 }
3180
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003181 public void closeSystemDialogs(String reason) {
3182 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003183 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003184 if (reason != null) {
3185 intent.putExtra("reason", reason);
3186 }
3187
3188 final int uid = Binder.getCallingUid();
3189 final long origId = Binder.clearCallingIdentity();
3190 synchronized (this) {
3191 int i = mWatchers.beginBroadcast();
3192 while (i > 0) {
3193 i--;
3194 IActivityWatcher w = mWatchers.getBroadcastItem(i);
3195 if (w != null) {
3196 try {
3197 w.closingSystemDialogs(reason);
3198 } catch (RemoteException e) {
3199 }
3200 }
3201 }
3202 mWatchers.finishBroadcast();
3203
Dianne Hackbornffa42482009-09-23 22:20:11 -07003204 mWindowManager.closeSystemDialogs(reason);
3205
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003206 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3207 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003208 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003209 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003210 Activity.RESULT_CANCELED, null, "close-sys");
3211 }
3212 }
3213
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003214 broadcastIntentLocked(null, null, intent, null,
3215 null, 0, null, null, null, false, false, -1, uid);
3216 }
3217 Binder.restoreCallingIdentity(origId);
3218 }
3219
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003220 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003221 throws RemoteException {
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003222 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3223 for (int i=pids.length-1; i>=0; i--) {
3224 infos[i] = new Debug.MemoryInfo();
3225 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003226 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003227 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003228 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003229
3230 public void killApplicationProcess(String processName, int uid) {
3231 if (processName == null) {
3232 return;
3233 }
3234
3235 int callerUid = Binder.getCallingUid();
3236 // Only the system server can kill an application
3237 if (callerUid == Process.SYSTEM_UID) {
3238 synchronized (this) {
3239 ProcessRecord app = getProcessRecordLocked(processName, uid);
3240 if (app != null) {
3241 try {
3242 app.thread.scheduleSuicide();
3243 } catch (RemoteException e) {
3244 // If the other end already died, then our work here is done.
3245 }
3246 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003247 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003248 + processName + " / " + uid);
3249 }
3250 }
3251 } else {
3252 throw new SecurityException(callerUid + " cannot kill app process: " +
3253 processName);
3254 }
3255 }
3256
Dianne Hackborn03abb812010-01-04 18:43:19 -08003257 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003258 forceStopPackageLocked(packageName, uid, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3260 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003261 if (!mProcessesReady) {
3262 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 intent.putExtra(Intent.EXTRA_UID, uid);
3265 broadcastIntentLocked(null, null, intent,
3266 null, null, 0, null, null, null,
3267 false, false, MY_PID, Process.SYSTEM_UID);
3268 }
3269
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003270 private final boolean killPackageProcessesLocked(String packageName, int uid,
3271 int minOomAdj, boolean callerWillRestart, boolean doit) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003272 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273
Dianne Hackborn03abb812010-01-04 18:43:19 -08003274 // Remove all processes this package may have touched: all with the
3275 // same UID (except for the system or root user), and all whose name
3276 // matches the package name.
3277 final String procNamePrefix = packageName + ":";
3278 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3279 final int NA = apps.size();
3280 for (int ia=0; ia<NA; ia++) {
3281 ProcessRecord app = apps.valueAt(ia);
3282 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003283 if (doit) {
3284 procs.add(app);
3285 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003286 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3287 || app.processName.equals(packageName)
3288 || app.processName.startsWith(procNamePrefix)) {
3289 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003290 if (!doit) {
3291 return true;
3292 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003293 app.removed = true;
3294 procs.add(app);
3295 }
3296 }
3297 }
3298 }
3299
3300 int N = procs.size();
3301 for (int i=0; i<N; i++) {
3302 removeProcessLocked(procs.get(i), callerWillRestart);
3303 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003304 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003305 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003306
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003307 private final boolean forceStopPackageLocked(String name, int uid,
3308 boolean callerWillRestart, boolean purgeCache, boolean doit) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 int i, N;
3310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 if (uid < 0) {
3312 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003313 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 } catch (RemoteException e) {
3315 }
3316 }
3317
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003318 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003319 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003320
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003321 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3322 while (badApps.hasNext()) {
3323 SparseArray<Long> ba = badApps.next();
3324 if (ba.get(uid) != null) {
3325 badApps.remove();
3326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 }
3328 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003329
3330 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
3331 callerWillRestart, doit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003333 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3334 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 if (r.packageName.equals(name)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003336 if (!doit) {
3337 return true;
3338 }
3339 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003340 Slog.i(TAG, " Force finishing activity " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 if (r.app != null) {
3342 r.app.removed = true;
3343 }
3344 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003345 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "uninstall");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 }
3347 }
3348
3349 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3350 for (ServiceRecord service : mServices.values()) {
3351 if (service.packageName.equals(name)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003352 if (!doit) {
3353 return true;
3354 }
3355 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003356 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 if (service.app != null) {
3358 service.app.removed = true;
3359 }
3360 service.app = null;
3361 services.add(service);
3362 }
3363 }
3364
3365 N = services.size();
3366 for (i=0; i<N; i++) {
3367 bringDownServiceLocked(services.get(i), true);
3368 }
3369
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003370 if (doit) {
3371 if (purgeCache) {
3372 AttributeCache ac = AttributeCache.instance();
3373 if (ac != null) {
3374 ac.removePackage(name);
3375 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003376 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003377 mMainStack.resumeTopActivityLocked(null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003378 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003379
3380 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 }
3382
3383 private final boolean removeProcessLocked(ProcessRecord app, boolean callerWillRestart) {
3384 final String name = app.processName;
3385 final int uid = app.info.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003386 if (DEBUG_PROCESSES) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 TAG, "Force removing process " + app + " (" + name
3388 + "/" + uid + ")");
3389
3390 mProcessNames.remove(name, uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003391 if (mHeavyWeightProcess == app) {
3392 mHeavyWeightProcess = null;
3393 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 boolean needRestart = false;
3396 if (app.pid > 0 && app.pid != MY_PID) {
3397 int pid = app.pid;
3398 synchronized (mPidsSelfLocked) {
3399 mPidsSelfLocked.remove(pid);
3400 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3401 }
3402 handleAppDiedLocked(app, true);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003403 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 Process.killProcess(pid);
3405
3406 if (app.persistent) {
3407 if (!callerWillRestart) {
3408 addAppLocked(app.info);
3409 } else {
3410 needRestart = true;
3411 }
3412 }
3413 } else {
3414 mRemovedProcesses.add(app);
3415 }
3416
3417 return needRestart;
3418 }
3419
3420 private final void processStartTimedOutLocked(ProcessRecord app) {
3421 final int pid = app.pid;
3422 boolean gone = false;
3423 synchronized (mPidsSelfLocked) {
3424 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3425 if (knownApp != null && knownApp.thread == null) {
3426 mPidsSelfLocked.remove(pid);
3427 gone = true;
3428 }
3429 }
3430
3431 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003432 Slog.w(TAG, "Process " + app + " failed to attach");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003433 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.info.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003434 app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003436 if (mHeavyWeightProcess == app) {
3437 mHeavyWeightProcess = null;
3438 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3439 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003440 // Take care of any launching providers waiting for this process.
3441 checkAppInLaunchingProvidersLocked(app, true);
3442 // Take care of any services that are waiting for the process.
3443 for (int i=0; i<mPendingServices.size(); i++) {
3444 ServiceRecord sr = mPendingServices.get(i);
3445 if (app.info.uid == sr.appInfo.uid
3446 && app.processName.equals(sr.processName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003447 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003448 mPendingServices.remove(i);
3449 i--;
3450 bringDownServiceLocked(sr, true);
3451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003453 Process.killProcess(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003454 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003455 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003456 try {
3457 IBackupManager bm = IBackupManager.Stub.asInterface(
3458 ServiceManager.getService(Context.BACKUP_SERVICE));
3459 bm.agentDisconnected(app.info.packageName);
3460 } catch (RemoteException e) {
3461 // Can't happen; the backup manager is local
3462 }
3463 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003464 if (mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003465 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003466 mPendingBroadcast.state = BroadcastRecord.IDLE;
3467 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003468 mPendingBroadcast = null;
3469 scheduleBroadcastsLocked();
3470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003472 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 }
3474 }
3475
3476 private final boolean attachApplicationLocked(IApplicationThread thread,
3477 int pid) {
3478
3479 // Find the application record that is being attached... either via
3480 // the pid if we are running in multiple processes, or just pull the
3481 // next app record if we are emulating process with anonymous threads.
3482 ProcessRecord app;
3483 if (pid != MY_PID && pid >= 0) {
3484 synchronized (mPidsSelfLocked) {
3485 app = mPidsSelfLocked.get(pid);
3486 }
3487 } else if (mStartingProcesses.size() > 0) {
3488 app = mStartingProcesses.remove(0);
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003489 app.setPid(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 } else {
3491 app = null;
3492 }
3493
3494 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003495 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003497 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 if (pid > 0 && pid != MY_PID) {
3499 Process.killProcess(pid);
3500 } else {
3501 try {
3502 thread.scheduleExit();
3503 } catch (Exception e) {
3504 // Ignore exceptions.
3505 }
3506 }
3507 return false;
3508 }
3509
3510 // If this application record is still attached to a previous
3511 // process, clean it up now.
3512 if (app.thread != null) {
3513 handleAppDiedLocked(app, true);
3514 }
3515
3516 // Tell the process all about itself.
3517
Joe Onorato8a9b2202010-02-26 18:56:32 -08003518 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519 TAG, "Binding process pid " + pid + " to record " + app);
3520
3521 String processName = app.processName;
3522 try {
3523 thread.asBinder().linkToDeath(new AppDeathRecipient(
3524 app, pid, thread), 0);
3525 } catch (RemoteException e) {
3526 app.resetPackageList();
3527 startProcessLocked(app, "link fail", processName);
3528 return false;
3529 }
3530
Doug Zongker2bec3d42009-12-04 12:52:44 -08003531 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532
3533 app.thread = thread;
3534 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003535 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3536 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 app.forcingToForeground = null;
3538 app.foregroundServices = false;
3539 app.debugging = false;
3540
3541 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3542
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003543 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003544 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003546 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003547 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003548 }
3549
Joe Onorato8a9b2202010-02-26 18:56:32 -08003550 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 TAG, "New app record " + app
3552 + " thread=" + thread.asBinder() + " pid=" + pid);
3553 try {
3554 int testMode = IApplicationThread.DEBUG_OFF;
3555 if (mDebugApp != null && mDebugApp.equals(processName)) {
3556 testMode = mWaitForDebugger
3557 ? IApplicationThread.DEBUG_WAIT
3558 : IApplicationThread.DEBUG_ON;
3559 app.debugging = true;
3560 if (mDebugTransient) {
3561 mDebugApp = mOrigDebugApp;
3562 mWaitForDebugger = mOrigWaitForDebugger;
3563 }
3564 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003565
Christopher Tate181fafa2009-05-14 11:12:14 -07003566 // If the app is being launched for restore or full backup, set it up specially
3567 boolean isRestrictedBackupMode = false;
3568 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3569 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
3570 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3571 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003572
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003573 ensurePackageDexOpt(app.instrumentationInfo != null
3574 ? app.instrumentationInfo.packageName
3575 : app.info.packageName);
3576 if (app.instrumentationClass != null) {
3577 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003578 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003579 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003580 + processName + " with config " + mConfiguration);
Dianne Hackborn1655be42009-05-08 14:29:01 -07003581 thread.bindApplication(processName, app.instrumentationInfo != null
3582 ? app.instrumentationInfo : app.info, providers,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583 app.instrumentationClass, app.instrumentationProfileFile,
3584 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003585 isRestrictedBackupMode || !normalMode,
3586 mConfiguration, getCommonServicesLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003587 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003588 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003589 } catch (Exception e) {
3590 // todo: Yikes! What should we do? For now we will try to
3591 // start another process, but that could easily get us in
3592 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003593 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594
3595 app.resetPackageList();
3596 startProcessLocked(app, "bind fail", processName);
3597 return false;
3598 }
3599
3600 // Remove this record from the list of starting applications.
3601 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003602 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3603 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 mProcessesOnHold.remove(app);
3605
3606 boolean badApp = false;
3607 boolean didSomething = false;
3608
3609 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003610 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003611 if (hr != null && normalMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
3613 && processName.equals(hr.processName)) {
3614 try {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003615 if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 didSomething = true;
3617 }
3618 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003619 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 + hr.intent.getComponent().flattenToShortString(), e);
3621 badApp = true;
3622 }
3623 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003624 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 }
3626 }
3627
3628 // Find any services that should be running in this process...
3629 if (!badApp && mPendingServices.size() > 0) {
3630 ServiceRecord sr = null;
3631 try {
3632 for (int i=0; i<mPendingServices.size(); i++) {
3633 sr = mPendingServices.get(i);
3634 if (app.info.uid != sr.appInfo.uid
3635 || !processName.equals(sr.processName)) {
3636 continue;
3637 }
3638
3639 mPendingServices.remove(i);
3640 i--;
3641 realStartServiceLocked(sr, app);
3642 didSomething = true;
3643 }
3644 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003645 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003646 + sr.shortName, e);
3647 badApp = true;
3648 }
3649 }
3650
3651 // Check if the next broadcast receiver is in this process...
3652 BroadcastRecord br = mPendingBroadcast;
3653 if (!badApp && br != null && br.curApp == app) {
3654 try {
3655 mPendingBroadcast = null;
3656 processCurBroadcastLocked(br, app);
3657 didSomething = true;
3658 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003659 Slog.w(TAG, "Exception in new application when starting receiver "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 + br.curComponent.flattenToShortString(), e);
3661 badApp = true;
Jeff Brown4d94a762010-09-23 11:33:28 -07003662 logBroadcastReceiverDiscardLocked(br);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 finishReceiverLocked(br.receiver, br.resultCode, br.resultData,
3664 br.resultExtras, br.resultAbort, true);
3665 scheduleBroadcastsLocked();
Magnus Edlund7bb25812010-02-24 15:45:06 +01003666 // We need to reset the state if we fails to start the receiver.
3667 br.state = BroadcastRecord.IDLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 }
3669 }
3670
Christopher Tate181fafa2009-05-14 11:12:14 -07003671 // Check whether the next backup agent is in this process...
3672 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.info.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003673 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003674 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003675 try {
3676 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, mBackupTarget.backupMode);
3677 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003678 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003679 e.printStackTrace();
3680 }
3681 }
3682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 if (badApp) {
3684 // todo: Also need to kill application to deal with all
3685 // kinds of exceptions.
3686 handleAppDiedLocked(app, false);
3687 return false;
3688 }
3689
3690 if (!didSomething) {
3691 updateOomAdjLocked();
3692 }
3693
3694 return true;
3695 }
3696
3697 public final void attachApplication(IApplicationThread thread) {
3698 synchronized (this) {
3699 int callingPid = Binder.getCallingPid();
3700 final long origId = Binder.clearCallingIdentity();
3701 attachApplicationLocked(thread, callingPid);
3702 Binder.restoreCallingIdentity(origId);
3703 }
3704 }
3705
Dianne Hackborne88846e2009-09-30 21:34:25 -07003706 public final void activityIdle(IBinder token, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003708 mMainStack.activityIdleInternal(token, false, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 Binder.restoreCallingIdentity(origId);
3710 }
3711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003713 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003714 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 mWindowManager.enableScreenAfterBoot();
3716 }
3717
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003718 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003719 IntentFilter pkgFilter = new IntentFilter();
3720 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
3721 pkgFilter.addDataScheme("package");
3722 mContext.registerReceiver(new BroadcastReceiver() {
3723 @Override
3724 public void onReceive(Context context, Intent intent) {
3725 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3726 if (pkgs != null) {
3727 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07003728 synchronized (ActivityManagerService.this) {
3729 if (forceStopPackageLocked(pkg, -1, false, false, false)) {
3730 setResultCode(Activity.RESULT_OK);
3731 return;
3732 }
3733 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003734 }
3735 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003736 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003737 }, pkgFilter);
3738
3739 synchronized (this) {
3740 // Ensure that any processes we had put on hold are now started
3741 // up.
3742 final int NP = mProcessesOnHold.size();
3743 if (NP > 0) {
3744 ArrayList<ProcessRecord> procs =
3745 new ArrayList<ProcessRecord>(mProcessesOnHold);
3746 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003747 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
3748 + procs.get(ip));
3749 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003750 }
3751 }
3752
3753 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003754 // Start looking for apps that are abusing wake locks.
3755 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003756 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003757 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07003758 SystemProperties.set("sys.boot_completed", "1");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003759 broadcastIntentLocked(null, null,
3760 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
3761 null, null, 0, null, null,
3762 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
3763 false, false, MY_PID, Process.SYSTEM_UID);
3764 }
3765 }
3766 }
3767
3768 final void ensureBootCompleted() {
3769 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003770 boolean enableScreen;
3771 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003772 booting = mBooting;
3773 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003774 enableScreen = !mBooted;
3775 mBooted = true;
3776 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003777
3778 if (booting) {
3779 finishBooting();
3780 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003781
3782 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003783 enableScreenAfterBoot();
3784 }
3785 }
3786
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003787 public final void activityPaused(IBinder token) {
3788 final long origId = Binder.clearCallingIdentity();
3789 mMainStack.activityPaused(token, false);
3790 Binder.restoreCallingIdentity(origId);
3791 }
3792
3793 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
3794 CharSequence description) {
3795 if (localLOGV) Slog.v(
3796 TAG, "Activity stopped: token=" + token);
3797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 // Refuse possible leaked file descriptors
3799 if (icicle != null && icicle.hasFileDescriptors()) {
3800 throw new IllegalArgumentException("File descriptors passed in Bundle");
3801 }
3802
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003803 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804
3805 final long origId = Binder.clearCallingIdentity();
3806
3807 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003808 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003810 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003811 r.icicle = icicle;
3812 r.haveState = true;
3813 if (thumbnail != null) {
3814 r.thumbnail = thumbnail;
Dianne Hackbornd2835932010-12-13 16:28:46 -08003815 if (r.task != null) {
3816 r.task.lastThumbnail = r.thumbnail;
3817 }
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819 r.description = description;
Dianne Hackbornd2835932010-12-13 16:28:46 -08003820 if (r.task != null) {
3821 r.task.lastDescription = r.description;
3822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 r.stopped = true;
3824 r.state = ActivityState.STOPPED;
3825 if (!r.finishing) {
3826 if (r.configDestroy) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003827 r.stack.destroyActivityLocked(r, true);
3828 r.stack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 }
3830 }
3831 }
3832 }
3833
3834 if (r != null) {
3835 sendPendingThumbnail(r, null, null, null, false);
3836 }
3837
3838 trimApplications();
3839
3840 Binder.restoreCallingIdentity(origId);
3841 }
3842
3843 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003844 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003845 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 }
3847
3848 public String getCallingPackage(IBinder token) {
3849 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003850 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07003851 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 }
3853 }
3854
3855 public ComponentName getCallingActivity(IBinder token) {
3856 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003857 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 return r != null ? r.intent.getComponent() : null;
3859 }
3860 }
3861
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003862 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003863 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003865 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 if (r != null) {
3867 return r.resultTo;
3868 }
3869 }
3870 return null;
3871 }
3872
3873 public ComponentName getActivityClassForToken(IBinder token) {
3874 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003875 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003877 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 return r.intent.getComponent();
3879 }
3880 return null;
3881 }
3882 }
3883
3884 public String getPackageForToken(IBinder token) {
3885 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003886 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003888 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 return r.packageName;
3890 }
3891 return null;
3892 }
3893 }
3894
3895 public IIntentSender getIntentSender(int type,
3896 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003897 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003899 if (intents != null) {
3900 if (intents.length < 1) {
3901 throw new IllegalArgumentException("Intents array length must be >= 1");
3902 }
3903 for (int i=0; i<intents.length; i++) {
3904 Intent intent = intents[i];
3905 if (intent == null) {
3906 throw new IllegalArgumentException("Null intent at index " + i);
3907 }
3908 if (intent.hasFileDescriptors()) {
3909 throw new IllegalArgumentException("File descriptors passed in Intent");
3910 }
3911 if (type == INTENT_SENDER_BROADCAST &&
3912 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
3913 throw new IllegalArgumentException(
3914 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
3915 }
3916 intents[i] = new Intent(intent);
3917 }
3918 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003919 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003920 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003921 }
3922 }
3923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 synchronized(this) {
3925 int callingUid = Binder.getCallingUid();
3926 try {
3927 if (callingUid != 0 && callingUid != Process.SYSTEM_UID &&
3928 Process.supportsProcesses()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003929 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 .getPackageUid(packageName);
3931 if (uid != Binder.getCallingUid()) {
3932 String msg = "Permission Denial: getIntentSender() from pid="
3933 + Binder.getCallingPid()
3934 + ", uid=" + Binder.getCallingUid()
3935 + ", (need uid=" + uid + ")"
3936 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003937 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 throw new SecurityException(msg);
3939 }
3940 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003941
3942 return getIntentSenderLocked(type, packageName, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003943 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 } catch (RemoteException e) {
3946 throw new SecurityException(e);
3947 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003948 }
3949 }
3950
3951 IIntentSender getIntentSenderLocked(int type,
3952 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003953 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003954 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003955 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003956 int index = mMainStack.indexOfTokenLocked(token);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003957 if (index < 0) {
3958 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003960 activity = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003961 if (activity.finishing) {
3962 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003964 }
3965
3966 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
3967 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
3968 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
3969 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
3970 |PendingIntent.FLAG_UPDATE_CURRENT);
3971
3972 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
3973 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003974 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003975 WeakReference<PendingIntentRecord> ref;
3976 ref = mIntentSenderRecords.get(key);
3977 PendingIntentRecord rec = ref != null ? ref.get() : null;
3978 if (rec != null) {
3979 if (!cancelCurrent) {
3980 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003981 if (rec.key.requestIntent != null) {
3982 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
3983 }
3984 if (intents != null) {
3985 intents[intents.length-1] = rec.key.requestIntent;
3986 rec.key.allIntents = intents;
3987 rec.key.allResolvedTypes = resolvedTypes;
3988 } else {
3989 rec.key.allIntents = null;
3990 rec.key.allResolvedTypes = null;
3991 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 return rec;
3994 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003995 rec.canceled = true;
3996 mIntentSenderRecords.remove(key);
3997 }
3998 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 return rec;
4000 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004001 rec = new PendingIntentRecord(this, key, callingUid);
4002 mIntentSenderRecords.put(key, rec.ref);
4003 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
4004 if (activity.pendingResults == null) {
4005 activity.pendingResults
4006 = new HashSet<WeakReference<PendingIntentRecord>>();
4007 }
4008 activity.pendingResults.add(rec.ref);
4009 }
4010 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 }
4012
4013 public void cancelIntentSender(IIntentSender sender) {
4014 if (!(sender instanceof PendingIntentRecord)) {
4015 return;
4016 }
4017 synchronized(this) {
4018 PendingIntentRecord rec = (PendingIntentRecord)sender;
4019 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004020 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 .getPackageUid(rec.key.packageName);
4022 if (uid != Binder.getCallingUid()) {
4023 String msg = "Permission Denial: cancelIntentSender() from pid="
4024 + Binder.getCallingPid()
4025 + ", uid=" + Binder.getCallingUid()
4026 + " is not allowed to cancel packges "
4027 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004028 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 throw new SecurityException(msg);
4030 }
4031 } catch (RemoteException e) {
4032 throw new SecurityException(e);
4033 }
4034 cancelIntentSenderLocked(rec, true);
4035 }
4036 }
4037
4038 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4039 rec.canceled = true;
4040 mIntentSenderRecords.remove(rec.key);
4041 if (cleanActivity && rec.key.activity != null) {
4042 rec.key.activity.pendingResults.remove(rec.ref);
4043 }
4044 }
4045
4046 public String getPackageForIntentSender(IIntentSender pendingResult) {
4047 if (!(pendingResult instanceof PendingIntentRecord)) {
4048 return null;
4049 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004050 try {
4051 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4052 return res.key.packageName;
4053 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 }
4055 return null;
4056 }
4057
4058 public void setProcessLimit(int max) {
4059 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4060 "setProcessLimit()");
4061 mProcessLimit = max;
4062 }
4063
4064 public int getProcessLimit() {
4065 return mProcessLimit;
4066 }
4067
4068 void foregroundTokenDied(ForegroundToken token) {
4069 synchronized (ActivityManagerService.this) {
4070 synchronized (mPidsSelfLocked) {
4071 ForegroundToken cur
4072 = mForegroundProcesses.get(token.pid);
4073 if (cur != token) {
4074 return;
4075 }
4076 mForegroundProcesses.remove(token.pid);
4077 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4078 if (pr == null) {
4079 return;
4080 }
4081 pr.forcingToForeground = null;
4082 pr.foregroundServices = false;
4083 }
4084 updateOomAdjLocked();
4085 }
4086 }
4087
4088 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4089 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4090 "setProcessForeground()");
4091 synchronized(this) {
4092 boolean changed = false;
4093
4094 synchronized (mPidsSelfLocked) {
4095 ProcessRecord pr = mPidsSelfLocked.get(pid);
4096 if (pr == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004097 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 return;
4099 }
4100 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4101 if (oldToken != null) {
4102 oldToken.token.unlinkToDeath(oldToken, 0);
4103 mForegroundProcesses.remove(pid);
4104 pr.forcingToForeground = null;
4105 changed = true;
4106 }
4107 if (isForeground && token != null) {
4108 ForegroundToken newToken = new ForegroundToken() {
4109 public void binderDied() {
4110 foregroundTokenDied(this);
4111 }
4112 };
4113 newToken.pid = pid;
4114 newToken.token = token;
4115 try {
4116 token.linkToDeath(newToken, 0);
4117 mForegroundProcesses.put(pid, newToken);
4118 pr.forcingToForeground = token;
4119 changed = true;
4120 } catch (RemoteException e) {
4121 // If the process died while doing this, we will later
4122 // do the cleanup with the process death link.
4123 }
4124 }
4125 }
4126
4127 if (changed) {
4128 updateOomAdjLocked();
4129 }
4130 }
4131 }
4132
4133 // =========================================================
4134 // PERMISSIONS
4135 // =========================================================
4136
4137 static class PermissionController extends IPermissionController.Stub {
4138 ActivityManagerService mActivityManagerService;
4139 PermissionController(ActivityManagerService activityManagerService) {
4140 mActivityManagerService = activityManagerService;
4141 }
4142
4143 public boolean checkPermission(String permission, int pid, int uid) {
4144 return mActivityManagerService.checkPermission(permission, pid,
4145 uid) == PackageManager.PERMISSION_GRANTED;
4146 }
4147 }
4148
4149 /**
4150 * This can be called with or without the global lock held.
4151 */
4152 int checkComponentPermission(String permission, int pid, int uid,
4153 int reqUid) {
4154 // We might be performing an operation on behalf of an indirect binder
4155 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4156 // client identity accordingly before proceeding.
4157 Identity tlsIdentity = sCallerIdentity.get();
4158 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004159 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4161 uid = tlsIdentity.uid;
4162 pid = tlsIdentity.pid;
4163 }
4164
4165 // Root, system server and our own process get to do everything.
4166 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID ||
4167 !Process.supportsProcesses()) {
4168 return PackageManager.PERMISSION_GRANTED;
4169 }
4170 // If the target requires a specific UID, always fail for others.
4171 if (reqUid >= 0 && uid != reqUid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004172 Slog.w(TAG, "Permission denied: checkComponentPermission() reqUid=" + reqUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004173 return PackageManager.PERMISSION_DENIED;
4174 }
4175 if (permission == null) {
4176 return PackageManager.PERMISSION_GRANTED;
4177 }
4178 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004179 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 .checkUidPermission(permission, uid);
4181 } catch (RemoteException e) {
4182 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004183 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 }
4185 return PackageManager.PERMISSION_DENIED;
4186 }
4187
4188 /**
4189 * As the only public entry point for permissions checking, this method
4190 * can enforce the semantic that requesting a check on a null global
4191 * permission is automatically denied. (Internally a null permission
4192 * string is used when calling {@link #checkComponentPermission} in cases
4193 * when only uid-based security is needed.)
4194 *
4195 * This can be called with or without the global lock held.
4196 */
4197 public int checkPermission(String permission, int pid, int uid) {
4198 if (permission == null) {
4199 return PackageManager.PERMISSION_DENIED;
4200 }
4201 return checkComponentPermission(permission, pid, uid, -1);
4202 }
4203
4204 /**
4205 * Binder IPC calls go through the public entry point.
4206 * This can be called with or without the global lock held.
4207 */
4208 int checkCallingPermission(String permission) {
4209 return checkPermission(permission,
4210 Binder.getCallingPid(),
4211 Binder.getCallingUid());
4212 }
4213
4214 /**
4215 * This can be called with or without the global lock held.
4216 */
4217 void enforceCallingPermission(String permission, String func) {
4218 if (checkCallingPermission(permission)
4219 == PackageManager.PERMISSION_GRANTED) {
4220 return;
4221 }
4222
4223 String msg = "Permission Denial: " + func + " from pid="
4224 + Binder.getCallingPid()
4225 + ", uid=" + Binder.getCallingUid()
4226 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004227 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 throw new SecurityException(msg);
4229 }
4230
4231 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07004232 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
4233 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4234 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
4235 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4236 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004238 // Is the component private from the target uid?
4239 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
4240
4241 // Acceptable if the there is no read permission needed from the
4242 // target or the target is holding the read permission.
4243 if (!readPerm) {
4244 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004246 == PackageManager.PERMISSION_GRANTED)) {
4247 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 }
4249 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004250
4251 // Acceptable if the there is no write permission needed from the
4252 // target or the target is holding the read permission.
4253 if (!writePerm) {
4254 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004255 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004256 == PackageManager.PERMISSION_GRANTED)) {
4257 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 }
4259 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004260
4261 // Acceptable if there is a path permission matching the URI that
4262 // the target holds the permission on.
4263 PathPermission[] pps = pi.pathPermissions;
4264 if (pps != null && (!readPerm || !writePerm)) {
4265 final String path = uri.getPath();
4266 int i = pps.length;
4267 while (i > 0 && (!readPerm || !writePerm)) {
4268 i--;
4269 PathPermission pp = pps[i];
4270 if (!readPerm) {
4271 final String pprperm = pp.getReadPermission();
4272 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4273 + pprperm + " for " + pp.getPath()
4274 + ": match=" + pp.match(path)
4275 + " check=" + pm.checkUidPermission(pprperm, uid));
4276 if (pprperm != null && pp.match(path) &&
4277 (pm.checkUidPermission(pprperm, uid)
4278 == PackageManager.PERMISSION_GRANTED)) {
4279 readPerm = true;
4280 }
4281 }
4282 if (!writePerm) {
4283 final String ppwperm = pp.getWritePermission();
4284 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4285 + ppwperm + " for " + pp.getPath()
4286 + ": match=" + pp.match(path)
4287 + " check=" + pm.checkUidPermission(ppwperm, uid));
4288 if (ppwperm != null && pp.match(path) &&
4289 (pm.checkUidPermission(ppwperm, uid)
4290 == PackageManager.PERMISSION_GRANTED)) {
4291 writePerm = true;
4292 }
4293 }
4294 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 } catch (RemoteException e) {
4297 return false;
4298 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004299
4300 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 }
4302
4303 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4304 int modeFlags) {
4305 // Root gets to do everything.
4306 if (uid == 0 || !Process.supportsProcesses()) {
4307 return true;
4308 }
4309 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4310 if (perms == null) return false;
4311 UriPermission perm = perms.get(uri);
4312 if (perm == null) return false;
4313 return (modeFlags&perm.modeFlags) == modeFlags;
4314 }
4315
4316 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
4317 // Another redirected-binder-call permissions check as in
4318 // {@link checkComponentPermission}.
4319 Identity tlsIdentity = sCallerIdentity.get();
4320 if (tlsIdentity != null) {
4321 uid = tlsIdentity.uid;
4322 pid = tlsIdentity.pid;
4323 }
4324
4325 // Our own process gets to do everything.
4326 if (pid == MY_PID) {
4327 return PackageManager.PERMISSION_GRANTED;
4328 }
4329 synchronized(this) {
4330 return checkUriPermissionLocked(uri, uid, modeFlags)
4331 ? PackageManager.PERMISSION_GRANTED
4332 : PackageManager.PERMISSION_DENIED;
4333 }
4334 }
4335
Dianne Hackborn39792d22010-08-19 18:01:52 -07004336 /**
4337 * Check if the targetPkg can be granted permission to access uri by
4338 * the callingUid using the given modeFlags. Throws a security exception
4339 * if callingUid is not allowed to do this. Returns the uid of the target
4340 * if the URI permission grant should be performed; returns -1 if it is not
4341 * needed (for example targetPkg already has permission to access the URI).
4342 */
4343 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
4344 Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4346 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4347 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004348 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 }
4350
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004351 if (targetPkg != null) {
4352 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4353 "Checking grant " + targetPkg + " permission to " + uri);
4354 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004355
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004356 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357
4358 // If this is not a content: uri, we can't do anything with it.
4359 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004360 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004361 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004362 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004363 }
4364
4365 String name = uri.getAuthority();
4366 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004367 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368 if (cpr != null) {
4369 pi = cpr.info;
4370 } else {
4371 try {
4372 pi = pm.resolveContentProvider(name,
4373 PackageManager.GET_URI_PERMISSION_PATTERNS);
4374 } catch (RemoteException ex) {
4375 }
4376 }
4377 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004378 Slog.w(TAG, "No content provider found for: " + name);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004379 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004380 }
4381
4382 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004383 if (targetPkg != null) {
4384 try {
4385 targetUid = pm.getPackageUid(targetPkg);
4386 if (targetUid < 0) {
4387 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4388 "Can't grant URI permission no uid for: " + targetPkg);
4389 return -1;
4390 }
4391 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004392 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004394 } else {
4395 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396 }
4397
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004398 if (targetUid >= 0) {
4399 // First... does the target actually need this permission?
4400 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4401 // No need to grant the target this permission.
4402 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4403 "Target " + targetPkg + " already has full permission to " + uri);
4404 return -1;
4405 }
4406 } else {
4407 // First... there is no target package, so can anyone access it?
4408 boolean allowed = pi.exported;
4409 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4410 if (pi.readPermission != null) {
4411 allowed = false;
4412 }
4413 }
4414 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4415 if (pi.writePermission != null) {
4416 allowed = false;
4417 }
4418 }
4419 if (allowed) {
4420 return -1;
4421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 }
4423
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004424 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004425 if (!pi.grantUriPermissions) {
4426 throw new SecurityException("Provider " + pi.packageName
4427 + "/" + pi.name
4428 + " does not allow granting of Uri permissions (uri "
4429 + uri + ")");
4430 }
4431 if (pi.uriPermissionPatterns != null) {
4432 final int N = pi.uriPermissionPatterns.length;
4433 boolean allowed = false;
4434 for (int i=0; i<N; i++) {
4435 if (pi.uriPermissionPatterns[i] != null
4436 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4437 allowed = true;
4438 break;
4439 }
4440 }
4441 if (!allowed) {
4442 throw new SecurityException("Provider " + pi.packageName
4443 + "/" + pi.name
4444 + " does not allow granting of permission to path of Uri "
4445 + uri);
4446 }
4447 }
4448
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004449 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004451 if (callingUid != Process.myUid()) {
4452 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4453 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4454 throw new SecurityException("Uid " + callingUid
4455 + " does not have permission to uri " + uri);
4456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004457 }
4458 }
4459
Dianne Hackborn39792d22010-08-19 18:01:52 -07004460 return targetUid;
4461 }
4462
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004463 public int checkGrantUriPermission(int callingUid, String targetPkg,
4464 Uri uri, int modeFlags) {
4465 synchronized(this) {
4466 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4467 }
4468 }
4469
Dianne Hackborn39792d22010-08-19 18:01:52 -07004470 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4471 Uri uri, int modeFlags, UriPermissionOwner owner) {
4472 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4473 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4474 if (modeFlags == 0) {
4475 return;
4476 }
4477
4478 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004479 // to the uri, and the target doesn't. Let's now give this to
4480 // the target.
4481
Joe Onorato8a9b2202010-02-26 18:56:32 -08004482 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004483 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 HashMap<Uri, UriPermission> targetUris
4486 = mGrantedUriPermissions.get(targetUid);
4487 if (targetUris == null) {
4488 targetUris = new HashMap<Uri, UriPermission>();
4489 mGrantedUriPermissions.put(targetUid, targetUris);
4490 }
4491
4492 UriPermission perm = targetUris.get(uri);
4493 if (perm == null) {
4494 perm = new UriPermission(targetUid, uri);
4495 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004499 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 perm.globalModeFlags |= modeFlags;
4501 } else if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004502 perm.readOwners.add(owner);
4503 owner.addReadPermission(perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 } else if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004505 perm.writeOwners.add(owner);
4506 owner.addWritePermission(perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 }
4508 }
4509
Dianne Hackborn39792d22010-08-19 18:01:52 -07004510 void grantUriPermissionLocked(int callingUid,
4511 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004512 if (targetPkg == null) {
4513 throw new NullPointerException("targetPkg");
4514 }
4515
Dianne Hackborn39792d22010-08-19 18:01:52 -07004516 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4517 if (targetUid < 0) {
4518 return;
4519 }
4520
4521 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4522 }
4523
4524 /**
4525 * Like checkGrantUriPermissionLocked, but takes an Intent.
4526 */
4527 int checkGrantUriPermissionFromIntentLocked(int callingUid,
4528 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004529 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004530 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004531 + " from " + intent + "; flags=0x"
4532 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4533
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004534 if (targetPkg == null) {
4535 throw new NullPointerException("targetPkg");
4536 }
4537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004538 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004539 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004540 }
4541 Uri data = intent.getData();
4542 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004543 return -1;
4544 }
4545 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4546 intent.getFlags());
4547 }
4548
4549 /**
4550 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4551 */
4552 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
4553 String targetPkg, Intent intent, UriPermissionOwner owner) {
4554 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
4555 intent.getFlags(), owner);
4556 }
4557
4558 void grantUriPermissionFromIntentLocked(int callingUid,
4559 String targetPkg, Intent intent, UriPermissionOwner owner) {
4560 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
4561 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004562 return;
4563 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004564
4565 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 }
4567
4568 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4569 Uri uri, int modeFlags) {
4570 synchronized(this) {
4571 final ProcessRecord r = getRecordForAppLocked(caller);
4572 if (r == null) {
4573 throw new SecurityException("Unable to find app for caller "
4574 + caller
4575 + " when granting permission to uri " + uri);
4576 }
4577 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004578 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004579 }
4580 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004581 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 }
4583
4584 grantUriPermissionLocked(r.info.uid, targetPkg, uri, modeFlags,
4585 null);
4586 }
4587 }
4588
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004589 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4591 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4592 HashMap<Uri, UriPermission> perms
4593 = mGrantedUriPermissions.get(perm.uid);
4594 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004595 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004596 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004597 perms.remove(perm.uri);
4598 if (perms.size() == 0) {
4599 mGrantedUriPermissions.remove(perm.uid);
4600 }
4601 }
4602 }
4603 }
4604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 private void revokeUriPermissionLocked(int callingUid, Uri uri,
4606 int modeFlags) {
4607 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4608 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4609 if (modeFlags == 0) {
4610 return;
4611 }
4612
Joe Onorato8a9b2202010-02-26 18:56:32 -08004613 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004614 "Revoking all granted permissions to " + uri);
4615
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004616 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617
4618 final String authority = uri.getAuthority();
4619 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004620 ContentProviderRecord cpr = mProvidersByName.get(authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 if (cpr != null) {
4622 pi = cpr.info;
4623 } else {
4624 try {
4625 pi = pm.resolveContentProvider(authority,
4626 PackageManager.GET_URI_PERMISSION_PATTERNS);
4627 } catch (RemoteException ex) {
4628 }
4629 }
4630 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004631 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 return;
4633 }
4634
4635 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07004636 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 // Right now, if you are not the original owner of the permission,
4638 // you are not allowed to revoke it.
4639 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4640 throw new SecurityException("Uid " + callingUid
4641 + " does not have permission to uri " + uri);
4642 //}
4643 }
4644
4645 // Go through all of the permissions and remove any that match.
4646 final List<String> SEGMENTS = uri.getPathSegments();
4647 if (SEGMENTS != null) {
4648 final int NS = SEGMENTS.size();
4649 int N = mGrantedUriPermissions.size();
4650 for (int i=0; i<N; i++) {
4651 HashMap<Uri, UriPermission> perms
4652 = mGrantedUriPermissions.valueAt(i);
4653 Iterator<UriPermission> it = perms.values().iterator();
4654 toploop:
4655 while (it.hasNext()) {
4656 UriPermission perm = it.next();
4657 Uri targetUri = perm.uri;
4658 if (!authority.equals(targetUri.getAuthority())) {
4659 continue;
4660 }
4661 List<String> targetSegments = targetUri.getPathSegments();
4662 if (targetSegments == null) {
4663 continue;
4664 }
4665 if (targetSegments.size() < NS) {
4666 continue;
4667 }
4668 for (int j=0; j<NS; j++) {
4669 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
4670 continue toploop;
4671 }
4672 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004673 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004674 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 perm.clearModes(modeFlags);
4676 if (perm.modeFlags == 0) {
4677 it.remove();
4678 }
4679 }
4680 if (perms.size() == 0) {
4681 mGrantedUriPermissions.remove(
4682 mGrantedUriPermissions.keyAt(i));
4683 N--;
4684 i--;
4685 }
4686 }
4687 }
4688 }
4689
4690 public void revokeUriPermission(IApplicationThread caller, Uri uri,
4691 int modeFlags) {
4692 synchronized(this) {
4693 final ProcessRecord r = getRecordForAppLocked(caller);
4694 if (r == null) {
4695 throw new SecurityException("Unable to find app for caller "
4696 + caller
4697 + " when revoking permission to uri " + uri);
4698 }
4699 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004700 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004701 return;
4702 }
4703
4704 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4705 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4706 if (modeFlags == 0) {
4707 return;
4708 }
4709
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004710 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004711
4712 final String authority = uri.getAuthority();
4713 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004714 ContentProviderRecord cpr = mProvidersByName.get(authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 if (cpr != null) {
4716 pi = cpr.info;
4717 } else {
4718 try {
4719 pi = pm.resolveContentProvider(authority,
4720 PackageManager.GET_URI_PERMISSION_PATTERNS);
4721 } catch (RemoteException ex) {
4722 }
4723 }
4724 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004725 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004726 return;
4727 }
4728
4729 revokeUriPermissionLocked(r.info.uid, uri, modeFlags);
4730 }
4731 }
4732
Dianne Hackborn7e269642010-08-25 19:50:20 -07004733 @Override
4734 public IBinder newUriPermissionOwner(String name) {
4735 synchronized(this) {
4736 UriPermissionOwner owner = new UriPermissionOwner(this, name);
4737 return owner.getExternalTokenLocked();
4738 }
4739 }
4740
4741 @Override
4742 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
4743 Uri uri, int modeFlags) {
4744 synchronized(this) {
4745 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
4746 if (owner == null) {
4747 throw new IllegalArgumentException("Unknown owner: " + token);
4748 }
4749 if (fromUid != Binder.getCallingUid()) {
4750 if (Binder.getCallingUid() != Process.myUid()) {
4751 // Only system code can grant URI permissions on behalf
4752 // of other users.
4753 throw new SecurityException("nice try");
4754 }
4755 }
4756 if (targetPkg == null) {
4757 throw new IllegalArgumentException("null target");
4758 }
4759 if (uri == null) {
4760 throw new IllegalArgumentException("null uri");
4761 }
4762
4763 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
4764 }
4765 }
4766
4767 @Override
4768 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
4769 synchronized(this) {
4770 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
4771 if (owner == null) {
4772 throw new IllegalArgumentException("Unknown owner: " + token);
4773 }
4774
4775 if (uri == null) {
4776 owner.removeUriPermissionsLocked(mode);
4777 } else {
4778 owner.removeUriPermissionLocked(uri, mode);
4779 }
4780 }
4781 }
4782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004783 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
4784 synchronized (this) {
4785 ProcessRecord app =
4786 who != null ? getRecordForAppLocked(who) : null;
4787 if (app == null) return;
4788
4789 Message msg = Message.obtain();
4790 msg.what = WAIT_FOR_DEBUGGER_MSG;
4791 msg.obj = app;
4792 msg.arg1 = waiting ? 1 : 0;
4793 mHandler.sendMessage(msg);
4794 }
4795 }
4796
4797 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
4798 outInfo.availMem = Process.getFreeMemory();
The Android Open Source Project4df24232009-03-05 14:34:35 -08004799 outInfo.threshold = HOME_APP_MEM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004800 outInfo.lowMemory = outInfo.availMem <
The Android Open Source Project4df24232009-03-05 14:34:35 -08004801 (HOME_APP_MEM + ((HIDDEN_APP_MEM-HOME_APP_MEM)/2));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004802 }
4803
4804 // =========================================================
4805 // TASK MANAGEMENT
4806 // =========================================================
4807
4808 public List getTasks(int maxNum, int flags,
4809 IThumbnailReceiver receiver) {
4810 ArrayList list = new ArrayList();
4811
4812 PendingThumbnailsRecord pending = null;
4813 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004814 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004815
4816 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004817 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
4819 + ", receiver=" + receiver);
4820
4821 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
4822 != PackageManager.PERMISSION_GRANTED) {
4823 if (receiver != null) {
4824 // If the caller wants to wait for pending thumbnails,
4825 // it ain't gonna get them.
4826 try {
4827 receiver.finished();
4828 } catch (RemoteException ex) {
4829 }
4830 }
4831 String msg = "Permission Denial: getTasks() from pid="
4832 + Binder.getCallingPid()
4833 + ", uid=" + Binder.getCallingUid()
4834 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004835 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004836 throw new SecurityException(msg);
4837 }
4838
Dianne Hackbornd2835932010-12-13 16:28:46 -08004839 final boolean canReadFb = (flags&ActivityManager.TASKS_GET_THUMBNAILS) != 0
4840 && checkCallingPermission(
4841 android.Manifest.permission.READ_FRAME_BUFFER)
4842 == PackageManager.PERMISSION_GRANTED;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004843
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004844 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004845 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004846 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004847 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 CharSequence topDescription = null;
4849 TaskRecord curTask = null;
4850 int numActivities = 0;
4851 int numRunning = 0;
4852 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004853 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004854 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004855 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004856
4857 // Initialize state for next task if needed.
4858 if (top == null ||
4859 (top.state == ActivityState.INITIALIZING
4860 && top.task == r.task)) {
4861 top = r;
4862 topDescription = r.description;
4863 curTask = r.task;
4864 numActivities = numRunning = 0;
4865 }
4866
4867 // Add 'r' into the current task.
4868 numActivities++;
4869 if (r.app != null && r.app.thread != null) {
4870 numRunning++;
4871 }
4872 if (topDescription == null) {
4873 topDescription = r.description;
4874 }
4875
Joe Onorato8a9b2202010-02-26 18:56:32 -08004876 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004877 TAG, r.intent.getComponent().flattenToShortString()
4878 + ": task=" + r.task);
4879
4880 // If the next one is a different task, generate a new
4881 // TaskInfo entry for what we have.
4882 if (next == null || next.task != curTask) {
4883 ActivityManager.RunningTaskInfo ci
4884 = new ActivityManager.RunningTaskInfo();
4885 ci.id = curTask.taskId;
4886 ci.baseActivity = r.intent.getComponent();
4887 ci.topActivity = top.intent.getComponent();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004888 if (canReadFb) {
4889 if (top.thumbnail != null) {
4890 ci.thumbnail = top.thumbnail;
4891 } else if (top.state == ActivityState.RESUMED) {
Dianne Hackbornd2835932010-12-13 16:28:46 -08004892 ci.thumbnail = top.stack.screenshotActivities(top);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004893 }
4894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 ci.description = topDescription;
4896 ci.numActivities = numActivities;
4897 ci.numRunning = numRunning;
4898 //System.out.println(
4899 // "#" + maxNum + ": " + " descr=" + ci.description);
4900 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004901 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 TAG, "State=" + top.state + "Idle=" + top.idle
4903 + " app=" + top.app
4904 + " thr=" + (top.app != null ? top.app.thread : null));
4905 if (top.state == ActivityState.RESUMED
4906 || top.state == ActivityState.PAUSING) {
4907 if (top.idle && top.app != null
4908 && top.app.thread != null) {
4909 topRecord = top;
4910 topThumbnail = top.app.thread;
4911 } else {
4912 top.thumbnailNeeded = true;
4913 }
4914 }
4915 if (pending == null) {
4916 pending = new PendingThumbnailsRecord(receiver);
4917 }
4918 pending.pendingRecords.add(top);
4919 }
4920 list.add(ci);
4921 maxNum--;
4922 top = null;
4923 }
4924 }
4925
4926 if (pending != null) {
4927 mPendingThumbnails.add(pending);
4928 }
4929 }
4930
Joe Onorato8a9b2202010-02-26 18:56:32 -08004931 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004932
4933 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004934 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004935 try {
4936 topThumbnail.requestThumbnail(topRecord);
4937 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004938 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 sendPendingThumbnail(null, topRecord, null, null, true);
4940 }
4941 }
4942
4943 if (pending == null && receiver != null) {
4944 // In this case all thumbnails were available and the client
4945 // is being asked to be told when the remaining ones come in...
4946 // which is unusually, since the top-most currently running
4947 // activity should never have a canned thumbnail! Oh well.
4948 try {
4949 receiver.finished();
4950 } catch (RemoteException ex) {
4951 }
4952 }
4953
4954 return list;
4955 }
4956
4957 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
4958 int flags) {
4959 synchronized (this) {
4960 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
4961 "getRecentTasks()");
4962
Dianne Hackbornd2835932010-12-13 16:28:46 -08004963 final boolean canReadFb = (flags&ActivityManager.TASKS_GET_THUMBNAILS) != 0
4964 && checkCallingPermission(
4965 android.Manifest.permission.READ_FRAME_BUFFER)
4966 == PackageManager.PERMISSION_GRANTED;
4967
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004968 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07004969
Dianne Hackbornd2835932010-12-13 16:28:46 -08004970 ActivityRecord resumed = mMainStack.mResumedActivity;
4971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004972 final int N = mRecentTasks.size();
4973 ArrayList<ActivityManager.RecentTaskInfo> res
4974 = new ArrayList<ActivityManager.RecentTaskInfo>(
4975 maxNum < N ? maxNum : N);
4976 for (int i=0; i<N && maxNum > 0; i++) {
4977 TaskRecord tr = mRecentTasks.get(i);
4978 if (((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
4979 || (tr.intent == null)
4980 || ((tr.intent.getFlags()
4981 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
4982 ActivityManager.RecentTaskInfo rti
4983 = new ActivityManager.RecentTaskInfo();
4984 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
4985 rti.baseIntent = new Intent(
4986 tr.intent != null ? tr.intent : tr.affinityIntent);
4987 rti.origActivity = tr.origActivity;
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07004988
Dianne Hackbornd2835932010-12-13 16:28:46 -08004989 if (canReadFb) {
4990 if (resumed != null && resumed.task == tr) {
4991 rti.thumbnail = resumed.stack.screenshotActivities(resumed);
4992 } else {
4993 rti.thumbnail = tr.lastThumbnail;
4994 }
4995 }
4996 rti.description = tr.lastDescription;
4997
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07004998 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
4999 // Check whether this activity is currently available.
5000 try {
5001 if (rti.origActivity != null) {
5002 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5003 continue;
5004 }
5005 } else if (rti.baseIntent != null) {
5006 if (pm.queryIntentActivities(rti.baseIntent,
5007 null, 0) == null) {
5008 continue;
5009 }
5010 }
5011 } catch (RemoteException e) {
5012 // Will never happen.
5013 }
5014 }
5015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 res.add(rti);
5017 maxNum--;
5018 }
5019 }
5020 return res;
5021 }
5022 }
5023
5024 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5025 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005026 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005027 TaskRecord jt = startTask;
5028
5029 // First look backwards
5030 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005031 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005032 if (r.task != jt) {
5033 jt = r.task;
5034 if (affinity.equals(jt.affinity)) {
5035 return j;
5036 }
5037 }
5038 }
5039
5040 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005041 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005042 jt = startTask;
5043 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005044 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005045 if (r.task != jt) {
5046 if (affinity.equals(jt.affinity)) {
5047 return j;
5048 }
5049 jt = r.task;
5050 }
5051 }
5052
5053 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005054 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005055 return N-1;
5056 }
5057
5058 return -1;
5059 }
5060
5061 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005062 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005063 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005064 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5066 "moveTaskToFront()");
5067
5068 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005069 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5070 Binder.getCallingUid(), "Task to front")) {
5071 return;
5072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005073 final long origId = Binder.clearCallingIdentity();
5074 try {
5075 int N = mRecentTasks.size();
5076 for (int i=0; i<N; i++) {
5077 TaskRecord tr = mRecentTasks.get(i);
5078 if (tr.taskId == task) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005079 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5080 // Caller wants the home activity moved with it. To accomplish this,
5081 // we'll just move the home task to the top first.
5082 mMainStack.moveHomeToFrontLocked();
5083 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005084 mMainStack.moveTaskToFrontLocked(tr, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005085 return;
5086 }
5087 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005088 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5089 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005090 if (hr.task.taskId == task) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005091 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5092 // Caller wants the home activity moved with it. To accomplish this,
5093 // we'll just move the home task to the top first.
5094 mMainStack.moveHomeToFrontLocked();
5095 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005096 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 return;
5098 }
5099 }
5100 } finally {
5101 Binder.restoreCallingIdentity(origId);
5102 }
5103 }
5104 }
5105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 public void moveTaskToBack(int task) {
5107 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5108 "moveTaskToBack()");
5109
5110 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005111 if (mMainStack.mResumedActivity != null
5112 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005113 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5114 Binder.getCallingUid(), "Task to back")) {
5115 return;
5116 }
5117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005119 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005120 Binder.restoreCallingIdentity(origId);
5121 }
5122 }
5123
5124 /**
5125 * Moves an activity, and all of the other activities within the same task, to the bottom
5126 * of the history stack. The activity's order within the task is unchanged.
5127 *
5128 * @param token A reference to the activity we wish to move
5129 * @param nonRoot If false then this only works if the activity is the root
5130 * of a task; if true it will work for any activity in a task.
5131 * @return Returns true if the move completed, false if not.
5132 */
5133 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
5134 synchronized(this) {
5135 final long origId = Binder.clearCallingIdentity();
5136 int taskId = getTaskForActivityLocked(token, !nonRoot);
5137 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005138 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 }
5140 Binder.restoreCallingIdentity(origId);
5141 }
5142 return false;
5143 }
5144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145 public void moveTaskBackwards(int task) {
5146 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5147 "moveTaskBackwards()");
5148
5149 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005150 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5151 Binder.getCallingUid(), "Task backwards")) {
5152 return;
5153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005154 final long origId = Binder.clearCallingIdentity();
5155 moveTaskBackwardsLocked(task);
5156 Binder.restoreCallingIdentity(origId);
5157 }
5158 }
5159
5160 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005161 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005162 }
5163
5164 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5165 synchronized(this) {
5166 return getTaskForActivityLocked(token, onlyRoot);
5167 }
5168 }
5169
5170 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005171 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005172 TaskRecord lastTask = null;
5173 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005174 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005175 if (r == token) {
5176 if (!onlyRoot || lastTask != r.task) {
5177 return r.task.taskId;
5178 }
5179 return -1;
5180 }
5181 lastTask = r.task;
5182 }
5183
5184 return -1;
5185 }
5186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005187 public void finishOtherInstances(IBinder token, ComponentName className) {
5188 synchronized(this) {
5189 final long origId = Binder.clearCallingIdentity();
5190
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005191 int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005192 TaskRecord lastTask = null;
5193 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005194 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005195 if (r.realActivity.equals(className)
5196 && r != token && lastTask != r.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005197 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 null, "others")) {
5199 i--;
5200 N--;
5201 }
5202 }
5203 lastTask = r.task;
5204 }
5205
5206 Binder.restoreCallingIdentity(origId);
5207 }
5208 }
5209
5210 // =========================================================
5211 // THUMBNAILS
5212 // =========================================================
5213
5214 public void reportThumbnail(IBinder token,
5215 Bitmap thumbnail, CharSequence description) {
5216 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5217 final long origId = Binder.clearCallingIdentity();
5218 sendPendingThumbnail(null, token, thumbnail, description, true);
5219 Binder.restoreCallingIdentity(origId);
5220 }
5221
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005222 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 Bitmap thumbnail, CharSequence description, boolean always) {
5224 TaskRecord task = null;
5225 ArrayList receivers = null;
5226
5227 //System.out.println("Send pending thumbnail: " + r);
5228
5229 synchronized(this) {
5230 if (r == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005231 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005232 if (index < 0) {
5233 return;
5234 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005235 r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005236 }
5237 if (thumbnail == null) {
5238 thumbnail = r.thumbnail;
5239 description = r.description;
5240 }
5241 if (thumbnail == null && !always) {
5242 // If there is no thumbnail, and this entry is not actually
5243 // going away, then abort for now and pick up the next
5244 // thumbnail we get.
5245 return;
5246 }
5247 task = r.task;
5248
5249 int N = mPendingThumbnails.size();
5250 int i=0;
5251 while (i<N) {
5252 PendingThumbnailsRecord pr =
5253 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5254 //System.out.println("Looking in " + pr.pendingRecords);
5255 if (pr.pendingRecords.remove(r)) {
5256 if (receivers == null) {
5257 receivers = new ArrayList();
5258 }
5259 receivers.add(pr);
5260 if (pr.pendingRecords.size() == 0) {
5261 pr.finished = true;
5262 mPendingThumbnails.remove(i);
5263 N--;
5264 continue;
5265 }
5266 }
5267 i++;
5268 }
5269 }
5270
5271 if (receivers != null) {
5272 final int N = receivers.size();
5273 for (int i=0; i<N; i++) {
5274 try {
5275 PendingThumbnailsRecord pr =
5276 (PendingThumbnailsRecord)receivers.get(i);
5277 pr.receiver.newThumbnail(
5278 task != null ? task.taskId : -1, thumbnail, description);
5279 if (pr.finished) {
5280 pr.receiver.finished();
5281 }
5282 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005283 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005284 }
5285 }
5286 }
5287 }
5288
5289 // =========================================================
5290 // CONTENT PROVIDERS
5291 // =========================================================
5292
5293 private final List generateApplicationProvidersLocked(ProcessRecord app) {
5294 List providers = null;
5295 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005296 providers = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005297 queryContentProviders(app.processName, app.info.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005298 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005299 } catch (RemoteException ex) {
5300 }
5301 if (providers != null) {
5302 final int N = providers.size();
5303 for (int i=0; i<N; i++) {
5304 ProviderInfo cpi =
5305 (ProviderInfo)providers.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07005306 ContentProviderRecord cpr = mProvidersByClass.get(cpi.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005307 if (cpr == null) {
5308 cpr = new ContentProviderRecord(cpi, app.info);
5309 mProvidersByClass.put(cpi.name, cpr);
5310 }
5311 app.pubProviders.put(cpi.name, cpr);
5312 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005313 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 }
5315 }
5316 return providers;
5317 }
5318
5319 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005320 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005321 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
5322 final int callingUid = (r != null) ? r.info.uid : Binder.getCallingUid();
5323 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
5324 cpi.exported ? -1 : cpi.applicationInfo.uid)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005325 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005326 return null;
5327 }
5328 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
5329 cpi.exported ? -1 : cpi.applicationInfo.uid)
5330 == PackageManager.PERMISSION_GRANTED) {
5331 return null;
5332 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005333
5334 PathPermission[] pps = cpi.pathPermissions;
5335 if (pps != null) {
5336 int i = pps.length;
5337 while (i > 0) {
5338 i--;
5339 PathPermission pp = pps[i];
5340 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
5341 cpi.exported ? -1 : cpi.applicationInfo.uid)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005342 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005343 return null;
5344 }
5345 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
5346 cpi.exported ? -1 : cpi.applicationInfo.uid)
5347 == PackageManager.PERMISSION_GRANTED) {
5348 return null;
5349 }
5350 }
5351 }
5352
Dianne Hackbornb424b632010-08-18 15:59:05 -07005353 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5354 if (perms != null) {
5355 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5356 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5357 return null;
5358 }
5359 }
5360 }
5361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 String msg = "Permission Denial: opening provider " + cpi.name
5363 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5364 + ", uid=" + callingUid + ") requires "
5365 + cpi.readPermission + " or " + cpi.writePermission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005366 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367 return msg;
5368 }
5369
5370 private final ContentProviderHolder getContentProviderImpl(
5371 IApplicationThread caller, String name) {
5372 ContentProviderRecord cpr;
5373 ProviderInfo cpi = null;
5374
5375 synchronized(this) {
5376 ProcessRecord r = null;
5377 if (caller != null) {
5378 r = getRecordForAppLocked(caller);
5379 if (r == null) {
5380 throw new SecurityException(
5381 "Unable to find app for caller " + caller
5382 + " (pid=" + Binder.getCallingPid()
5383 + ") when getting content provider " + name);
5384 }
5385 }
5386
5387 // First check if this content provider has been published...
Dianne Hackborn860755f2010-06-03 18:47:52 -07005388 cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 if (cpr != null) {
5390 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005391 String msg;
5392 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5393 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005394 }
5395
5396 if (r != null && cpr.canRunHere(r)) {
5397 // This provider has been published or is in the process
5398 // of being published... but it is also allowed to run
5399 // in the caller's process, so don't make a connection
5400 // and just let the caller instantiate its own instance.
5401 if (cpr.provider != null) {
5402 // don't give caller the provider object, it needs
5403 // to make its own.
5404 cpr = new ContentProviderRecord(cpr);
5405 }
5406 return cpr;
5407 }
5408
5409 final long origId = Binder.clearCallingIdentity();
5410
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005411 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005412 // return it right away.
5413 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005414 if (DEBUG_PROVIDER) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005415 "Adding provider requested by "
5416 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005417 + cpr.info.processName);
5418 Integer cnt = r.conProviders.get(cpr);
5419 if (cnt == null) {
5420 r.conProviders.put(cpr, new Integer(1));
5421 } else {
5422 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424 cpr.clients.add(r);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005425 if (cpr.app != null && r.setAdj <= PERCEPTIBLE_APP_ADJ) {
5426 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005427 // make sure to count it as being accessed and thus
5428 // back up on the LRU list. This is good because
5429 // content providers are often expensive to start.
5430 updateLruProcessLocked(cpr.app, false, true);
5431 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07005432 } else {
5433 cpr.externals++;
5434 }
5435
5436 if (cpr.app != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005437 updateOomAdjLocked(cpr.app);
5438 }
5439
5440 Binder.restoreCallingIdentity(origId);
5441
5442 } else {
5443 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005444 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07005445 resolveContentProvider(name,
5446 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 } catch (RemoteException ex) {
5448 }
5449 if (cpi == null) {
5450 return null;
5451 }
5452
Dianne Hackbornb424b632010-08-18 15:59:05 -07005453 String msg;
5454 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5455 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456 }
5457
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07005458 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005459 && !cpi.processName.equals("system")) {
5460 // If this content provider does not run in the system
5461 // process, and the system is not yet ready to run other
5462 // processes, then fail fast instead of hanging.
5463 throw new IllegalArgumentException(
5464 "Attempt to launch content provider before system ready");
5465 }
5466
Dianne Hackborn860755f2010-06-03 18:47:52 -07005467 cpr = mProvidersByClass.get(cpi.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 final boolean firstClass = cpr == null;
5469 if (firstClass) {
5470 try {
5471 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005472 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005473 getApplicationInfo(
5474 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005475 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005477 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 + cpi.name);
5479 return null;
5480 }
5481 cpr = new ContentProviderRecord(cpi, ai);
5482 } catch (RemoteException ex) {
5483 // pm is in same process, this will never happen.
5484 }
5485 }
5486
5487 if (r != null && cpr.canRunHere(r)) {
5488 // If this is a multiprocess provider, then just return its
5489 // info and allow the caller to instantiate it. Only do
5490 // this if the provider is the same user as the caller's
5491 // process, or can run as root (so can be in any process).
5492 return cpr;
5493 }
5494
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005495 if (DEBUG_PROVIDER) {
5496 RuntimeException e = new RuntimeException("here");
Joe Onorato8a9b2202010-02-26 18:56:32 -08005497 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.info.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005498 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 }
5500
5501 // This is single process, and our app is now connecting to it.
5502 // See if we are already in the process of launching this
5503 // provider.
5504 final int N = mLaunchingProviders.size();
5505 int i;
5506 for (i=0; i<N; i++) {
5507 if (mLaunchingProviders.get(i) == cpr) {
5508 break;
5509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 }
5511
5512 // If the provider is not already being launched, then get it
5513 // started.
5514 if (i >= N) {
5515 final long origId = Binder.clearCallingIdentity();
5516 ProcessRecord proc = startProcessLocked(cpi.processName,
5517 cpr.appInfo, false, 0, "content provider",
5518 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005519 cpi.name), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005521 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 + cpi.applicationInfo.packageName + "/"
5523 + cpi.applicationInfo.uid + " for provider "
5524 + name + ": process is bad");
5525 return null;
5526 }
5527 cpr.launchingApp = proc;
5528 mLaunchingProviders.add(cpr);
5529 Binder.restoreCallingIdentity(origId);
5530 }
5531
5532 // Make sure the provider is published (the same provider class
5533 // may be published under multiple names).
5534 if (firstClass) {
5535 mProvidersByClass.put(cpi.name, cpr);
5536 }
5537 mProvidersByName.put(name, cpr);
5538
5539 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005540 if (DEBUG_PROVIDER) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005541 "Adding provider requested by "
5542 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005543 + cpr.info.processName);
5544 Integer cnt = r.conProviders.get(cpr);
5545 if (cnt == null) {
5546 r.conProviders.put(cpr, new Integer(1));
5547 } else {
5548 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 cpr.clients.add(r);
5551 } else {
5552 cpr.externals++;
5553 }
5554 }
5555 }
5556
5557 // Wait for the provider to be published...
5558 synchronized (cpr) {
5559 while (cpr.provider == null) {
5560 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005561 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005562 + cpi.applicationInfo.packageName + "/"
5563 + cpi.applicationInfo.uid + " for provider "
5564 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08005565 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 cpi.applicationInfo.packageName,
5567 cpi.applicationInfo.uid, name);
5568 return null;
5569 }
5570 try {
5571 cpr.wait();
5572 } catch (InterruptedException ex) {
5573 }
5574 }
5575 }
5576 return cpr;
5577 }
5578
5579 public final ContentProviderHolder getContentProvider(
5580 IApplicationThread caller, String name) {
5581 if (caller == null) {
5582 String msg = "null IApplicationThread when getting content provider "
5583 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005584 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 throw new SecurityException(msg);
5586 }
5587
5588 return getContentProviderImpl(caller, name);
5589 }
5590
5591 private ContentProviderHolder getContentProviderExternal(String name) {
5592 return getContentProviderImpl(null, name);
5593 }
5594
5595 /**
5596 * Drop a content provider from a ProcessRecord's bookkeeping
5597 * @param cpr
5598 */
5599 public void removeContentProvider(IApplicationThread caller, String name) {
5600 synchronized (this) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005601 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005603 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08005604 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005605 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 return;
5607 }
5608 final ProcessRecord r = getRecordForAppLocked(caller);
5609 if (r == null) {
5610 throw new SecurityException(
5611 "Unable to find app for caller " + caller +
5612 " when removing content provider " + name);
5613 }
5614 //update content provider record entry info
Dianne Hackborn860755f2010-06-03 18:47:52 -07005615 ContentProviderRecord localCpr = mProvidersByClass.get(cpr.info.name);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005616 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005617 + r.info.processName + " from process "
5618 + localCpr.appInfo.processName);
5619 if (localCpr.app == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005620 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08005621 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005622 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 return;
5624 } else {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005625 Integer cnt = r.conProviders.get(localCpr);
5626 if (cnt == null || cnt.intValue() <= 1) {
5627 localCpr.clients.remove(r);
5628 r.conProviders.remove(localCpr);
5629 } else {
5630 r.conProviders.put(localCpr, new Integer(cnt.intValue()-1));
5631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 }
5633 updateOomAdjLocked();
5634 }
5635 }
5636
5637 private void removeContentProviderExternal(String name) {
5638 synchronized (this) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005639 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 if(cpr == null) {
5641 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08005642 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 return;
5644 }
5645
5646 //update content provider record entry info
Dianne Hackborn860755f2010-06-03 18:47:52 -07005647 ContentProviderRecord localCpr = mProvidersByClass.get(cpr.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005648 localCpr.externals--;
5649 if (localCpr.externals < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005650 Slog.e(TAG, "Externals < 0 for content provider " + localCpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 }
5652 updateOomAdjLocked();
5653 }
5654 }
5655
5656 public final void publishContentProviders(IApplicationThread caller,
5657 List<ContentProviderHolder> providers) {
5658 if (providers == null) {
5659 return;
5660 }
5661
5662 synchronized(this) {
5663 final ProcessRecord r = getRecordForAppLocked(caller);
5664 if (r == null) {
5665 throw new SecurityException(
5666 "Unable to find app for caller " + caller
5667 + " (pid=" + Binder.getCallingPid()
5668 + ") when publishing content providers");
5669 }
5670
5671 final long origId = Binder.clearCallingIdentity();
5672
5673 final int N = providers.size();
5674 for (int i=0; i<N; i++) {
5675 ContentProviderHolder src = providers.get(i);
5676 if (src == null || src.info == null || src.provider == null) {
5677 continue;
5678 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005679 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 if (dst != null) {
5681 mProvidersByClass.put(dst.info.name, dst);
5682 String names[] = dst.info.authority.split(";");
5683 for (int j = 0; j < names.length; j++) {
5684 mProvidersByName.put(names[j], dst);
5685 }
5686
5687 int NL = mLaunchingProviders.size();
5688 int j;
5689 for (j=0; j<NL; j++) {
5690 if (mLaunchingProviders.get(j) == dst) {
5691 mLaunchingProviders.remove(j);
5692 j--;
5693 NL--;
5694 }
5695 }
5696 synchronized (dst) {
5697 dst.provider = src.provider;
5698 dst.app = r;
5699 dst.notifyAll();
5700 }
5701 updateOomAdjLocked(r);
5702 }
5703 }
5704
5705 Binder.restoreCallingIdentity(origId);
5706 }
5707 }
5708
5709 public static final void installSystemProviders() {
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08005710 List providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06005711 synchronized (mSelf) {
5712 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
5713 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08005714 if (providers != null) {
5715 for (int i=providers.size()-1; i>=0; i--) {
5716 ProviderInfo pi = (ProviderInfo)providers.get(i);
5717 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5718 Slog.w(TAG, "Not installing system proc provider " + pi.name
5719 + ": not system .apk");
5720 providers.remove(i);
5721 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005722 }
5723 }
5724 }
Josh Bartel2ecce342010-02-25 10:55:48 -06005725 if (providers != null) {
5726 mSystemThread.installSystemProviders(providers);
5727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005728 }
5729
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07005730 /**
5731 * Allows app to retrieve the MIME type of a URI without having permission
5732 * to access its content provider.
5733 *
5734 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
5735 *
5736 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
5737 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
5738 */
5739 public String getProviderMimeType(Uri uri) {
5740 final String name = uri.getAuthority();
5741 final long ident = Binder.clearCallingIdentity();
5742 ContentProviderHolder holder = null;
5743
5744 try {
5745 holder = getContentProviderExternal(name);
5746 if (holder != null) {
5747 return holder.provider.getType(uri);
5748 }
5749 } catch (RemoteException e) {
5750 Log.w(TAG, "Content provider dead retrieving " + uri, e);
5751 return null;
5752 } finally {
5753 if (holder != null) {
5754 removeContentProviderExternal(name);
5755 }
5756 Binder.restoreCallingIdentity(ident);
5757 }
5758
5759 return null;
5760 }
5761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 // =========================================================
5763 // GLOBAL MANAGEMENT
5764 // =========================================================
5765
5766 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
5767 ApplicationInfo info, String customProcess) {
5768 String proc = customProcess != null ? customProcess : info.processName;
5769 BatteryStatsImpl.Uid.Proc ps = null;
5770 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
5771 synchronized (stats) {
5772 ps = stats.getProcessStatsLocked(info.uid, proc);
5773 }
5774 return new ProcessRecord(ps, thread, info, proc);
5775 }
5776
5777 final ProcessRecord addAppLocked(ApplicationInfo info) {
5778 ProcessRecord app = getProcessRecordLocked(info.processName, info.uid);
5779
5780 if (app == null) {
5781 app = newProcessRecordLocked(null, info, null);
5782 mProcessNames.put(info.processName, info.uid, app);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08005783 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 }
5785
5786 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
5787 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
5788 app.persistent = true;
5789 app.maxAdj = CORE_SERVER_ADJ;
5790 }
5791 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
5792 mPersistentStartingProcesses.add(app);
5793 startProcessLocked(app, "added application", app.processName);
5794 }
5795
5796 return app;
5797 }
5798
5799 public void unhandledBack() {
5800 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
5801 "unhandledBack()");
5802
5803 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005804 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08005805 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005806 TAG, "Performing unhandledBack(): stack size = " + count);
5807 if (count > 1) {
5808 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005809 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005810 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
5811 Binder.restoreCallingIdentity(origId);
5812 }
5813 }
5814 }
5815
5816 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
5817 String name = uri.getAuthority();
5818 ContentProviderHolder cph = getContentProviderExternal(name);
5819 ParcelFileDescriptor pfd = null;
5820 if (cph != null) {
5821 // We record the binder invoker's uid in thread-local storage before
5822 // going to the content provider to open the file. Later, in the code
5823 // that handles all permissions checks, we look for this uid and use
5824 // that rather than the Activity Manager's own uid. The effect is that
5825 // we do the check against the caller's permissions even though it looks
5826 // to the content provider like the Activity Manager itself is making
5827 // the request.
5828 sCallerIdentity.set(new Identity(
5829 Binder.getCallingPid(), Binder.getCallingUid()));
5830 try {
5831 pfd = cph.provider.openFile(uri, "r");
5832 } catch (FileNotFoundException e) {
5833 // do nothing; pfd will be returned null
5834 } finally {
5835 // Ensure that whatever happens, we clean up the identity state
5836 sCallerIdentity.remove();
5837 }
5838
5839 // We've got the fd now, so we're done with the provider.
5840 removeContentProviderExternal(name);
5841 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005842 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 }
5844 return pfd;
5845 }
5846
5847 public void goingToSleep() {
5848 synchronized(this) {
5849 mSleeping = true;
5850 mWindowManager.setEventDispatching(false);
5851
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005852 if (mMainStack.mResumedActivity != null) {
5853 mMainStack.pauseIfSleepingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005854 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005855 Slog.w(TAG, "goingToSleep with no resumed activity!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005857
5858 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07005859 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005860 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
5861 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07005862 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 }
5864 }
5865
Dianne Hackborn55280a92009-05-07 15:53:46 -07005866 public boolean shutdown(int timeout) {
5867 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
5868 != PackageManager.PERMISSION_GRANTED) {
5869 throw new SecurityException("Requires permission "
5870 + android.Manifest.permission.SHUTDOWN);
5871 }
5872
5873 boolean timedout = false;
5874
5875 synchronized(this) {
5876 mShuttingDown = true;
5877 mWindowManager.setEventDispatching(false);
5878
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005879 if (mMainStack.mResumedActivity != null) {
5880 mMainStack.pauseIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07005881 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005882 while (mMainStack.mResumedActivity != null
5883 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07005884 long delay = endTime - System.currentTimeMillis();
5885 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005886 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07005887 timedout = true;
5888 break;
5889 }
5890 try {
5891 this.wait();
5892 } catch (InterruptedException e) {
5893 }
5894 }
5895 }
5896 }
5897
5898 mUsageStatsService.shutdown();
5899 mBatteryStatsService.shutdown();
5900
5901 return timedout;
5902 }
5903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005904 public void wakingUp() {
5905 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005906 if (mMainStack.mGoingToSleep.isHeld()) {
5907 mMainStack.mGoingToSleep.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005908 }
5909 mWindowManager.setEventDispatching(true);
5910 mSleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005911 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 }
5913 }
5914
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005915 public void stopAppSwitches() {
5916 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
5917 != PackageManager.PERMISSION_GRANTED) {
5918 throw new SecurityException("Requires permission "
5919 + android.Manifest.permission.STOP_APP_SWITCHES);
5920 }
5921
5922 synchronized(this) {
5923 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
5924 + APP_SWITCH_DELAY_TIME;
5925 mDidAppSwitch = false;
5926 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
5927 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
5928 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
5929 }
5930 }
5931
5932 public void resumeAppSwitches() {
5933 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
5934 != PackageManager.PERMISSION_GRANTED) {
5935 throw new SecurityException("Requires permission "
5936 + android.Manifest.permission.STOP_APP_SWITCHES);
5937 }
5938
5939 synchronized(this) {
5940 // Note that we don't execute any pending app switches... we will
5941 // let those wait until either the timeout, or the next start
5942 // activity request.
5943 mAppSwitchesAllowedTime = 0;
5944 }
5945 }
5946
5947 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
5948 String name) {
5949 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
5950 return true;
5951 }
5952
5953 final int perm = checkComponentPermission(
5954 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
5955 callingUid, -1);
5956 if (perm == PackageManager.PERMISSION_GRANTED) {
5957 return true;
5958 }
5959
Joe Onorato8a9b2202010-02-26 18:56:32 -08005960 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005961 return false;
5962 }
5963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005964 public void setDebugApp(String packageName, boolean waitForDebugger,
5965 boolean persistent) {
5966 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
5967 "setDebugApp()");
5968
5969 // Note that this is not really thread safe if there are multiple
5970 // callers into it at the same time, but that's not a situation we
5971 // care about.
5972 if (persistent) {
5973 final ContentResolver resolver = mContext.getContentResolver();
5974 Settings.System.putString(
5975 resolver, Settings.System.DEBUG_APP,
5976 packageName);
5977 Settings.System.putInt(
5978 resolver, Settings.System.WAIT_FOR_DEBUGGER,
5979 waitForDebugger ? 1 : 0);
5980 }
5981
5982 synchronized (this) {
5983 if (!persistent) {
5984 mOrigDebugApp = mDebugApp;
5985 mOrigWaitForDebugger = mWaitForDebugger;
5986 }
5987 mDebugApp = packageName;
5988 mWaitForDebugger = waitForDebugger;
5989 mDebugTransient = !persistent;
5990 if (packageName != null) {
5991 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005992 forceStopPackageLocked(packageName, -1, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 Binder.restoreCallingIdentity(origId);
5994 }
5995 }
5996 }
5997
5998 public void setAlwaysFinish(boolean enabled) {
5999 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6000 "setAlwaysFinish()");
6001
6002 Settings.System.putInt(
6003 mContext.getContentResolver(),
6004 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6005
6006 synchronized (this) {
6007 mAlwaysFinishActivities = enabled;
6008 }
6009 }
6010
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006011 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006013 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006015 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006016 }
6017 }
6018
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006019 public boolean isUserAMonkey() {
6020 // For now the fact that there is a controller implies
6021 // we have a monkey.
6022 synchronized (this) {
6023 return mController != null;
6024 }
6025 }
6026
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006027 public void registerActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06006028 synchronized (this) {
6029 mWatchers.register(watcher);
6030 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006031 }
6032
6033 public void unregisterActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06006034 synchronized (this) {
6035 mWatchers.unregister(watcher);
6036 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006037 }
6038
Daniel Sandler69a48172010-06-23 16:29:36 -04006039 public void setImmersive(IBinder token, boolean immersive) {
6040 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006041 int index = (token != null) ? mMainStack.indexOfTokenLocked(token) : -1;
Daniel Sandler69a48172010-06-23 16:29:36 -04006042 if (index < 0) {
6043 throw new IllegalArgumentException();
6044 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006045 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
Daniel Sandler69a48172010-06-23 16:29:36 -04006046 r.immersive = immersive;
6047 }
6048 }
6049
6050 public boolean isImmersive(IBinder token) {
6051 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006052 int index = (token != null) ? mMainStack.indexOfTokenLocked(token) : -1;
Daniel Sandler69a48172010-06-23 16:29:36 -04006053 if (index < 0) {
6054 throw new IllegalArgumentException();
6055 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006056 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
Daniel Sandler69a48172010-06-23 16:29:36 -04006057 return r.immersive;
6058 }
6059 }
6060
6061 public boolean isTopActivityImmersive() {
6062 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006063 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006064 return (r != null) ? r.immersive : false;
6065 }
6066 }
6067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 public final void enterSafeMode() {
6069 synchronized(this) {
6070 // It only makes sense to do this before the system is ready
6071 // and started launching other packages.
6072 if (!mSystemReady) {
6073 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006074 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006075 } catch (RemoteException e) {
6076 }
6077
6078 View v = LayoutInflater.from(mContext).inflate(
6079 com.android.internal.R.layout.safe_mode, null);
6080 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Jeff Brown3b2b3542010-10-15 00:54:27 -07006081 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6083 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6084 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6085 lp.format = v.getBackground().getOpacity();
6086 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6087 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6088 ((WindowManager)mContext.getSystemService(
6089 Context.WINDOW_SERVICE)).addView(v, lp);
6090 }
6091 }
6092 }
6093
6094 public void noteWakeupAlarm(IIntentSender sender) {
6095 if (!(sender instanceof PendingIntentRecord)) {
6096 return;
6097 }
6098 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6099 synchronized (stats) {
6100 if (mBatteryStatsService.isOnBattery()) {
6101 mBatteryStatsService.enforceCallingPermission();
6102 PendingIntentRecord rec = (PendingIntentRecord)sender;
6103 int MY_UID = Binder.getCallingUid();
6104 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6105 BatteryStatsImpl.Uid.Pkg pkg =
6106 stats.getPackageStatsLocked(uid, rec.key.packageName);
6107 pkg.incWakeupsLocked();
6108 }
6109 }
6110 }
6111
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006112 public boolean killPids(int[] pids, String pReason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006114 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006116 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 // XXX Note: don't acquire main activity lock here, because the window
6118 // manager calls in with its locks held.
6119
6120 boolean killed = false;
6121 synchronized (mPidsSelfLocked) {
6122 int[] types = new int[pids.length];
6123 int worstType = 0;
6124 for (int i=0; i<pids.length; i++) {
6125 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6126 if (proc != null) {
6127 int type = proc.setAdj;
6128 types[i] = type;
6129 if (type > worstType) {
6130 worstType = type;
6131 }
6132 }
6133 }
6134
6135 // If the worse oom_adj is somewhere in the hidden proc LRU range,
6136 // then constrain it so we will kill all hidden procs.
6137 if (worstType < EMPTY_APP_ADJ && worstType > HIDDEN_APP_MIN_ADJ) {
6138 worstType = HIDDEN_APP_MIN_ADJ;
6139 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006140 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 for (int i=0; i<pids.length; i++) {
6142 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6143 if (proc == null) {
6144 continue;
6145 }
6146 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006147 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006148 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006149 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6150 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006152 proc.killedBackground = true;
6153 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 }
6155 }
6156 }
6157 return killed;
6158 }
6159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 public final void startRunning(String pkg, String cls, String action,
6161 String data) {
6162 synchronized(this) {
6163 if (mStartRunning) {
6164 return;
6165 }
6166 mStartRunning = true;
6167 mTopComponent = pkg != null && cls != null
6168 ? new ComponentName(pkg, cls) : null;
6169 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6170 mTopData = data;
6171 if (!mSystemReady) {
6172 return;
6173 }
6174 }
6175
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006176 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006177 }
6178
6179 private void retrieveSettings() {
6180 final ContentResolver resolver = mContext.getContentResolver();
6181 String debugApp = Settings.System.getString(
6182 resolver, Settings.System.DEBUG_APP);
6183 boolean waitForDebugger = Settings.System.getInt(
6184 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6185 boolean alwaysFinishActivities = Settings.System.getInt(
6186 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6187
6188 Configuration configuration = new Configuration();
6189 Settings.System.getConfiguration(resolver, configuration);
6190
6191 synchronized (this) {
6192 mDebugApp = mOrigDebugApp = debugApp;
6193 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6194 mAlwaysFinishActivities = alwaysFinishActivities;
6195 // This happens before any activities are started, so we can
6196 // change mConfiguration in-place.
6197 mConfiguration.updateFrom(configuration);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006198 mConfigurationSeq = mConfiguration.seq = 1;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006199 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 }
6201 }
6202
6203 public boolean testIsSystemReady() {
6204 // no need to synchronize(this) just to read & return the value
6205 return mSystemReady;
6206 }
6207
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006208 private static File getCalledPreBootReceiversFile() {
6209 File dataDir = Environment.getDataDirectory();
6210 File systemDir = new File(dataDir, "system");
6211 File fname = new File(systemDir, "called_pre_boots.dat");
6212 return fname;
6213 }
6214
6215 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6216 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6217 File file = getCalledPreBootReceiversFile();
6218 FileInputStream fis = null;
6219 try {
6220 fis = new FileInputStream(file);
6221 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
6222 int vers = dis.readInt();
6223 String codename = dis.readUTF();
6224 if (vers == android.os.Build.VERSION.SDK_INT
6225 && codename.equals(android.os.Build.VERSION.CODENAME)) {
6226 int num = dis.readInt();
6227 while (num > 0) {
6228 num--;
6229 String pkg = dis.readUTF();
6230 String cls = dis.readUTF();
6231 lastDoneReceivers.add(new ComponentName(pkg, cls));
6232 }
6233 }
6234 } catch (FileNotFoundException e) {
6235 } catch (IOException e) {
6236 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6237 } finally {
6238 if (fis != null) {
6239 try {
6240 fis.close();
6241 } catch (IOException e) {
6242 }
6243 }
6244 }
6245 return lastDoneReceivers;
6246 }
6247
6248 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
6249 File file = getCalledPreBootReceiversFile();
6250 FileOutputStream fos = null;
6251 DataOutputStream dos = null;
6252 try {
6253 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
6254 fos = new FileOutputStream(file);
6255 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
6256 dos.writeInt(android.os.Build.VERSION.SDK_INT);
6257 dos.writeUTF(android.os.Build.VERSION.CODENAME);
6258 dos.writeInt(list.size());
6259 for (int i=0; i<list.size(); i++) {
6260 dos.writeUTF(list.get(i).getPackageName());
6261 dos.writeUTF(list.get(i).getClassName());
6262 }
6263 } catch (IOException e) {
6264 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
6265 file.delete();
6266 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006267 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006268 if (dos != null) {
6269 try {
6270 dos.close();
6271 } catch (IOException e) {
6272 // TODO Auto-generated catch block
6273 e.printStackTrace();
6274 }
6275 }
6276 }
6277 }
6278
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006279 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 // In the simulator, startRunning will never have been called, which
6281 // normally sets a few crucial variables. Do it here instead.
6282 if (!Process.supportsProcesses()) {
6283 mStartRunning = true;
6284 mTopAction = Intent.ACTION_MAIN;
6285 }
6286
6287 synchronized(this) {
6288 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006289 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 return;
6291 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006292
6293 // Check to see if there are any update receivers to run.
6294 if (!mDidUpdate) {
6295 if (mWaitingUpdate) {
6296 return;
6297 }
6298 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6299 List<ResolveInfo> ris = null;
6300 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006301 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006302 intent, null, 0);
6303 } catch (RemoteException e) {
6304 }
6305 if (ris != null) {
6306 for (int i=ris.size()-1; i>=0; i--) {
6307 if ((ris.get(i).activityInfo.applicationInfo.flags
6308 &ApplicationInfo.FLAG_SYSTEM) == 0) {
6309 ris.remove(i);
6310 }
6311 }
6312 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006313
6314 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
6315
6316 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006317 for (int i=0; i<ris.size(); i++) {
6318 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006319 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6320 if (lastDoneReceivers.contains(comp)) {
6321 ris.remove(i);
6322 i--;
6323 }
6324 }
6325
6326 for (int i=0; i<ris.size(); i++) {
6327 ActivityInfo ai = ris.get(i).activityInfo;
6328 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6329 doneReceivers.add(comp);
6330 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006331 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08006332 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006333 finisher = new IIntentReceiver.Stub() {
6334 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07006335 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006336 boolean sticky) {
6337 // The raw IIntentReceiver interface is called
6338 // with the AM lock held, so redispatch to
6339 // execute our code without the lock.
6340 mHandler.post(new Runnable() {
6341 public void run() {
6342 synchronized (ActivityManagerService.this) {
6343 mDidUpdate = true;
6344 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006345 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006346 systemReady(goingCallback);
6347 }
6348 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006349 }
6350 };
6351 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006352 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006353 broadcastIntentLocked(null, null, intent, null, finisher,
6354 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackbornd6847842010-01-12 18:14:19 -08006355 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006356 mWaitingUpdate = true;
6357 }
6358 }
6359 }
6360 if (mWaitingUpdate) {
6361 return;
6362 }
6363 mDidUpdate = true;
6364 }
6365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 mSystemReady = true;
6367 if (!mStartRunning) {
6368 return;
6369 }
6370 }
6371
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006372 ArrayList<ProcessRecord> procsToKill = null;
6373 synchronized(mPidsSelfLocked) {
6374 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
6375 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
6376 if (!isAllowedWhileBooting(proc.info)){
6377 if (procsToKill == null) {
6378 procsToKill = new ArrayList<ProcessRecord>();
6379 }
6380 procsToKill.add(proc);
6381 }
6382 }
6383 }
6384
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006385 synchronized(this) {
6386 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006387 for (int i=procsToKill.size()-1; i>=0; i--) {
6388 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006389 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006390 removeProcessLocked(proc, true);
6391 }
6392 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006393
6394 // Now that we have cleaned up any update processes, we
6395 // are ready to start launching real processes and know that
6396 // we won't trample on them any more.
6397 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006398 }
6399
Joe Onorato8a9b2202010-02-26 18:56:32 -08006400 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006401 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 SystemClock.uptimeMillis());
6403
6404 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006405 // Make sure we have no pre-ready processes sitting around.
6406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
6408 ResolveInfo ri = mContext.getPackageManager()
6409 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07006410 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 CharSequence errorMsg = null;
6412 if (ri != null) {
6413 ActivityInfo ai = ri.activityInfo;
6414 ApplicationInfo app = ai.applicationInfo;
6415 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6416 mTopAction = Intent.ACTION_FACTORY_TEST;
6417 mTopData = null;
6418 mTopComponent = new ComponentName(app.packageName,
6419 ai.name);
6420 } else {
6421 errorMsg = mContext.getResources().getText(
6422 com.android.internal.R.string.factorytest_not_system);
6423 }
6424 } else {
6425 errorMsg = mContext.getResources().getText(
6426 com.android.internal.R.string.factorytest_no_action);
6427 }
6428 if (errorMsg != null) {
6429 mTopAction = null;
6430 mTopData = null;
6431 mTopComponent = null;
6432 Message msg = Message.obtain();
6433 msg.what = SHOW_FACTORY_ERROR_MSG;
6434 msg.getData().putCharSequence("msg", errorMsg);
6435 mHandler.sendMessage(msg);
6436 }
6437 }
6438 }
6439
6440 retrieveSettings();
6441
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006442 if (goingCallback != null) goingCallback.run();
6443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 synchronized (this) {
6445 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
6446 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006447 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006448 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 if (apps != null) {
6450 int N = apps.size();
6451 int i;
6452 for (i=0; i<N; i++) {
6453 ApplicationInfo info
6454 = (ApplicationInfo)apps.get(i);
6455 if (info != null &&
6456 !info.packageName.equals("android")) {
6457 addAppLocked(info);
6458 }
6459 }
6460 }
6461 } catch (RemoteException ex) {
6462 // pm is in same process, this will never happen.
6463 }
6464 }
6465
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006466 // Start up initial activity.
6467 mBooting = true;
6468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006470 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 Message msg = Message.obtain();
6472 msg.what = SHOW_UID_ERROR_MSG;
6473 mHandler.sendMessage(msg);
6474 }
6475 } catch (RemoteException e) {
6476 }
6477
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006478 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 }
6480 }
6481
Dan Egnorb7f03672009-12-09 16:22:32 -08006482 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006483 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006484 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08006485 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08006486 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 startAppProblemLocked(app);
6488 app.stopFreezingAllLocked();
6489 return handleAppCrashLocked(app);
6490 }
6491
Dan Egnorb7f03672009-12-09 16:22:32 -08006492 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006493 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08006495 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08006496 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
6497 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 startAppProblemLocked(app);
6499 app.stopFreezingAllLocked();
6500 }
6501
6502 /**
6503 * Generate a process error record, suitable for attachment to a ProcessRecord.
6504 *
6505 * @param app The ProcessRecord in which the error occurred.
6506 * @param condition Crashing, Application Not Responding, etc. Values are defined in
6507 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08006508 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006509 * @param shortMsg Short message describing the crash.
6510 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08006511 * @param stackTrace Full crash stack trace, may be null.
6512 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 * @return Returns a fully-formed AppErrorStateInfo record.
6514 */
6515 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006516 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006517 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08006518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 report.condition = condition;
6520 report.processName = app.processName;
6521 report.pid = app.pid;
6522 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08006523 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 report.shortMsg = shortMsg;
6525 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08006526 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527
6528 return report;
6529 }
6530
Dan Egnor42471dd2010-01-07 17:25:22 -08006531 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 synchronized (this) {
6533 app.crashing = false;
6534 app.crashingReport = null;
6535 app.notResponding = false;
6536 app.notRespondingReport = null;
6537 if (app.anrDialog == fromDialog) {
6538 app.anrDialog = null;
6539 }
6540 if (app.waitDialog == fromDialog) {
6541 app.waitDialog = null;
6542 }
6543 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08006544 handleAppCrashLocked(app);
Dianne Hackborn8633e682010-04-22 16:03:41 -07006545 Slog.i(ActivityManagerService.TAG, "Killing "
6546 + app.processName + " (pid=" + app.pid + "): user's request");
6547 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
6548 app.processName, app.setAdj, "user's request after error");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 Process.killProcess(app.pid);
6550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006551 }
6552 }
Dan Egnor42471dd2010-01-07 17:25:22 -08006553
Dan Egnorb7f03672009-12-09 16:22:32 -08006554 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006555 long now = SystemClock.uptimeMillis();
6556
6557 Long crashTime = mProcessCrashTimes.get(app.info.processName,
6558 app.info.uid);
6559 if (crashTime != null && now < crashTime+MIN_CRASH_INTERVAL) {
6560 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08006561 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006562 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006563 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006564 app.info.processName, app.info.uid);
6565 killServicesLocked(app, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006566 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6567 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006569 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006570 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006571 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 }
6573 }
6574 if (!app.persistent) {
6575 // We don't want to start this process again until the user
6576 // explicitly does so... but for persistent process, we really
6577 // need to keep it running. If a persistent process is actually
6578 // repeatedly crashing, then badness for everyone.
Doug Zongker2bec3d42009-12-04 12:52:44 -08006579 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 app.info.processName);
6581 mBadProcesses.put(app.info.processName, app.info.uid, now);
6582 app.bad = true;
6583 mProcessCrashTimes.remove(app.info.processName, app.info.uid);
6584 app.removed = true;
6585 removeProcessLocked(app, false);
6586 return false;
6587 }
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006588 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006589 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006590 if (r.app == app) {
6591 // If the top running activity is from this crashing
6592 // process, then terminate it to avoid getting in a loop.
6593 Slog.w(TAG, " Force finishing activity "
6594 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006595 int index = mMainStack.indexOfTokenLocked(r);
6596 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006597 Activity.RESULT_CANCELED, null, "crashed");
6598 // Also terminate an activities below it that aren't yet
6599 // stopped, to avoid a situation where one will get
6600 // re-start our crashing activity once it gets resumed again.
6601 index--;
6602 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006603 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006604 if (r.state == ActivityState.RESUMED
6605 || r.state == ActivityState.PAUSING
6606 || r.state == ActivityState.PAUSED) {
6607 if (!r.isHomeActivity) {
6608 Slog.w(TAG, " Force finishing activity "
6609 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006610 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006611 Activity.RESULT_CANCELED, null, "crashed");
6612 }
6613 }
6614 }
6615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 }
6617
6618 // Bump up the crash count of any services currently running in the proc.
6619 if (app.services.size() != 0) {
6620 // Any services running in the application need to be placed
6621 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07006622 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006623 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07006624 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006625 sr.crashCount++;
6626 }
6627 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02006628
6629 // If the crashing process is what we consider to be the "home process" and it has been
6630 // replaced by a third-party app, clear the package preferred activities from packages
6631 // with a home activity running in the process to prevent a repeatedly crashing app
6632 // from blocking the user to manually clear the list.
6633 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
6634 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
6635 Iterator it = mHomeProcess.activities.iterator();
6636 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07006637 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02006638 if (r.isHomeActivity) {
6639 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
6640 try {
6641 ActivityThread.getPackageManager()
6642 .clearPackagePreferredActivities(r.packageName);
6643 } catch (RemoteException c) {
6644 // pm is in same process, this will never happen.
6645 }
6646 }
6647 }
6648 }
6649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 mProcessCrashTimes.put(app.info.processName, app.info.uid, now);
6651 return true;
6652 }
6653
6654 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006655 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
6656 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006657 skipCurrentReceiverLocked(app);
6658 }
6659
6660 void skipCurrentReceiverLocked(ProcessRecord app) {
6661 boolean reschedule = false;
6662 BroadcastRecord r = app.curReceiver;
6663 if (r != null) {
6664 // The current broadcast is waiting for this app's receiver
6665 // to be finished. Looks like that's not going to happen, so
6666 // let the broadcast continue.
Jeff Brown4d94a762010-09-23 11:33:28 -07006667 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
6669 r.resultExtras, r.resultAbort, true);
6670 reschedule = true;
6671 }
6672 r = mPendingBroadcast;
6673 if (r != null && r.curApp == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006674 if (DEBUG_BROADCAST) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 "skip & discard pending app " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -07006676 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
6678 r.resultExtras, r.resultAbort, true);
6679 reschedule = true;
6680 }
6681 if (reschedule) {
6682 scheduleBroadcastsLocked();
6683 }
6684 }
6685
Dan Egnor60d87622009-12-16 16:32:58 -08006686 /**
6687 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
6688 * The application process will exit immediately after this call returns.
6689 * @param app object of the crashing app, null for the system server
6690 * @param crashInfo describing the exception
6691 */
6692 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
6693 ProcessRecord r = findAppProcess(app);
6694
6695 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
6696 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08006697 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08006698 crashInfo.exceptionClassName,
6699 crashInfo.exceptionMessage,
6700 crashInfo.throwFileName,
6701 crashInfo.throwLineNumber);
6702
Dan Egnor42471dd2010-01-07 17:25:22 -08006703 addErrorToDropBox("crash", r, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08006704
6705 crashApplication(r, crashInfo);
6706 }
6707
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006708 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006709 IBinder app,
6710 int violationMask,
6711 StrictMode.ViolationInfo info) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006712 ProcessRecord r = findAppProcess(app);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006713
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006714 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08006715 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006716 boolean logIt = true;
6717 synchronized (mAlreadyLoggedViolatedStacks) {
6718 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
6719 logIt = false;
6720 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006721 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006722 // the relative pain numbers, without logging all
6723 // the stack traces repeatedly. We'd want to do
6724 // likewise in the client code, which also does
6725 // dup suppression, before the Binder call.
6726 } else {
6727 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
6728 mAlreadyLoggedViolatedStacks.clear();
6729 }
6730 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
6731 }
6732 }
6733 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006734 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006735 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006736 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006737
6738 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
6739 AppErrorResult result = new AppErrorResult();
6740 synchronized (this) {
6741 final long origId = Binder.clearCallingIdentity();
6742
6743 Message msg = Message.obtain();
6744 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
6745 HashMap<String, Object> data = new HashMap<String, Object>();
6746 data.put("result", result);
6747 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006748 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006749 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006750 msg.obj = data;
6751 mHandler.sendMessage(msg);
6752
6753 Binder.restoreCallingIdentity(origId);
6754 }
6755 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07006756 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006757 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006758 }
6759
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006760 // Depending on the policy in effect, there could be a bunch of
6761 // these in quick succession so we try to batch these together to
6762 // minimize disk writes, number of dropbox entries, and maximize
6763 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006764 private void logStrictModeViolationToDropBox(
6765 ProcessRecord process,
6766 StrictMode.ViolationInfo info) {
6767 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006768 return;
6769 }
6770 final boolean isSystemApp = process == null ||
6771 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
6772 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
6773 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
6774 final DropBoxManager dbox = (DropBoxManager)
6775 mContext.getSystemService(Context.DROPBOX_SERVICE);
6776
6777 // Exit early if the dropbox isn't configured to accept this report type.
6778 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
6779
6780 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006781 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006782 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
6783 synchronized (sb) {
6784 bufferWasEmpty = sb.length() == 0;
6785 appendDropBoxProcessHeaders(process, sb);
6786 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
6787 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006788 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
6789 if (info.violationNumThisLoop != 0) {
6790 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
6791 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07006792 if (info.numAnimationsRunning != 0) {
6793 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
6794 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07006795 if (info.broadcastIntentAction != null) {
6796 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
6797 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08006798 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006799 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006800 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08006801 if (info.tags != null) {
6802 for (String tag : info.tags) {
6803 sb.append("Span-Tag: ").append(tag).append("\n");
6804 }
6805 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006806 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006807 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
6808 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006809 }
6810 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006811
6812 // Only buffer up to ~64k. Various logging bits truncate
6813 // things at 128k.
6814 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006815 }
6816
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006817 // Flush immediately if the buffer's grown too large, or this
6818 // is a non-system app. Non-system apps are isolated with a
6819 // different tag & policy and not batched.
6820 //
6821 // Batching is useful during internal testing with
6822 // StrictMode settings turned up high. Without batching,
6823 // thousands of separate files could be created on boot.
6824 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006825 new Thread("Error dump: " + dropboxTag) {
6826 @Override
6827 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006828 String report;
6829 synchronized (sb) {
6830 report = sb.toString();
6831 sb.delete(0, sb.length());
6832 sb.trimToSize();
6833 }
6834 if (report.length() != 0) {
6835 dbox.addText(dropboxTag, report);
6836 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006837 }
6838 }.start();
6839 return;
6840 }
6841
6842 // System app batching:
6843 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006844 // An existing dropbox-writing thread is outstanding, so
6845 // we don't need to start it up. The existing thread will
6846 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006847 return;
6848 }
6849
6850 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
6851 // (After this point, we shouldn't access AMS internal data structures.)
6852 new Thread("Error dump: " + dropboxTag) {
6853 @Override
6854 public void run() {
6855 // 5 second sleep to let stacks arrive and be batched together
6856 try {
6857 Thread.sleep(5000); // 5 seconds
6858 } catch (InterruptedException e) {}
6859
6860 String errorReport;
6861 synchronized (mStrictModeBuffer) {
6862 errorReport = mStrictModeBuffer.toString();
6863 if (errorReport.length() == 0) {
6864 return;
6865 }
6866 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
6867 mStrictModeBuffer.trimToSize();
6868 }
6869 dbox.addText(dropboxTag, errorReport);
6870 }
6871 }.start();
6872 }
6873
Dan Egnor60d87622009-12-16 16:32:58 -08006874 /**
6875 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
6876 * @param app object of the crashing app, null for the system server
6877 * @param tag reported by the caller
6878 * @param crashInfo describing the context of the error
6879 * @return true if the process should exit immediately (WTF is fatal)
6880 */
6881 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08006882 ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnor60d87622009-12-16 16:32:58 -08006883 ProcessRecord r = findAppProcess(app);
6884
6885 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
6886 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08006887 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08006888 tag, crashInfo.exceptionMessage);
6889
Dan Egnor42471dd2010-01-07 17:25:22 -08006890 addErrorToDropBox("wtf", r, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08006891
Doug Zongker43866e02010-01-07 12:09:54 -08006892 if (Settings.Secure.getInt(mContext.getContentResolver(),
6893 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08006894 crashApplication(r, crashInfo);
6895 return true;
6896 } else {
6897 return false;
6898 }
6899 }
6900
6901 /**
6902 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
6903 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
6904 */
6905 private ProcessRecord findAppProcess(IBinder app) {
6906 if (app == null) {
6907 return null;
6908 }
6909
6910 synchronized (this) {
6911 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
6912 final int NA = apps.size();
6913 for (int ia=0; ia<NA; ia++) {
6914 ProcessRecord p = apps.valueAt(ia);
6915 if (p.thread != null && p.thread.asBinder() == app) {
6916 return p;
6917 }
6918 }
6919 }
6920
Joe Onorato8a9b2202010-02-26 18:56:32 -08006921 Slog.w(TAG, "Can't find mystery application: " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08006922 return null;
6923 }
6924 }
6925
6926 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006927 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
6928 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08006929 */
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07006930 private void appendDropBoxProcessHeaders(ProcessRecord process, StringBuilder sb) {
6931 // Note: ProcessRecord 'process' is guarded by the service
6932 // instance. (notably process.pkgList, which could otherwise change
6933 // concurrently during execution of this method)
6934 synchronized (this) {
6935 if (process == null || process.pid == MY_PID) {
6936 sb.append("Process: system_server\n");
6937 } else {
6938 sb.append("Process: ").append(process.processName).append("\n");
6939 }
6940 if (process == null) {
6941 return;
6942 }
Dan Egnora455d192010-03-12 08:52:28 -08006943 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006944 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08006945 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
6946 for (String pkg : process.pkgList) {
6947 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08006948 try {
Dan Egnora455d192010-03-12 08:52:28 -08006949 PackageInfo pi = pm.getPackageInfo(pkg, 0);
6950 if (pi != null) {
6951 sb.append(" v").append(pi.versionCode);
6952 if (pi.versionName != null) {
6953 sb.append(" (").append(pi.versionName).append(")");
6954 }
6955 }
6956 } catch (RemoteException e) {
6957 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08006958 }
Dan Egnora455d192010-03-12 08:52:28 -08006959 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08006960 }
Dan Egnora455d192010-03-12 08:52:28 -08006961 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006962 }
6963
6964 private static String processClass(ProcessRecord process) {
6965 if (process == null || process.pid == MY_PID) {
6966 return "system_server";
6967 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6968 return "system_app";
6969 } else {
6970 return "data_app";
6971 }
6972 }
6973
6974 /**
6975 * Write a description of an error (crash, WTF, ANR) to the drop box.
6976 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
6977 * @param process which caused the error, null means the system server
6978 * @param activity which triggered the error, null if unknown
6979 * @param parent activity related to the error, null if unknown
6980 * @param subject line related to the error, null if absent
6981 * @param report in long form describing the error, null if absent
6982 * @param logFile to include in the report, null if none
6983 * @param crashInfo giving an application stack trace, null if absent
6984 */
6985 public void addErrorToDropBox(String eventType,
6986 ProcessRecord process, ActivityRecord activity, ActivityRecord parent, String subject,
6987 final String report, final File logFile,
6988 final ApplicationErrorReport.CrashInfo crashInfo) {
6989 // NOTE -- this must never acquire the ActivityManagerService lock,
6990 // otherwise the watchdog may be prevented from resetting the system.
6991
6992 final String dropboxTag = processClass(process) + "_" + eventType;
6993 final DropBoxManager dbox = (DropBoxManager)
6994 mContext.getSystemService(Context.DROPBOX_SERVICE);
6995
6996 // Exit early if the dropbox isn't configured to accept this report type.
6997 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
6998
6999 final StringBuilder sb = new StringBuilder(1024);
7000 appendDropBoxProcessHeaders(process, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007001 if (activity != null) {
7002 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7003 }
7004 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7005 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7006 }
7007 if (parent != null && parent != activity) {
7008 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7009 }
7010 if (subject != null) {
7011 sb.append("Subject: ").append(subject).append("\n");
7012 }
7013 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007014 if (Debug.isDebuggerConnected()) {
7015 sb.append("Debugger: Connected\n");
7016 }
Dan Egnora455d192010-03-12 08:52:28 -08007017 sb.append("\n");
7018
7019 // Do the rest in a worker thread to avoid blocking the caller on I/O
7020 // (After this point, we shouldn't access AMS internal data structures.)
7021 Thread worker = new Thread("Error dump: " + dropboxTag) {
7022 @Override
7023 public void run() {
7024 if (report != null) {
7025 sb.append(report);
7026 }
7027 if (logFile != null) {
7028 try {
7029 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7030 } catch (IOException e) {
7031 Slog.e(TAG, "Error reading " + logFile, e);
7032 }
7033 }
7034 if (crashInfo != null && crashInfo.stackTrace != null) {
7035 sb.append(crashInfo.stackTrace);
7036 }
7037
7038 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7039 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7040 if (lines > 0) {
7041 sb.append("\n");
7042
7043 // Merge several logcat streams, and take the last N lines
7044 InputStreamReader input = null;
7045 try {
7046 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7047 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7048 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7049
7050 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7051 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7052 input = new InputStreamReader(logcat.getInputStream());
7053
7054 int num;
7055 char[] buf = new char[8192];
7056 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7057 } catch (IOException e) {
7058 Slog.e(TAG, "Error running logcat", e);
7059 } finally {
7060 if (input != null) try { input.close(); } catch (IOException e) {}
7061 }
7062 }
7063
7064 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007065 }
Dan Egnora455d192010-03-12 08:52:28 -08007066 };
7067
7068 if (process == null || process.pid == MY_PID) {
7069 worker.run(); // We may be about to die -- need to run this synchronously
7070 } else {
7071 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007072 }
7073 }
7074
7075 /**
7076 * Bring up the "unexpected error" dialog box for a crashing app.
7077 * Deal with edge cases (intercepts from instrumented applications,
7078 * ActivityController, error intent receivers, that sort of thing).
7079 * @param r the application crashing
7080 * @param crashInfo describing the failure
7081 */
7082 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007083 long timeMillis = System.currentTimeMillis();
7084 String shortMsg = crashInfo.exceptionClassName;
7085 String longMsg = crashInfo.exceptionMessage;
7086 String stackTrace = crashInfo.stackTrace;
7087 if (shortMsg != null && longMsg != null) {
7088 longMsg = shortMsg + ": " + longMsg;
7089 } else if (shortMsg != null) {
7090 longMsg = shortMsg;
7091 }
7092
Dan Egnor60d87622009-12-16 16:32:58 -08007093 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007095 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007096 try {
7097 String name = r != null ? r.processName : null;
7098 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007099 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007100 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007101 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007102 + " at watcher's request");
7103 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007104 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007105 }
7106 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007107 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007108 }
7109 }
7110
7111 final long origId = Binder.clearCallingIdentity();
7112
7113 // If this process is running instrumentation, finish it.
7114 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007115 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007116 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007117 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7118 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 Bundle info = new Bundle();
7120 info.putString("shortMsg", shortMsg);
7121 info.putString("longMsg", longMsg);
7122 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7123 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007124 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007125 }
7126
Dan Egnor60d87622009-12-16 16:32:58 -08007127 // If we can't identify the process or it's already exceeded its crash quota,
7128 // quit right away without showing a crash dialog.
7129 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007130 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007131 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 }
7133
7134 Message msg = Message.obtain();
7135 msg.what = SHOW_ERROR_MSG;
7136 HashMap data = new HashMap();
7137 data.put("result", result);
7138 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007139 msg.obj = data;
7140 mHandler.sendMessage(msg);
7141
7142 Binder.restoreCallingIdentity(origId);
7143 }
7144
7145 int res = result.get();
7146
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007147 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007148 synchronized (this) {
7149 if (r != null) {
7150 mProcessCrashTimes.put(r.info.processName, r.info.uid,
7151 SystemClock.uptimeMillis());
7152 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007153 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007154 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007155 }
7156 }
7157
7158 if (appErrorIntent != null) {
7159 try {
7160 mContext.startActivity(appErrorIntent);
7161 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007162 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007165 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007166
7167 Intent createAppErrorIntentLocked(ProcessRecord r,
7168 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7169 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007170 if (report == null) {
7171 return null;
7172 }
7173 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7174 result.setComponent(r.errorReportReceiver);
7175 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7176 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7177 return result;
7178 }
7179
Dan Egnorb7f03672009-12-09 16:22:32 -08007180 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7181 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007182 if (r.errorReportReceiver == null) {
7183 return null;
7184 }
7185
7186 if (!r.crashing && !r.notResponding) {
7187 return null;
7188 }
7189
Dan Egnorb7f03672009-12-09 16:22:32 -08007190 ApplicationErrorReport report = new ApplicationErrorReport();
7191 report.packageName = r.info.packageName;
7192 report.installerPackageName = r.errorReportReceiver.getPackageName();
7193 report.processName = r.processName;
7194 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007195 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007196
Dan Egnorb7f03672009-12-09 16:22:32 -08007197 if (r.crashing) {
7198 report.type = ApplicationErrorReport.TYPE_CRASH;
7199 report.crashInfo = crashInfo;
7200 } else if (r.notResponding) {
7201 report.type = ApplicationErrorReport.TYPE_ANR;
7202 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007203
Dan Egnorb7f03672009-12-09 16:22:32 -08007204 report.anrInfo.activity = r.notRespondingReport.tag;
7205 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7206 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007207 }
7208
Dan Egnorb7f03672009-12-09 16:22:32 -08007209 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007210 }
7211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
7213 // assume our apps are happy - lazy create the list
7214 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7215
7216 synchronized (this) {
7217
7218 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007219 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7220 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007221 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7222 // This one's in trouble, so we'll generate a report for it
7223 // crashes are higher priority (in case there's a crash *and* an anr)
7224 ActivityManager.ProcessErrorStateInfo report = null;
7225 if (app.crashing) {
7226 report = app.crashingReport;
7227 } else if (app.notResponding) {
7228 report = app.notRespondingReport;
7229 }
7230
7231 if (report != null) {
7232 if (errList == null) {
7233 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
7234 }
7235 errList.add(report);
7236 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007237 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007238 " crashing = " + app.crashing +
7239 " notResponding = " + app.notResponding);
7240 }
7241 }
7242 }
7243 }
7244
7245 return errList;
7246 }
7247
7248 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
7249 // Lazy instantiation of list
7250 List<ActivityManager.RunningAppProcessInfo> runList = null;
7251 synchronized (this) {
7252 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007253 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7254 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
7256 // Generate process state info for running application
7257 ActivityManager.RunningAppProcessInfo currApp =
7258 new ActivityManager.RunningAppProcessInfo(app.processName,
7259 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07007260 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007261 if (mHeavyWeightProcess == app) {
Dianne Hackborn482566e2010-09-03 12:51:28 -07007262 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007263 }
Dianne Hackborn42499172010-10-15 18:45:07 -07007264 if (app.persistent) {
7265 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
7266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007267 int adj = app.curAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007268 if (adj >= EMPTY_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007269 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY;
7270 } else if (adj >= HIDDEN_APP_MIN_ADJ) {
7271 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
The Android Open Source Project4df24232009-03-05 14:34:35 -08007272 currApp.lru = adj - HIDDEN_APP_MIN_ADJ + 1;
7273 } else if (adj >= HOME_APP_ADJ) {
7274 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
7275 currApp.lru = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007276 } else if (adj >= SECONDARY_SERVER_ADJ) {
7277 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07007278 } else if (adj >= HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackborn5383f502010-10-22 12:59:20 -07007279 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07007280 } else if (adj >= PERCEPTIBLE_APP_ADJ) {
7281 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007282 } else if (adj >= VISIBLE_APP_ADJ) {
7283 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
7284 } else {
7285 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
7286 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007287 currApp.importanceReasonCode = app.adjTypeCode;
7288 if (app.adjSource instanceof ProcessRecord) {
7289 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007290 } else if (app.adjSource instanceof ActivityRecord) {
7291 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007292 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
7293 }
7294 if (app.adjTarget instanceof ComponentName) {
7295 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
7296 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007297 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007298 // + " lru=" + currApp.lru);
7299 if (runList == null) {
7300 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
7301 }
7302 runList.add(currApp);
7303 }
7304 }
7305 }
7306 return runList;
7307 }
7308
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007309 public List<ApplicationInfo> getRunningExternalApplications() {
7310 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
7311 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
7312 if (runningApps != null && runningApps.size() > 0) {
7313 Set<String> extList = new HashSet<String>();
7314 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
7315 if (app.pkgList != null) {
7316 for (String pkg : app.pkgList) {
7317 extList.add(pkg);
7318 }
7319 }
7320 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007321 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007322 for (String pkg : extList) {
7323 try {
7324 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
7325 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
7326 retList.add(info);
7327 }
7328 } catch (RemoteException e) {
7329 }
7330 }
7331 }
7332 return retList;
7333 }
7334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007335 @Override
7336 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007337 if (checkCallingPermission(android.Manifest.permission.DUMP)
7338 != PackageManager.PERMISSION_GRANTED) {
7339 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7340 + Binder.getCallingPid()
7341 + ", uid=" + Binder.getCallingUid()
7342 + " without permission "
7343 + android.Manifest.permission.DUMP);
7344 return;
7345 }
7346
7347 boolean dumpAll = false;
7348
7349 int opti = 0;
7350 while (opti < args.length) {
7351 String opt = args[opti];
7352 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7353 break;
7354 }
7355 opti++;
7356 if ("-a".equals(opt)) {
7357 dumpAll = true;
7358 } else if ("-h".equals(opt)) {
7359 pw.println("Activity manager dump options:");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007360 pw.println(" [-a] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007361 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07007362 pw.println(" a[ctivities]: activity stack state");
7363 pw.println(" b[roadcasts]: broadcast state");
7364 pw.println(" i[ntents]: pending intent state");
7365 pw.println(" p[rocesses]: process state");
7366 pw.println(" o[om]: out of memory management");
7367 pw.println(" prov[iders]: content provider state");
7368 pw.println(" s[ervices]: service state");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007369 pw.println(" service [name]: service client-side state");
Dianne Hackborn30d71892010-12-11 10:37:55 -08007370 pw.println(" cmd may also be a component name (com.foo/.myApp),");
7371 pw.println(" a partial substring in a component name, or an");
7372 pw.println(" ActivityRecord hex object identifier.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007374 } else {
7375 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007376 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007377 }
7378
7379 // Is the caller requesting to dump a particular piece of data?
7380 if (opti < args.length) {
7381 String cmd = args[opti];
7382 opti++;
7383 if ("activities".equals(cmd) || "a".equals(cmd)) {
7384 synchronized (this) {
7385 dumpActivitiesLocked(fd, pw, args, opti, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007387 return;
7388 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
7389 synchronized (this) {
7390 dumpBroadcastsLocked(fd, pw, args, opti, true);
7391 }
7392 return;
7393 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
7394 synchronized (this) {
7395 dumpPendingIntentsLocked(fd, pw, args, opti, true);
7396 }
7397 return;
7398 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
7399 synchronized (this) {
7400 dumpProcessesLocked(fd, pw, args, opti, true);
7401 }
7402 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07007403 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
7404 synchronized (this) {
7405 dumpOomLocked(fd, pw, args, opti, true);
7406 }
7407 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007408 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
7409 synchronized (this) {
7410 dumpProvidersLocked(fd, pw, args, opti, true);
7411 }
7412 return;
7413 } else if ("service".equals(cmd)) {
Joe Onoratoeb95b082010-10-21 14:54:19 -04007414 dumpService(fd, pw, args, opti);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007415 return;
7416 } else if ("services".equals(cmd) || "s".equals(cmd)) {
7417 synchronized (this) {
7418 dumpServicesLocked(fd, pw, args, opti, true);
7419 }
7420 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07007421 } else {
7422 // Dumping a single activity?
7423 if (dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
7424 return;
7425 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08007426 pw.println("Bad activity command, or no activities match: " + cmd);
7427 pw.println("Use -h for help.");
7428 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007430 }
7431
7432 // No piece of data specified, dump everything.
7433 synchronized (this) {
7434 boolean needSep;
7435 if (dumpAll) {
7436 pw.println("Providers in Current Activity Manager State:");
7437 }
7438 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll);
7439 if (needSep) {
7440 pw.println(" ");
7441 }
7442 if (dumpAll) {
7443 pw.println("-------------------------------------------------------------------------------");
7444 pw.println("Broadcasts in Current Activity Manager State:");
7445 }
7446 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll);
7447 if (needSep) {
7448 pw.println(" ");
7449 }
7450 if (dumpAll) {
7451 pw.println("-------------------------------------------------------------------------------");
7452 pw.println("Services in Current Activity Manager State:");
7453 }
7454 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll);
7455 if (needSep) {
7456 pw.println(" ");
7457 }
7458 if (dumpAll) {
7459 pw.println("-------------------------------------------------------------------------------");
7460 pw.println("PendingIntents in Current Activity Manager State:");
7461 }
7462 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll);
7463 if (needSep) {
7464 pw.println(" ");
7465 }
7466 if (dumpAll) {
7467 pw.println("-------------------------------------------------------------------------------");
7468 pw.println("Activities in Current Activity Manager State:");
7469 }
7470 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, !dumpAll);
7471 if (needSep) {
7472 pw.println(" ");
7473 }
7474 if (dumpAll) {
7475 pw.println("-------------------------------------------------------------------------------");
7476 pw.println("Processes in Current Activity Manager State:");
7477 }
7478 dumpProcessesLocked(fd, pw, args, opti, dumpAll);
7479 }
7480 }
7481
7482 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7483 int opti, boolean dumpAll, boolean needHeader) {
7484 if (needHeader) {
7485 pw.println(" Activity stack:");
7486 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007487 dumpHistoryList(pw, mMainStack.mHistory, " ", "Hist", true);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007488 pw.println(" ");
7489 pw.println(" Running activities (most recent first):");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007490 dumpHistoryList(pw, mMainStack.mLRUActivities, " ", "Run", false);
7491 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007492 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007493 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007494 dumpHistoryList(pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007495 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007496 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007497 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007498 pw.println(" Activities waiting to stop:");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007499 dumpHistoryList(pw, mMainStack.mStoppingActivities, " ", "Stop", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007500 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007501 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007502 pw.println(" ");
7503 pw.println(" Activities waiting to finish:");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007504 dumpHistoryList(pw, mMainStack.mFinishingActivities, " ", "Fin", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007507 pw.println(" ");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007508 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
7509 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007510 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007511 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007512
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007513 if (dumpAll && mRecentTasks.size() > 0) {
7514 pw.println(" ");
7515 pw.println("Recent tasks in Current Activity Manager State:");
7516
7517 final int N = mRecentTasks.size();
7518 for (int i=0; i<N; i++) {
7519 TaskRecord tr = mRecentTasks.get(i);
7520 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
7521 pw.println(tr);
7522 mRecentTasks.get(i).dump(pw, " ");
7523 }
7524 }
7525
7526 pw.println(" ");
7527 pw.println(" mCurTask: " + mCurTask);
7528
7529 return true;
7530 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07007531
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007532 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7533 int opti, boolean dumpAll) {
7534 boolean needSep = false;
7535 int numPers = 0;
7536
7537 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
7539 final int NA = procs.size();
7540 for (int ia=0; ia<NA; ia++) {
7541 if (!needSep) {
7542 pw.println(" All known processes:");
7543 needSep = true;
7544 }
7545 ProcessRecord r = procs.valueAt(ia);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007546 pw.print(r.persistent ? " *PERS*" : " *APP*");
7547 pw.print(" UID "); pw.print(procs.keyAt(ia));
7548 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007549 r.dump(pw, " ");
7550 if (r.persistent) {
7551 numPers++;
7552 }
7553 }
7554 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007555 }
7556
7557 if (mLruProcesses.size() > 0) {
7558 if (needSep) pw.println(" ");
7559 needSep = true;
7560 pw.println(" Running processes (most recent first):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07007561 dumpProcessOomList(pw, this, mLruProcesses, " ",
7562 "Proc", "PERS", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007563 needSep = true;
7564 }
7565
7566 synchronized (mPidsSelfLocked) {
7567 if (mPidsSelfLocked.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568 if (needSep) pw.println(" ");
7569 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007570 pw.println(" PID mappings:");
7571 for (int i=0; i<mPidsSelfLocked.size(); i++) {
7572 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
7573 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 }
7575 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007576 }
7577
7578 if (mForegroundProcesses.size() > 0) {
7579 if (needSep) pw.println(" ");
7580 needSep = true;
7581 pw.println(" Foreground Processes:");
7582 for (int i=0; i<mForegroundProcesses.size(); i++) {
7583 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
7584 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007586 }
7587
7588 if (mPersistentStartingProcesses.size() > 0) {
7589 if (needSep) pw.println(" ");
7590 needSep = true;
7591 pw.println(" Persisent processes that are starting:");
7592 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007593 "Starting Norm", "Restarting PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007595
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007596 if (mStartingProcesses.size() > 0) {
7597 if (needSep) pw.println(" ");
7598 needSep = true;
7599 pw.println(" Processes that are starting:");
7600 dumpProcessList(pw, this, mStartingProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007601 "Starting Norm", "Starting PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007604 if (mRemovedProcesses.size() > 0) {
7605 if (needSep) pw.println(" ");
7606 needSep = true;
7607 pw.println(" Processes that are being removed:");
7608 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007609 "Removed Norm", "Removed PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007610 }
7611
7612 if (mProcessesOnHold.size() > 0) {
7613 if (needSep) pw.println(" ");
7614 needSep = true;
7615 pw.println(" Processes that are on old until the system is ready:");
7616 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007617 "OnHold Norm", "OnHold PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007619
Dianne Hackborn287952c2010-09-22 22:34:31 -07007620 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007621
7622 if (mProcessCrashTimes.getMap().size() > 0) {
7623 if (needSep) pw.println(" ");
7624 needSep = true;
7625 pw.println(" Time since processes crashed:");
7626 long now = SystemClock.uptimeMillis();
7627 for (Map.Entry<String, SparseArray<Long>> procs
7628 : mProcessCrashTimes.getMap().entrySet()) {
7629 SparseArray<Long> uids = procs.getValue();
7630 final int N = uids.size();
7631 for (int i=0; i<N; i++) {
7632 pw.print(" Process "); pw.print(procs.getKey());
7633 pw.print(" uid "); pw.print(uids.keyAt(i));
7634 pw.print(": last crashed ");
7635 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07007636 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07007637 }
7638 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007640
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007641 if (mBadProcesses.getMap().size() > 0) {
7642 if (needSep) pw.println(" ");
7643 needSep = true;
7644 pw.println(" Bad processes:");
7645 for (Map.Entry<String, SparseArray<Long>> procs
7646 : mBadProcesses.getMap().entrySet()) {
7647 SparseArray<Long> uids = procs.getValue();
7648 final int N = uids.size();
7649 for (int i=0; i<N; i++) {
7650 pw.print(" Bad process "); pw.print(procs.getKey());
7651 pw.print(" uid "); pw.print(uids.keyAt(i));
7652 pw.print(": crashed at time ");
7653 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007654 }
7655 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007657
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007658 pw.println(" ");
7659 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackborn860755f2010-06-03 18:47:52 -07007660 if (mHeavyWeightProcess != null) {
7661 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7662 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007663 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007664 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007665 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
7666 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
7667 || mOrigWaitForDebugger) {
7668 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
7669 + " mDebugTransient=" + mDebugTransient
7670 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
7671 }
7672 if (mAlwaysFinishActivities || mController != null) {
7673 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
7674 + " mController=" + mController);
7675 }
7676 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07007679 + " mProcessesReady=" + mProcessesReady
7680 + " mSystemReady=" + mSystemReady);
7681 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 + " mBooted=" + mBooted
7683 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07007684 pw.print(" mLastPowerCheckRealtime=");
7685 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
7686 pw.println("");
7687 pw.print(" mLastPowerCheckUptime=");
7688 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
7689 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007690 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
7691 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07007692 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007693 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007694
7695 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007696 }
7697
Dianne Hackborn287952c2010-09-22 22:34:31 -07007698 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
7699 int opti, boolean needSep, boolean dumpAll) {
7700 if (mProcessesToGc.size() > 0) {
7701 if (needSep) pw.println(" ");
7702 needSep = true;
7703 pw.println(" Processes that are waiting to GC:");
7704 long now = SystemClock.uptimeMillis();
7705 for (int i=0; i<mProcessesToGc.size(); i++) {
7706 ProcessRecord proc = mProcessesToGc.get(i);
7707 pw.print(" Process "); pw.println(proc);
7708 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
7709 pw.print(", last gced=");
7710 pw.print(now-proc.lastRequestedGc);
7711 pw.print(" ms ago, last lowMem=");
7712 pw.print(now-proc.lastLowMemory);
7713 pw.println(" ms ago");
7714
7715 }
7716 }
7717 return needSep;
7718 }
7719
7720 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7721 int opti, boolean dumpAll) {
7722 boolean needSep = false;
7723
7724 if (mLruProcesses.size() > 0) {
7725 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(mLruProcesses);
7726
7727 Comparator<ProcessRecord> comparator = new Comparator<ProcessRecord>() {
7728 @Override
7729 public int compare(ProcessRecord object1, ProcessRecord object2) {
7730 if (object1.setAdj != object2.setAdj) {
7731 return object1.setAdj > object2.setAdj ? -1 : 1;
7732 }
7733 if (object1.setSchedGroup != object2.setSchedGroup) {
7734 return object1.setSchedGroup > object2.setSchedGroup ? -1 : 1;
7735 }
7736 if (object1.keeping != object2.keeping) {
7737 return object1.keeping ? -1 : 1;
7738 }
7739 if (object1.pid != object2.pid) {
7740 return object1.pid > object2.pid ? -1 : 1;
7741 }
7742 return 0;
7743 }
7744 };
7745
7746 Collections.sort(procs, comparator);
7747
7748 if (needSep) pw.println(" ");
7749 needSep = true;
7750 pw.println(" Process OOM control:");
7751 dumpProcessOomList(pw, this, procs, " ",
7752 "Proc", "PERS", true);
7753 needSep = true;
7754 }
7755
7756 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll);
7757
7758 pw.println(" ");
7759 pw.println(" mHomeProcess: " + mHomeProcess);
7760 if (mHeavyWeightProcess != null) {
7761 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7762 }
7763
7764 return true;
7765 }
7766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007767 /**
7768 * There are three ways to call this:
7769 * - no service specified: dump all the services
7770 * - a flattened component name that matched an existing service was specified as the
7771 * first arg: dump that one service
7772 * - the first arg isn't the flattened component name of an existing service:
7773 * dump all services whose component contains the first arg as a substring
7774 */
Joe Onoratoeb95b082010-10-21 14:54:19 -04007775 protected void dumpService(FileDescriptor fd, PrintWriter pw, String[] args, int opti) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 String[] newArgs;
7777 String componentNameString;
7778 ServiceRecord r;
Kenny Root3619b9ab2010-02-13 10:05:42 -08007779 if (opti >= args.length) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 componentNameString = null;
7781 newArgs = EMPTY_STRING_ARRAY;
7782 r = null;
7783 } else {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007784 componentNameString = args[opti];
7785 opti++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786 ComponentName componentName = ComponentName.unflattenFromString(componentNameString);
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007787 synchronized (this) {
7788 r = componentName != null ? mServices.get(componentName) : null;
7789 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007790 newArgs = new String[args.length - opti];
7791 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007792 }
7793
7794 if (r != null) {
Joe Onoratoeb95b082010-10-21 14:54:19 -04007795 dumpService(fd, pw, r, newArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007796 } else {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007797 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
7798 synchronized (this) {
7799 for (ServiceRecord r1 : mServices.values()) {
7800 if (componentNameString == null
7801 || r1.name.flattenToString().contains(componentNameString)) {
7802 services.add(r1);
7803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007804 }
7805 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007806 for (int i=0; i<services.size(); i++) {
Joe Onoratoeb95b082010-10-21 14:54:19 -04007807 dumpService(fd, pw, services.get(i), newArgs);
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 }
7810 }
7811
7812 /**
7813 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
7814 * there is a thread associated with the service.
7815 */
Joe Onoratoeb95b082010-10-21 14:54:19 -04007816 private void dumpService(FileDescriptor fd, PrintWriter pw, ServiceRecord r, String[] args) {
7817 pw.println("------------------------------------------------------------"
7818 + "-------------------");
7819 pw.println("APP SERVICE: " + r.name.flattenToString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007820 if (r.app != null && r.app.thread != null) {
7821 try {
7822 // flush anything that is already in the PrintWriter since the thread is going
7823 // to write to the file descriptor directly
7824 pw.flush();
7825 r.app.thread.dumpService(fd, r, args);
7826 pw.print("\n");
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007827 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 } catch (RemoteException e) {
7829 pw.println("got a RemoteException while dumping the service");
7830 }
7831 }
7832 }
7833
Dianne Hackborn625ac272010-09-17 18:29:22 -07007834 /**
7835 * There are three things that cmd can be:
7836 * - a flattened component name that matched an existing activity
7837 * - the cmd arg isn't the flattened component name of an existing activity:
7838 * dump all activity whose component contains the cmd as a substring
7839 * - A hex number of the ActivityRecord object instance.
7840 */
7841 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
7842 int opti, boolean dumpAll) {
7843 String[] newArgs;
7844 ComponentName componentName = ComponentName.unflattenFromString(name);
7845 int objectId = 0;
Dianne Hackborn30d71892010-12-11 10:37:55 -08007846 if (componentName == null) {
7847 // Not a '/' separated full component name; maybe an object ID?
7848 try {
7849 objectId = Integer.parseInt(name, 16);
7850 name = null;
7851 componentName = null;
7852 } catch (RuntimeException e) {
7853 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07007854 }
7855 newArgs = new String[args.length - opti];
7856 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
7857
7858 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
7859 synchronized (this) {
7860 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
7861 if (componentName != null) {
7862 if (r1.intent.getComponent().equals(componentName)) {
7863 activities.add(r1);
7864 }
7865 } else if (name != null) {
7866 if (r1.intent.getComponent().flattenToString().contains(name)) {
7867 activities.add(r1);
7868 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08007869 } else if (System.identityHashCode(r1) == objectId) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07007870 activities.add(r1);
7871 }
7872 }
7873 }
7874
7875 if (activities.size() <= 0) {
7876 return false;
7877 }
7878
Dianne Hackborn30d71892010-12-11 10:37:55 -08007879 TaskRecord lastTask = null;
7880 for (int i=activities.size()-1; i>=0; i--) {
7881 ActivityRecord r = (ActivityRecord)activities.get(i);
7882 if (lastTask != r.task) {
7883 lastTask = r.task;
7884 pw.print("* Task "); pw.print(lastTask.affinity);
7885 pw.print(" id="); pw.println(lastTask.taskId);
7886 if (dumpAll) {
7887 lastTask.dump(pw, " ");
7888 }
7889 }
7890 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07007891 }
7892 return true;
7893 }
7894
7895 /**
7896 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
7897 * there is a thread associated with the activity.
7898 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08007899 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
7900 ActivityRecord r, String[] args, boolean dumpAll) {
7901 synchronized (this) {
7902 pw.print(prefix); pw.print("* Activity ");
7903 pw.print(Integer.toHexString(System.identityHashCode(r)));
7904 pw.print(" "); pw.print(r.shortComponentName); pw.print(" pid=");
7905 if (r.app != null) pw.println(r.app.pid);
7906 else pw.println("(not running)");
7907 if (dumpAll) {
7908 r.dump(pw, prefix + " ");
Dianne Hackborn625ac272010-09-17 18:29:22 -07007909 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07007910 }
7911 if (r.app != null && r.app.thread != null) {
7912 try {
7913 // flush anything that is already in the PrintWriter since the thread is going
7914 // to write to the file descriptor directly
7915 pw.flush();
Dianne Hackborn30d71892010-12-11 10:37:55 -08007916 r.app.thread.dumpActivity(fd, r, prefix + " ", args);
Dianne Hackborn625ac272010-09-17 18:29:22 -07007917 pw.flush();
7918 } catch (RemoteException e) {
7919 pw.println("got a RemoteException while dumping the activity");
7920 }
7921 }
7922 }
7923
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007924 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7925 int opti, boolean dumpAll) {
7926 boolean needSep = false;
7927
7928 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007929 if (mRegisteredReceivers.size() > 0) {
7930 pw.println(" ");
7931 pw.println(" Registered Receivers:");
7932 Iterator it = mRegisteredReceivers.values().iterator();
7933 while (it.hasNext()) {
7934 ReceiverList r = (ReceiverList)it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007935 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 r.dump(pw, " ");
7937 }
7938 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007940 pw.println(" ");
7941 pw.println("Receiver Resolver Table:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007942 mReceiverResolver.dump(pw, null, " ", null, false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007943 needSep = true;
7944 }
7945
7946 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
7947 || mPendingBroadcast != null) {
7948 if (mParallelBroadcasts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007949 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007950 pw.println(" Active broadcasts:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007951 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007952 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
7953 pw.println(" Broadcast #" + i + ":");
7954 mParallelBroadcasts.get(i).dump(pw, " ");
7955 }
7956 if (mOrderedBroadcasts.size() > 0) {
7957 pw.println(" ");
Dianne Hackborn399cccb2010-04-13 22:57:49 -07007958 pw.println(" Active ordered broadcasts:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007959 }
7960 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
7961 pw.println(" Serialized Broadcast #" + i + ":");
7962 mOrderedBroadcasts.get(i).dump(pw, " ");
7963 }
7964 pw.println(" ");
7965 pw.println(" Pending broadcast:");
7966 if (mPendingBroadcast != null) {
7967 mPendingBroadcast.dump(pw, " ");
7968 } else {
7969 pw.println(" (null)");
7970 }
7971 needSep = true;
7972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007974 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007975 pw.println(" ");
Dianne Hackborn12527f92009-11-11 17:39:50 -08007976 pw.println(" Historical broadcasts:");
7977 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
7978 BroadcastRecord r = mBroadcastHistory[i];
7979 if (r == null) {
7980 break;
7981 }
7982 pw.println(" Historical Broadcast #" + i + ":");
7983 r.dump(pw, " ");
7984 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007985 needSep = true;
7986 }
7987
7988 if (mStickyBroadcasts != null) {
Dianne Hackborn12527f92009-11-11 17:39:50 -08007989 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007990 pw.println(" Sticky broadcasts:");
7991 StringBuilder sb = new StringBuilder(128);
7992 for (Map.Entry<String, ArrayList<Intent>> ent
7993 : mStickyBroadcasts.entrySet()) {
7994 pw.print(" * Sticky action "); pw.print(ent.getKey());
7995 pw.println(":");
7996 ArrayList<Intent> intents = ent.getValue();
7997 final int N = intents.size();
7998 for (int i=0; i<N; i++) {
7999 sb.setLength(0);
8000 sb.append(" Intent: ");
8001 intents.get(i).toShortString(sb, true, false);
8002 pw.println(sb.toString());
8003 Bundle bundle = intents.get(i).getExtras();
8004 if (bundle != null) {
8005 pw.print(" ");
8006 pw.println(bundle.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008007 }
8008 }
8009 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008010 needSep = true;
8011 }
8012
8013 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008015 pw.println(" mBroadcastsScheduled=" + mBroadcastsScheduled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008016 pw.println(" mHandler:");
8017 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008018 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008019 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008020
8021 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008022 }
8023
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008024 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8025 int opti, boolean dumpAll) {
8026 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008028 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008029 if (mServices.size() > 0) {
8030 pw.println(" Active services:");
8031 Iterator<ServiceRecord> it = mServices.values().iterator();
8032 while (it.hasNext()) {
8033 ServiceRecord r = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008034 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 r.dump(pw, " ");
8036 }
8037 needSep = true;
8038 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008041 if (mPendingServices.size() > 0) {
8042 if (needSep) pw.println(" ");
8043 pw.println(" Pending services:");
8044 for (int i=0; i<mPendingServices.size(); i++) {
8045 ServiceRecord r = mPendingServices.get(i);
8046 pw.print(" * Pending "); pw.println(r);
8047 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008048 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008049 needSep = true;
8050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008052 if (mRestartingServices.size() > 0) {
8053 if (needSep) pw.println(" ");
8054 pw.println(" Restarting services:");
8055 for (int i=0; i<mRestartingServices.size(); i++) {
8056 ServiceRecord r = mRestartingServices.get(i);
8057 pw.print(" * Restarting "); pw.println(r);
8058 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008059 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008060 needSep = true;
8061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008062
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008063 if (mStoppingServices.size() > 0) {
8064 if (needSep) pw.println(" ");
8065 pw.println(" Stopping services:");
8066 for (int i=0; i<mStoppingServices.size(); i++) {
8067 ServiceRecord r = mStoppingServices.get(i);
8068 pw.print(" * Stopping "); pw.println(r);
8069 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008071 needSep = true;
8072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008073
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008074 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 if (mServiceConnections.size() > 0) {
8076 if (needSep) pw.println(" ");
8077 pw.println(" Connection bindings to services:");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008078 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 = mServiceConnections.values().iterator();
8080 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008081 ArrayList<ConnectionRecord> r = it.next();
8082 for (int i=0; i<r.size(); i++) {
8083 pw.print(" * "); pw.println(r.get(i));
8084 r.get(i).dump(pw, " ");
8085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008086 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008087 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008088 }
8089 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008090
8091 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 }
8093
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008094 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8095 int opti, boolean dumpAll) {
8096 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008097
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008098 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 if (mProvidersByClass.size() > 0) {
8100 if (needSep) pw.println(" ");
8101 pw.println(" Published content providers (by class):");
Dianne Hackborn860755f2010-06-03 18:47:52 -07008102 Iterator<Map.Entry<String, ContentProviderRecord>> it
8103 = mProvidersByClass.entrySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008104 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008105 Map.Entry<String, ContentProviderRecord> e = it.next();
8106 ContentProviderRecord r = e.getValue();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008107 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 r.dump(pw, " ");
8109 }
8110 needSep = true;
8111 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008112
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008113 if (mProvidersByName.size() > 0) {
8114 pw.println(" ");
8115 pw.println(" Authority to provider mappings:");
Dianne Hackborn860755f2010-06-03 18:47:52 -07008116 Iterator<Map.Entry<String, ContentProviderRecord>> it
8117 = mProvidersByName.entrySet().iterator();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008118 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008119 Map.Entry<String, ContentProviderRecord> e = it.next();
8120 ContentProviderRecord r = e.getValue();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008121 pw.print(" "); pw.print(e.getKey()); pw.print(": ");
8122 pw.println(r);
8123 }
8124 needSep = true;
8125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008126 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008127
8128 if (mLaunchingProviders.size() > 0) {
8129 if (needSep) pw.println(" ");
8130 pw.println(" Launching content providers:");
8131 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
8132 pw.print(" Launching #"); pw.print(i); pw.print(": ");
8133 pw.println(mLaunchingProviders.get(i));
8134 }
8135 needSep = true;
8136 }
8137
8138 if (mGrantedUriPermissions.size() > 0) {
8139 pw.println();
8140 pw.println("Granted Uri Permissions:");
8141 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
8142 int uid = mGrantedUriPermissions.keyAt(i);
8143 HashMap<Uri, UriPermission> perms
8144 = mGrantedUriPermissions.valueAt(i);
8145 pw.print(" * UID "); pw.print(uid);
8146 pw.println(" holds:");
8147 for (UriPermission perm : perms.values()) {
8148 pw.print(" "); pw.println(perm);
8149 perm.dump(pw, " ");
8150 }
8151 }
8152 needSep = true;
8153 }
8154
8155 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008156 }
8157
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008158 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8159 int opti, boolean dumpAll) {
8160 boolean needSep = false;
8161
8162 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008163 if (this.mIntentSenderRecords.size() > 0) {
8164 Iterator<WeakReference<PendingIntentRecord>> it
8165 = mIntentSenderRecords.values().iterator();
8166 while (it.hasNext()) {
8167 WeakReference<PendingIntentRecord> ref = it.next();
8168 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008169 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 if (rec != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008171 pw.print(" * "); pw.println(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008172 rec.dump(pw, " ");
8173 } else {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008174 pw.print(" * "); pw.print(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 }
8176 }
8177 }
8178 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008179
8180 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008181 }
8182
8183 private static final void dumpHistoryList(PrintWriter pw, List list,
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008184 String prefix, String label, boolean complete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 TaskRecord lastTask = null;
8186 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008187 ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008188 final boolean full = complete || !r.inHistory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008189 if (lastTask != r.task) {
8190 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008191 pw.print(prefix);
8192 pw.print(full ? "* " : " ");
8193 pw.println(lastTask);
8194 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008195 lastTask.dump(pw, prefix + " ");
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008197 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008198 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
8199 pw.print(" #"); pw.print(i); pw.print(": ");
8200 pw.println(r);
8201 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008202 r.dump(pw, prefix + " ");
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008204 }
8205 }
8206
Dianne Hackborn09c916b2009-12-08 14:50:51 -08008207 private static String buildOomTag(String prefix, String space, int val, int base) {
8208 if (val == base) {
8209 if (space == null) return prefix;
8210 return prefix + " ";
8211 }
8212 return prefix + "+" + Integer.toString(val-base);
8213 }
8214
8215 private static final int dumpProcessList(PrintWriter pw,
8216 ActivityManagerService service, List list,
Dianne Hackborn287952c2010-09-22 22:34:31 -07008217 String prefix, String normalLabel, String persistentLabel) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008218 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07008219 final int N = list.size()-1;
8220 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008221 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008222 pw.println(String.format("%s%s #%2d: %s",
8223 prefix, (r.persistent ? persistentLabel : normalLabel),
8224 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 if (r.persistent) {
8226 numPers++;
8227 }
8228 }
8229 return numPers;
8230 }
8231
Dianne Hackborn287952c2010-09-22 22:34:31 -07008232 private static final void dumpProcessOomList(PrintWriter pw,
8233 ActivityManagerService service, List<ProcessRecord> list,
8234 String prefix, String normalLabel, String persistentLabel,
8235 boolean inclDetails) {
8236
8237 final long curRealtime = SystemClock.elapsedRealtime();
8238 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
8239 final long curUptime = SystemClock.uptimeMillis();
8240 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
8241
8242 final int N = list.size()-1;
8243 for (int i=N; i>=0; i--) {
8244 ProcessRecord r = list.get(i);
8245 String oomAdj;
8246 if (r.setAdj >= EMPTY_APP_ADJ) {
8247 oomAdj = buildOomTag("empty", null, r.setAdj, EMPTY_APP_ADJ);
8248 } else if (r.setAdj >= HIDDEN_APP_MIN_ADJ) {
8249 oomAdj = buildOomTag("bak", " ", r.setAdj, HIDDEN_APP_MIN_ADJ);
8250 } else if (r.setAdj >= HOME_APP_ADJ) {
8251 oomAdj = buildOomTag("home ", null, r.setAdj, HOME_APP_ADJ);
8252 } else if (r.setAdj >= SECONDARY_SERVER_ADJ) {
8253 oomAdj = buildOomTag("svc", " ", r.setAdj, SECONDARY_SERVER_ADJ);
8254 } else if (r.setAdj >= BACKUP_APP_ADJ) {
8255 oomAdj = buildOomTag("bckup", null, r.setAdj, BACKUP_APP_ADJ);
8256 } else if (r.setAdj >= HEAVY_WEIGHT_APP_ADJ) {
8257 oomAdj = buildOomTag("hvy ", null, r.setAdj, HEAVY_WEIGHT_APP_ADJ);
8258 } else if (r.setAdj >= PERCEPTIBLE_APP_ADJ) {
8259 oomAdj = buildOomTag("prcp ", null, r.setAdj, PERCEPTIBLE_APP_ADJ);
8260 } else if (r.setAdj >= VISIBLE_APP_ADJ) {
8261 oomAdj = buildOomTag("vis ", null, r.setAdj, VISIBLE_APP_ADJ);
8262 } else if (r.setAdj >= FOREGROUND_APP_ADJ) {
8263 oomAdj = buildOomTag("fore ", null, r.setAdj, FOREGROUND_APP_ADJ);
8264 } else if (r.setAdj >= CORE_SERVER_ADJ) {
8265 oomAdj = buildOomTag("core ", null, r.setAdj, CORE_SERVER_ADJ);
8266 } else if (r.setAdj >= SYSTEM_ADJ) {
8267 oomAdj = buildOomTag("sys ", null, r.setAdj, SYSTEM_ADJ);
8268 } else {
8269 oomAdj = Integer.toString(r.setAdj);
8270 }
8271 String schedGroup;
8272 switch (r.setSchedGroup) {
8273 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
8274 schedGroup = "B";
8275 break;
8276 case Process.THREAD_GROUP_DEFAULT:
8277 schedGroup = "F";
8278 break;
8279 default:
8280 schedGroup = Integer.toString(r.setSchedGroup);
8281 break;
8282 }
8283 pw.println(String.format("%s%s #%2d: adj=%s/%s %s (%s)",
8284 prefix, (r.persistent ? persistentLabel : normalLabel),
8285 N-i, oomAdj, schedGroup, r.toShortString(), r.adjType));
8286 if (r.adjSource != null || r.adjTarget != null) {
8287 pw.print(prefix);
8288 pw.print(" ");
8289 if (r.adjTarget instanceof ComponentName) {
8290 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
8291 } else if (r.adjTarget != null) {
8292 pw.print(r.adjTarget.toString());
8293 } else {
8294 pw.print("{null}");
8295 }
8296 pw.print("<=");
8297 if (r.adjSource instanceof ProcessRecord) {
8298 pw.print("Proc{");
8299 pw.print(((ProcessRecord)r.adjSource).toShortString());
8300 pw.println("}");
8301 } else if (r.adjSource != null) {
8302 pw.println(r.adjSource.toString());
8303 } else {
8304 pw.println("{null}");
8305 }
8306 }
8307 if (inclDetails) {
8308 pw.print(prefix);
8309 pw.print(" ");
8310 pw.print("oom: max="); pw.print(r.maxAdj);
8311 pw.print(" hidden="); pw.print(r.hiddenAdj);
8312 pw.print(" curRaw="); pw.print(r.curRawAdj);
8313 pw.print(" setRaw="); pw.print(r.setRawAdj);
8314 pw.print(" cur="); pw.print(r.curAdj);
8315 pw.print(" set="); pw.println(r.setAdj);
8316 pw.print(prefix);
8317 pw.print(" ");
8318 pw.print("keeping="); pw.print(r.keeping);
8319 pw.print(" hidden="); pw.print(r.hidden);
8320 pw.print(" empty="); pw.println(r.empty);
8321
8322 if (!r.keeping) {
8323 if (r.lastWakeTime != 0) {
8324 long wtime;
8325 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
8326 synchronized (stats) {
8327 wtime = stats.getProcessWakeTime(r.info.uid,
8328 r.pid, curRealtime);
8329 }
8330 long timeUsed = wtime - r.lastWakeTime;
8331 pw.print(prefix);
8332 pw.print(" ");
8333 pw.print("keep awake over ");
8334 TimeUtils.formatDuration(realtimeSince, pw);
8335 pw.print(" used ");
8336 TimeUtils.formatDuration(timeUsed, pw);
8337 pw.print(" (");
8338 pw.print((timeUsed*100)/realtimeSince);
8339 pw.println("%)");
8340 }
8341 if (r.lastCpuTime != 0) {
8342 long timeUsed = r.curCpuTime - r.lastCpuTime;
8343 pw.print(prefix);
8344 pw.print(" ");
8345 pw.print("run cpu over ");
8346 TimeUtils.formatDuration(uptimeSince, pw);
8347 pw.print(" used ");
8348 TimeUtils.formatDuration(timeUsed, pw);
8349 pw.print(" (");
8350 pw.print((timeUsed*100)/uptimeSince);
8351 pw.println("%)");
8352 }
8353 }
8354 }
8355 }
8356 }
8357
Dianne Hackborn472ad872010-04-07 17:31:48 -07008358 static final void dumpApplicationMemoryUsage(FileDescriptor fd,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008359 PrintWriter pw, List list, String prefix, String[] args) {
Dianne Hackborn6447ca32009-04-07 19:50:08 -07008360 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008361 long uptime = SystemClock.uptimeMillis();
8362 long realtime = SystemClock.elapsedRealtime();
8363
8364 if (isCheckinRequest) {
8365 // short checkin version
8366 pw.println(uptime + "," + realtime);
8367 pw.flush();
8368 } else {
8369 pw.println("Applications Memory Usage (kB):");
8370 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
8371 }
8372 for (int i = list.size() - 1 ; i >= 0 ; i--) {
8373 ProcessRecord r = (ProcessRecord)list.get(i);
8374 if (r.thread != null) {
8375 if (!isCheckinRequest) {
8376 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
8377 pw.flush();
8378 }
8379 try {
8380 r.thread.asBinder().dump(fd, args);
8381 } catch (RemoteException e) {
8382 if (!isCheckinRequest) {
8383 pw.println("Got RemoteException!");
8384 pw.flush();
8385 }
8386 }
8387 }
8388 }
8389 }
8390
8391 /**
8392 * Searches array of arguments for the specified string
8393 * @param args array of argument strings
8394 * @param value value to search for
8395 * @return true if the value is contained in the array
8396 */
8397 private static boolean scanArgs(String[] args, String value) {
8398 if (args != null) {
8399 for (String arg : args) {
8400 if (value.equals(arg)) {
8401 return true;
8402 }
8403 }
8404 }
8405 return false;
8406 }
8407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008408 private final void killServicesLocked(ProcessRecord app,
8409 boolean allowRestart) {
8410 // Report disconnected services.
8411 if (false) {
8412 // XXX we are letting the client link to the service for
8413 // death notifications.
8414 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008415 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008416 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008417 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008418 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008419 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008420 = r.connections.values().iterator();
8421 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008422 ArrayList<ConnectionRecord> cl = jt.next();
8423 for (int i=0; i<cl.size(); i++) {
8424 ConnectionRecord c = cl.get(i);
8425 if (c.binding.client != app) {
8426 try {
8427 //c.conn.connected(r.className, null);
8428 } catch (Exception e) {
8429 // todo: this should be asynchronous!
8430 Slog.w(TAG, "Exception thrown disconnected servce "
8431 + r.shortName
8432 + " from app " + app.processName, e);
8433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008434 }
8435 }
8436 }
8437 }
8438 }
8439 }
8440 }
8441
8442 // Clean up any connections this application has to other services.
8443 if (app.connections.size() > 0) {
8444 Iterator<ConnectionRecord> it = app.connections.iterator();
8445 while (it.hasNext()) {
8446 ConnectionRecord r = it.next();
8447 removeConnectionLocked(r, app, null);
8448 }
8449 }
8450 app.connections.clear();
8451
8452 if (app.services.size() != 0) {
8453 // Any services running in the application need to be placed
8454 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008455 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008456 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008457 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458 synchronized (sr.stats.getBatteryStats()) {
8459 sr.stats.stopLaunchedLocked();
8460 }
8461 sr.app = null;
8462 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008463 if (mStoppingServices.remove(sr)) {
8464 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
8465 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008466
8467 boolean hasClients = sr.bindings.size() > 0;
8468 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008469 Iterator<IntentBindRecord> bindings
8470 = sr.bindings.values().iterator();
8471 while (bindings.hasNext()) {
8472 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -08008473 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008474 + ": shouldUnbind=" + b.hasBound);
8475 b.binder = null;
8476 b.requested = b.received = b.hasBound = false;
8477 }
8478 }
8479
8480 if (sr.crashCount >= 2) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008481 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008482 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -08008483 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008484 sr.crashCount, sr.shortName, app.pid);
8485 bringDownServiceLocked(sr, true);
8486 } else if (!allowRestart) {
8487 bringDownServiceLocked(sr, true);
8488 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008489 boolean canceled = scheduleServiceRestartLocked(sr, true);
8490
8491 // Should the service remain running? Note that in the
8492 // extreme case of so many attempts to deliver a command
8493 // that it failed, that we also will stop it here.
8494 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
8495 if (sr.pendingStarts.size() == 0) {
8496 sr.startRequested = false;
8497 if (!hasClients) {
8498 // Whoops, no reason to restart!
8499 bringDownServiceLocked(sr, true);
8500 }
8501 }
8502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 }
8504 }
8505
8506 if (!allowRestart) {
8507 app.services.clear();
8508 }
8509 }
8510
Dianne Hackbornde42bb62009-08-05 12:26:15 -07008511 // Make sure we have no more records on the stopping list.
8512 int i = mStoppingServices.size();
8513 while (i > 0) {
8514 i--;
8515 ServiceRecord sr = mStoppingServices.get(i);
8516 if (sr.app == app) {
8517 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008518 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -07008519 }
8520 }
8521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008522 app.executingServices.clear();
8523 }
8524
8525 private final void removeDyingProviderLocked(ProcessRecord proc,
8526 ContentProviderRecord cpr) {
8527 synchronized (cpr) {
8528 cpr.launchingApp = null;
8529 cpr.notifyAll();
8530 }
8531
8532 mProvidersByClass.remove(cpr.info.name);
8533 String names[] = cpr.info.authority.split(";");
8534 for (int j = 0; j < names.length; j++) {
8535 mProvidersByName.remove(names[j]);
8536 }
8537
8538 Iterator<ProcessRecord> cit = cpr.clients.iterator();
8539 while (cit.hasNext()) {
8540 ProcessRecord capp = cit.next();
8541 if (!capp.persistent && capp.thread != null
8542 && capp.pid != 0
8543 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07008544 Slog.i(TAG, "Kill " + capp.processName
8545 + " (pid " + capp.pid + "): provider " + cpr.info.name
8546 + " in dying process " + proc.processName);
8547 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
8548 capp.processName, capp.setAdj, "dying provider " + proc.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008549 Process.killProcess(capp.pid);
8550 }
8551 }
8552
8553 mLaunchingProviders.remove(cpr);
8554 }
8555
8556 /**
8557 * Main code for cleaning up a process when it has gone away. This is
8558 * called both as a result of the process dying, or directly when stopping
8559 * a process when running in single process mode.
8560 */
8561 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
8562 boolean restarting, int index) {
8563 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008564 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008565 }
8566
Dianne Hackborn36124872009-10-08 16:22:03 -07008567 mProcessesToGc.remove(app);
8568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008569 // Dismiss any open dialogs.
8570 if (app.crashDialog != null) {
8571 app.crashDialog.dismiss();
8572 app.crashDialog = null;
8573 }
8574 if (app.anrDialog != null) {
8575 app.anrDialog.dismiss();
8576 app.anrDialog = null;
8577 }
8578 if (app.waitDialog != null) {
8579 app.waitDialog.dismiss();
8580 app.waitDialog = null;
8581 }
8582
8583 app.crashing = false;
8584 app.notResponding = false;
8585
8586 app.resetPackageList();
8587 app.thread = null;
8588 app.forcingToForeground = null;
8589 app.foregroundServices = false;
8590
8591 killServicesLocked(app, true);
8592
8593 boolean restart = false;
8594
8595 int NL = mLaunchingProviders.size();
8596
8597 // Remove published content providers.
8598 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008599 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008600 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008601 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008602 cpr.provider = null;
8603 cpr.app = null;
8604
8605 // See if someone is waiting for this provider... in which
8606 // case we don't remove it, but just let it restart.
8607 int i = 0;
8608 if (!app.bad) {
8609 for (; i<NL; i++) {
8610 if (mLaunchingProviders.get(i) == cpr) {
8611 restart = true;
8612 break;
8613 }
8614 }
8615 } else {
8616 i = NL;
8617 }
8618
8619 if (i >= NL) {
8620 removeDyingProviderLocked(app, cpr);
8621 NL = mLaunchingProviders.size();
8622 }
8623 }
8624 app.pubProviders.clear();
8625 }
8626
Dianne Hackbornf670ef72009-11-16 13:59:16 -08008627 // Take care of any launching providers waiting for this process.
8628 if (checkAppInLaunchingProvidersLocked(app, false)) {
8629 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008630 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08008631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008632 // Unregister from connected content providers.
8633 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07008634 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008635 while (it.hasNext()) {
8636 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
8637 cpr.clients.remove(app);
8638 }
8639 app.conProviders.clear();
8640 }
8641
Dianne Hackbornde42bb62009-08-05 12:26:15 -07008642 // At this point there may be remaining entries in mLaunchingProviders
8643 // where we were the only one waiting, so they are no longer of use.
8644 // Look for these and clean up if found.
8645 // XXX Commented out for now. Trying to figure out a way to reproduce
8646 // the actual situation to identify what is actually going on.
8647 if (false) {
8648 for (int i=0; i<NL; i++) {
8649 ContentProviderRecord cpr = (ContentProviderRecord)
8650 mLaunchingProviders.get(i);
8651 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
8652 synchronized (cpr) {
8653 cpr.launchingApp = null;
8654 cpr.notifyAll();
8655 }
8656 }
8657 }
8658 }
8659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008660 skipCurrentReceiverLocked(app);
8661
8662 // Unregister any receivers.
8663 if (app.receivers.size() > 0) {
8664 Iterator<ReceiverList> it = app.receivers.iterator();
8665 while (it.hasNext()) {
8666 removeReceiverLocked(it.next());
8667 }
8668 app.receivers.clear();
8669 }
8670
Christopher Tate181fafa2009-05-14 11:12:14 -07008671 // If the app is undergoing backup, tell the backup manager about it
8672 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008673 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -07008674 try {
8675 IBackupManager bm = IBackupManager.Stub.asInterface(
8676 ServiceManager.getService(Context.BACKUP_SERVICE));
8677 bm.agentDisconnected(app.info.packageName);
8678 } catch (RemoteException e) {
8679 // can't happen; backup manager is local
8680 }
8681 }
8682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008683 // If the caller is restarting this app, then leave it in its
8684 // current lists and let the caller take care of it.
8685 if (restarting) {
8686 return;
8687 }
8688
8689 if (!app.persistent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008690 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008691 "Removing non-persistent process during cleanup: " + app);
8692 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07008693 if (mHeavyWeightProcess == app) {
8694 mHeavyWeightProcess = null;
8695 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
8696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008697 } else if (!app.removed) {
8698 // This app is persistent, so we need to keep its record around.
8699 // If it is not already on the pending app list, add it there
8700 // and start a new process for it.
8701 app.thread = null;
8702 app.forcingToForeground = null;
8703 app.foregroundServices = false;
8704 if (mPersistentStartingProcesses.indexOf(app) < 0) {
8705 mPersistentStartingProcesses.add(app);
8706 restart = true;
8707 }
8708 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008709 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
8710 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 mProcessesOnHold.remove(app);
8712
The Android Open Source Project4df24232009-03-05 14:34:35 -08008713 if (app == mHomeProcess) {
8714 mHomeProcess = null;
8715 }
8716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008717 if (restart) {
8718 // We have components that still need to be running in the
8719 // process, so re-launch it.
8720 mProcessNames.put(app.processName, app.info.uid, app);
8721 startProcessLocked(app, "restart", app.processName);
8722 } else if (app.pid > 0 && app.pid != MY_PID) {
8723 // Goodbye!
8724 synchronized (mPidsSelfLocked) {
8725 mPidsSelfLocked.remove(app.pid);
8726 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
8727 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008728 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008729 }
8730 }
8731
Dianne Hackbornf670ef72009-11-16 13:59:16 -08008732 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
8733 // Look through the content providers we are waiting to have launched,
8734 // and if any run in this process then either schedule a restart of
8735 // the process or kill the client waiting for it if this process has
8736 // gone bad.
8737 int NL = mLaunchingProviders.size();
8738 boolean restart = false;
8739 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008740 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08008741 if (cpr.launchingApp == app) {
8742 if (!alwaysBad && !app.bad) {
8743 restart = true;
8744 } else {
8745 removeDyingProviderLocked(app, cpr);
8746 NL = mLaunchingProviders.size();
8747 }
8748 }
8749 }
8750 return restart;
8751 }
8752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008753 // =========================================================
8754 // SERVICES
8755 // =========================================================
8756
8757 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
8758 ActivityManager.RunningServiceInfo info =
8759 new ActivityManager.RunningServiceInfo();
8760 info.service = r.name;
8761 if (r.app != null) {
8762 info.pid = r.app.pid;
8763 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -07008764 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008765 info.process = r.processName;
8766 info.foreground = r.isForeground;
8767 info.activeSince = r.createTime;
8768 info.started = r.startRequested;
8769 info.clientCount = r.connections.size();
8770 info.crashCount = r.crashCount;
8771 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07008772 if (r.isForeground) {
8773 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
8774 }
8775 if (r.startRequested) {
8776 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
8777 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008778 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -07008779 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
8780 }
8781 if (r.app != null && r.app.persistent) {
8782 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
8783 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008784
8785 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
8786 for (int i=0; i<connl.size(); i++) {
8787 ConnectionRecord conn = connl.get(i);
8788 if (conn.clientLabel != 0) {
8789 info.clientPackage = conn.binding.client.info.packageName;
8790 info.clientLabel = conn.clientLabel;
8791 return info;
8792 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008793 }
8794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008795 return info;
8796 }
8797
8798 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
8799 int flags) {
8800 synchronized (this) {
8801 ArrayList<ActivityManager.RunningServiceInfo> res
8802 = new ArrayList<ActivityManager.RunningServiceInfo>();
8803
8804 if (mServices.size() > 0) {
8805 Iterator<ServiceRecord> it = mServices.values().iterator();
8806 while (it.hasNext() && res.size() < maxNum) {
8807 res.add(makeRunningServiceInfoLocked(it.next()));
8808 }
8809 }
8810
8811 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
8812 ServiceRecord r = mRestartingServices.get(i);
8813 ActivityManager.RunningServiceInfo info =
8814 makeRunningServiceInfoLocked(r);
8815 info.restarting = r.nextRestartTime;
8816 res.add(info);
8817 }
8818
8819 return res;
8820 }
8821 }
8822
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008823 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
8824 synchronized (this) {
8825 ServiceRecord r = mServices.get(name);
8826 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008827 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
8828 for (int i=0; i<conn.size(); i++) {
8829 if (conn.get(i).clientIntent != null) {
8830 return conn.get(i).clientIntent;
8831 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008832 }
8833 }
8834 }
8835 }
8836 return null;
8837 }
8838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008839 private final ServiceRecord findServiceLocked(ComponentName name,
8840 IBinder token) {
8841 ServiceRecord r = mServices.get(name);
8842 return r == token ? r : null;
8843 }
8844
8845 private final class ServiceLookupResult {
8846 final ServiceRecord record;
8847 final String permission;
8848
8849 ServiceLookupResult(ServiceRecord _record, String _permission) {
8850 record = _record;
8851 permission = _permission;
8852 }
8853 };
8854
8855 private ServiceLookupResult findServiceLocked(Intent service,
8856 String resolvedType) {
8857 ServiceRecord r = null;
8858 if (service.getComponent() != null) {
8859 r = mServices.get(service.getComponent());
8860 }
8861 if (r == null) {
8862 Intent.FilterComparison filter = new Intent.FilterComparison(service);
8863 r = mServicesByIntent.get(filter);
8864 }
8865
8866 if (r == null) {
8867 try {
8868 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008869 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008870 service, resolvedType, 0);
8871 ServiceInfo sInfo =
8872 rInfo != null ? rInfo.serviceInfo : null;
8873 if (sInfo == null) {
8874 return null;
8875 }
8876
8877 ComponentName name = new ComponentName(
8878 sInfo.applicationInfo.packageName, sInfo.name);
8879 r = mServices.get(name);
8880 } catch (RemoteException ex) {
8881 // pm is in same process, this will never happen.
8882 }
8883 }
8884 if (r != null) {
8885 int callingPid = Binder.getCallingPid();
8886 int callingUid = Binder.getCallingUid();
8887 if (checkComponentPermission(r.permission,
8888 callingPid, callingUid, r.exported ? -1 : r.appInfo.uid)
8889 != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008890 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008891 + " from pid=" + callingPid
8892 + ", uid=" + callingUid
8893 + " requires " + r.permission);
8894 return new ServiceLookupResult(null, r.permission);
8895 }
8896 return new ServiceLookupResult(r, null);
8897 }
8898 return null;
8899 }
8900
8901 private class ServiceRestarter implements Runnable {
8902 private ServiceRecord mService;
8903
8904 void setService(ServiceRecord service) {
8905 mService = service;
8906 }
8907
8908 public void run() {
8909 synchronized(ActivityManagerService.this) {
8910 performServiceRestartLocked(mService);
8911 }
8912 }
8913 }
8914
8915 private ServiceLookupResult retrieveServiceLocked(Intent service,
8916 String resolvedType, int callingPid, int callingUid) {
8917 ServiceRecord r = null;
8918 if (service.getComponent() != null) {
8919 r = mServices.get(service.getComponent());
8920 }
8921 Intent.FilterComparison filter = new Intent.FilterComparison(service);
8922 r = mServicesByIntent.get(filter);
8923 if (r == null) {
8924 try {
8925 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008926 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -07008927 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 ServiceInfo sInfo =
8929 rInfo != null ? rInfo.serviceInfo : null;
8930 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008931 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 ": not found");
8933 return null;
8934 }
8935
8936 ComponentName name = new ComponentName(
8937 sInfo.applicationInfo.packageName, sInfo.name);
8938 r = mServices.get(name);
8939 if (r == null) {
8940 filter = new Intent.FilterComparison(service.cloneFilter());
8941 ServiceRestarter res = new ServiceRestarter();
8942 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
8943 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
8944 synchronized (stats) {
8945 ss = stats.getServiceStatsLocked(
8946 sInfo.applicationInfo.uid, sInfo.packageName,
8947 sInfo.name);
8948 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -08008949 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008950 res.setService(r);
8951 mServices.put(name, r);
8952 mServicesByIntent.put(filter, r);
8953
8954 // Make sure this component isn't in the pending list.
8955 int N = mPendingServices.size();
8956 for (int i=0; i<N; i++) {
8957 ServiceRecord pr = mPendingServices.get(i);
8958 if (pr.name.equals(name)) {
8959 mPendingServices.remove(i);
8960 i--;
8961 N--;
8962 }
8963 }
8964 }
8965 } catch (RemoteException ex) {
8966 // pm is in same process, this will never happen.
8967 }
8968 }
8969 if (r != null) {
8970 if (checkComponentPermission(r.permission,
8971 callingPid, callingUid, r.exported ? -1 : r.appInfo.uid)
8972 != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008973 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008974 + " from pid=" + Binder.getCallingPid()
8975 + ", uid=" + Binder.getCallingUid()
8976 + " requires " + r.permission);
8977 return new ServiceLookupResult(null, r.permission);
8978 }
8979 return new ServiceLookupResult(r, null);
8980 }
8981 return null;
8982 }
8983
Dianne Hackborn287952c2010-09-22 22:34:31 -07008984 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
8985 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
8986 + why + " of " + r + " in app " + r.app);
8987 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
8988 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989 long now = SystemClock.uptimeMillis();
8990 if (r.executeNesting == 0 && r.app != null) {
8991 if (r.app.executingServices.size() == 0) {
8992 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
8993 msg.obj = r.app;
8994 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
8995 }
8996 r.app.executingServices.add(r);
8997 }
8998 r.executeNesting++;
8999 r.executingStart = now;
9000 }
9001
9002 private final void sendServiceArgsLocked(ServiceRecord r,
9003 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009004 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009005 if (N == 0) {
9006 return;
9007 }
9008
Dianne Hackborn39792d22010-08-19 18:01:52 -07009009 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009010 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -07009011 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009012 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
9013 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn39792d22010-08-19 18:01:52 -07009014 if (si.intent == null) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009015 // If somehow we got a dummy start at the front, then
9016 // just drop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009017 continue;
9018 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07009019 si.deliveredTime = SystemClock.uptimeMillis();
9020 r.deliveredStarts.add(si);
9021 si.deliveryCount++;
9022 if (si.targetPermissionUid >= 0) {
9023 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -07009024 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07009025 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009026 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 if (!oomAdjusted) {
9028 oomAdjusted = true;
9029 updateOomAdjLocked(r.app);
9030 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009031 int flags = 0;
9032 if (si.deliveryCount > 0) {
9033 flags |= Service.START_FLAG_RETRY;
9034 }
9035 if (si.doneExecutingCount > 0) {
9036 flags |= Service.START_FLAG_REDELIVERY;
9037 }
9038 r.app.thread.scheduleServiceArgs(r, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009039 } catch (RemoteException e) {
9040 // Remote process gone... we'll let the normal cleanup take
9041 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009042 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009043 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009044 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009045 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009046 break;
9047 }
9048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009049 }
9050
9051 private final boolean requestServiceBindingLocked(ServiceRecord r,
9052 IntentBindRecord i, boolean rebind) {
9053 if (r.app == null || r.app.thread == null) {
9054 // If service is not currently running, can't yet bind.
9055 return false;
9056 }
9057 if ((!i.requested || rebind) && i.apps.size() > 0) {
9058 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009059 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009060 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
9061 if (!rebind) {
9062 i.requested = true;
9063 }
9064 i.hasBound = true;
9065 i.doRebind = false;
9066 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009067 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009068 return false;
9069 }
9070 }
9071 return true;
9072 }
9073
9074 private final void requestServiceBindingsLocked(ServiceRecord r) {
9075 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
9076 while (bindings.hasNext()) {
9077 IntentBindRecord i = bindings.next();
9078 if (!requestServiceBindingLocked(r, i, false)) {
9079 break;
9080 }
9081 }
9082 }
9083
9084 private final void realStartServiceLocked(ServiceRecord r,
9085 ProcessRecord app) throws RemoteException {
9086 if (app.thread == null) {
9087 throw new RemoteException();
9088 }
9089
9090 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -07009091 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092
9093 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009094 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009095 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096
9097 boolean created = false;
9098 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07009099 mStringBuilder.setLength(0);
9100 r.intent.getIntent().toShortString(mStringBuilder, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -08009101 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009102 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -07009103 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009104 synchronized (r.stats.getBatteryStats()) {
9105 r.stats.startLaunchedLocked();
9106 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07009107 ensurePackageDexOpt(r.serviceInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108 app.thread.scheduleCreateService(r, r.serviceInfo);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009109 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009110 created = true;
9111 } finally {
9112 if (!created) {
9113 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009114 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009115 }
9116 }
9117
9118 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009119
9120 // If the service is in the started state, and there are no
9121 // pending arguments, then fake up one so its onStartCommand() will
9122 // be called.
9123 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
9124 r.lastStartId++;
9125 if (r.lastStartId < 1) {
9126 r.lastStartId = 1;
9127 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07009128 r.pendingStarts.add(new ServiceRecord.StartItem(r, r.lastStartId, null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009129 }
9130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009131 sendServiceArgsLocked(r, true);
9132 }
9133
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009134 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
9135 boolean allowCancel) {
9136 boolean canceled = false;
9137
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009138 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009139 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -07009140 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009141
9142 // Any delivered but not yet finished starts should be put back
9143 // on the pending list.
9144 final int N = r.deliveredStarts.size();
9145 if (N > 0) {
9146 for (int i=N-1; i>=0; i--) {
9147 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -07009148 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009149 if (si.intent == null) {
9150 // We'll generate this again if needed.
9151 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
9152 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
9153 r.pendingStarts.add(0, si);
9154 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
9155 dur *= 2;
9156 if (minDuration < dur) minDuration = dur;
9157 if (resetTime < dur) resetTime = dur;
9158 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009159 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009160 + r.name);
9161 canceled = true;
9162 }
9163 }
9164 r.deliveredStarts.clear();
9165 }
9166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009167 r.totalRestartCount++;
9168 if (r.restartDelay == 0) {
9169 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009170 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009171 } else {
9172 // If it has been a "reasonably long time" since the service
9173 // was started, then reset our restart duration back to
9174 // the beginning, so we don't infinitely increase the duration
9175 // on a service that just occasionally gets killed (which is
9176 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009177 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009178 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009179 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009180 } else {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009181 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009182 if (r.restartDelay < minDuration) {
9183 r.restartDelay = minDuration;
9184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009185 }
9186 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009187
9188 r.nextRestartTime = now + r.restartDelay;
9189
9190 // Make sure that we don't end up restarting a bunch of services
9191 // all at the same time.
9192 boolean repeat;
9193 do {
9194 repeat = false;
9195 for (int i=mRestartingServices.size()-1; i>=0; i--) {
9196 ServiceRecord r2 = mRestartingServices.get(i);
9197 if (r2 != r && r.nextRestartTime
9198 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
9199 && r.nextRestartTime
9200 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
9201 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
9202 r.restartDelay = r.nextRestartTime - now;
9203 repeat = true;
9204 break;
9205 }
9206 }
9207 } while (repeat);
9208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009209 if (!mRestartingServices.contains(r)) {
9210 mRestartingServices.add(r);
9211 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009212
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009213 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009215 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009216 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009217 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -08009218 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009219 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -08009220 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009221 r.shortName, r.restartDelay);
9222
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009223 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009224 }
9225
9226 final void performServiceRestartLocked(ServiceRecord r) {
9227 if (!mRestartingServices.contains(r)) {
9228 return;
9229 }
9230 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
9231 }
9232
9233 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
9234 if (r.restartDelay == 0) {
9235 return false;
9236 }
9237 r.resetRestartCounter();
9238 mRestartingServices.remove(r);
9239 mHandler.removeCallbacks(r.restarter);
9240 return true;
9241 }
9242
9243 private final boolean bringUpServiceLocked(ServiceRecord r,
9244 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009245 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009246 //r.dump(" ");
9247
Dianne Hackborn36124872009-10-08 16:22:03 -07009248 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009249 sendServiceArgsLocked(r, false);
9250 return true;
9251 }
9252
9253 if (!whileRestarting && r.restartDelay > 0) {
9254 // If waiting for a restart, then do nothing.
9255 return true;
9256 }
9257
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009258 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009259
Dianne Hackbornde42bb62009-08-05 12:26:15 -07009260 // We are now bringing the service up, so no longer in the
9261 // restarting state.
9262 mRestartingServices.remove(r);
9263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009264 final String appName = r.processName;
9265 ProcessRecord app = getProcessRecordLocked(appName, r.appInfo.uid);
9266 if (app != null && app.thread != null) {
9267 try {
9268 realStartServiceLocked(r, app);
9269 return true;
9270 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009271 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009272 }
9273
9274 // If a dead object exception was thrown -- fall through to
9275 // restart the application.
9276 }
9277
Dianne Hackborn36124872009-10-08 16:22:03 -07009278 // Not running -- get it started, and enqueue this service record
9279 // to be executed when the app comes up.
9280 if (startProcessLocked(appName, r.appInfo, true, intentFlags,
9281 "service", r.name, false) == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009282 Slog.w(TAG, "Unable to launch app "
Dianne Hackborn36124872009-10-08 16:22:03 -07009283 + r.appInfo.packageName + "/"
9284 + r.appInfo.uid + " for service "
9285 + r.intent.getIntent() + ": process is bad");
9286 bringDownServiceLocked(r, true);
9287 return false;
9288 }
9289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009290 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009291 mPendingServices.add(r);
9292 }
Dianne Hackborn36124872009-10-08 16:22:03 -07009293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009294 return true;
9295 }
9296
9297 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009298 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009299 //r.dump(" ");
9300
9301 // Does it still need to run?
9302 if (!force && r.startRequested) {
9303 return;
9304 }
9305 if (r.connections.size() > 0) {
9306 if (!force) {
9307 // XXX should probably keep a count of the number of auto-create
9308 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009309 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009310 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009311 ArrayList<ConnectionRecord> cr = it.next();
9312 for (int i=0; i<cr.size(); i++) {
9313 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
9314 return;
9315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009316 }
9317 }
9318 }
9319
9320 // Report to all of the connections that the service is no longer
9321 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009322 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009323 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009324 ArrayList<ConnectionRecord> c = it.next();
9325 for (int i=0; i<c.size(); i++) {
9326 try {
9327 c.get(i).conn.connected(r.name, null);
9328 } catch (Exception e) {
9329 Slog.w(TAG, "Failure disconnecting service " + r.name +
9330 " to connection " + c.get(i).conn.asBinder() +
9331 " (in " + c.get(i).binding.client.processName + ")", e);
9332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009333 }
9334 }
9335 }
9336
9337 // Tell the service that it has been unbound.
9338 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
9339 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
9340 while (it.hasNext()) {
9341 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -08009342 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009343 + ": hasBound=" + ibr.hasBound);
9344 if (r.app != null && r.app.thread != null && ibr.hasBound) {
9345 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009346 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009347 updateOomAdjLocked(r.app);
9348 ibr.hasBound = false;
9349 r.app.thread.scheduleUnbindService(r,
9350 ibr.intent.getIntent());
9351 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009352 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353 + r.shortName, e);
9354 serviceDoneExecutingLocked(r, true);
9355 }
9356 }
9357 }
9358 }
9359
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009360 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -08009361 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009362 System.identityHashCode(r), r.shortName,
9363 (r.app != null) ? r.app.pid : -1);
9364
9365 mServices.remove(r.name);
9366 mServicesByIntent.remove(r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009367 r.totalRestartCount = 0;
9368 unscheduleServiceRestartLocked(r);
9369
9370 // Also make sure it is not on the pending list.
9371 int N = mPendingServices.size();
9372 for (int i=0; i<N; i++) {
9373 if (mPendingServices.get(i) == r) {
9374 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009375 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009376 i--;
9377 N--;
9378 }
9379 }
9380
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009381 r.cancelNotification();
9382 r.isForeground = false;
9383 r.foregroundId = 0;
9384 r.foregroundNoti = null;
9385
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009386 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -07009387 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009388 r.pendingStarts.clear();
9389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009390 if (r.app != null) {
9391 synchronized (r.stats.getBatteryStats()) {
9392 r.stats.stopLaunchedLocked();
9393 }
9394 r.app.services.remove(r);
9395 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009396 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009397 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009398 mStoppingServices.add(r);
9399 updateOomAdjLocked(r.app);
9400 r.app.thread.scheduleStopService(r);
9401 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009402 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009403 + r.shortName, e);
9404 serviceDoneExecutingLocked(r, true);
9405 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009406 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009407 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009408 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009409 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009410 }
9411 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009412 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009413 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009414 }
9415 }
9416
9417 ComponentName startServiceLocked(IApplicationThread caller,
9418 Intent service, String resolvedType,
9419 int callingPid, int callingUid) {
9420 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009421 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009422 + " type=" + resolvedType + " args=" + service.getExtras());
9423
9424 if (caller != null) {
9425 final ProcessRecord callerApp = getRecordForAppLocked(caller);
9426 if (callerApp == null) {
9427 throw new SecurityException(
9428 "Unable to find app for caller " + caller
9429 + " (pid=" + Binder.getCallingPid()
9430 + ") when starting service " + service);
9431 }
9432 }
9433
9434 ServiceLookupResult res =
9435 retrieveServiceLocked(service, resolvedType,
9436 callingPid, callingUid);
9437 if (res == null) {
9438 return null;
9439 }
9440 if (res.record == null) {
9441 return new ComponentName("!", res.permission != null
9442 ? res.permission : "private to package");
9443 }
9444 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -07009445 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
9446 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009447 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009448 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009449 }
9450 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009451 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009452 r.lastStartId++;
9453 if (r.lastStartId < 1) {
9454 r.lastStartId = 1;
9455 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07009456 r.pendingStarts.add(new ServiceRecord.StartItem(r, r.lastStartId,
9457 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009458 r.lastActivity = SystemClock.uptimeMillis();
9459 synchronized (r.stats.getBatteryStats()) {
9460 r.stats.startRunningLocked();
9461 }
9462 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
9463 return new ComponentName("!", "Service process is bad");
9464 }
9465 return r.name;
9466 }
9467 }
9468
9469 public ComponentName startService(IApplicationThread caller, Intent service,
9470 String resolvedType) {
9471 // Refuse possible leaked file descriptors
9472 if (service != null && service.hasFileDescriptors() == true) {
9473 throw new IllegalArgumentException("File descriptors passed in Intent");
9474 }
9475
9476 synchronized(this) {
9477 final int callingPid = Binder.getCallingPid();
9478 final int callingUid = Binder.getCallingUid();
9479 final long origId = Binder.clearCallingIdentity();
9480 ComponentName res = startServiceLocked(caller, service,
9481 resolvedType, callingPid, callingUid);
9482 Binder.restoreCallingIdentity(origId);
9483 return res;
9484 }
9485 }
9486
9487 ComponentName startServiceInPackage(int uid,
9488 Intent service, String resolvedType) {
9489 synchronized(this) {
9490 final long origId = Binder.clearCallingIdentity();
9491 ComponentName res = startServiceLocked(null, service,
9492 resolvedType, -1, uid);
9493 Binder.restoreCallingIdentity(origId);
9494 return res;
9495 }
9496 }
9497
9498 public int stopService(IApplicationThread caller, Intent service,
9499 String resolvedType) {
9500 // Refuse possible leaked file descriptors
9501 if (service != null && service.hasFileDescriptors() == true) {
9502 throw new IllegalArgumentException("File descriptors passed in Intent");
9503 }
9504
9505 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009506 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009507 + " type=" + resolvedType);
9508
9509 final ProcessRecord callerApp = getRecordForAppLocked(caller);
9510 if (caller != null && callerApp == null) {
9511 throw new SecurityException(
9512 "Unable to find app for caller " + caller
9513 + " (pid=" + Binder.getCallingPid()
9514 + ") when stopping service " + service);
9515 }
9516
9517 // If this service is active, make sure it is stopped.
9518 ServiceLookupResult r = findServiceLocked(service, resolvedType);
9519 if (r != null) {
9520 if (r.record != null) {
9521 synchronized (r.record.stats.getBatteryStats()) {
9522 r.record.stats.stopRunningLocked();
9523 }
9524 r.record.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009525 r.record.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009526 final long origId = Binder.clearCallingIdentity();
9527 bringDownServiceLocked(r.record, false);
9528 Binder.restoreCallingIdentity(origId);
9529 return 1;
9530 }
9531 return -1;
9532 }
9533 }
9534
9535 return 0;
9536 }
9537
9538 public IBinder peekService(Intent service, String resolvedType) {
9539 // Refuse possible leaked file descriptors
9540 if (service != null && service.hasFileDescriptors() == true) {
9541 throw new IllegalArgumentException("File descriptors passed in Intent");
9542 }
9543
9544 IBinder ret = null;
9545
9546 synchronized(this) {
9547 ServiceLookupResult r = findServiceLocked(service, resolvedType);
9548
9549 if (r != null) {
9550 // r.record is null if findServiceLocked() failed the caller permission check
9551 if (r.record == null) {
9552 throw new SecurityException(
9553 "Permission Denial: Accessing service " + r.record.name
9554 + " from pid=" + Binder.getCallingPid()
9555 + ", uid=" + Binder.getCallingUid()
9556 + " requires " + r.permission);
9557 }
9558 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
9559 if (ib != null) {
9560 ret = ib.binder;
9561 }
9562 }
9563 }
9564
9565 return ret;
9566 }
9567
9568 public boolean stopServiceToken(ComponentName className, IBinder token,
9569 int startId) {
9570 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009571 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009572 + " " + token + " startId=" + startId);
9573 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009574 if (r != null) {
9575 if (startId >= 0) {
9576 // Asked to only stop if done with all work. Note that
9577 // to avoid leaks, we will take this as dropping all
9578 // start items up to and including this one.
9579 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
9580 if (si != null) {
9581 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07009582 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
9583 cur.removeUriPermissionsLocked();
9584 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009585 break;
9586 }
9587 }
9588 }
9589
9590 if (r.lastStartId != startId) {
9591 return false;
9592 }
9593
9594 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009595 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009596 + " is last, but have " + r.deliveredStarts.size()
9597 + " remaining args");
9598 }
9599 }
9600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009601 synchronized (r.stats.getBatteryStats()) {
9602 r.stats.stopRunningLocked();
9603 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009604 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009605 }
9606 final long origId = Binder.clearCallingIdentity();
9607 bringDownServiceLocked(r, false);
9608 Binder.restoreCallingIdentity(origId);
9609 return true;
9610 }
9611 }
9612 return false;
9613 }
9614
9615 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009616 int id, Notification notification, boolean removeNotification) {
9617 final long origId = Binder.clearCallingIdentity();
9618 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009619 synchronized(this) {
9620 ServiceRecord r = findServiceLocked(className, token);
9621 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009622 if (id != 0) {
9623 if (notification == null) {
9624 throw new IllegalArgumentException("null notification");
9625 }
9626 if (r.foregroundId != id) {
9627 r.cancelNotification();
9628 r.foregroundId = id;
9629 }
9630 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
9631 r.foregroundNoti = notification;
9632 r.isForeground = true;
9633 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009634 if (r.app != null) {
9635 updateServiceForegroundLocked(r.app, true);
9636 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009637 } else {
9638 if (r.isForeground) {
9639 r.isForeground = false;
9640 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07009641 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009642 updateServiceForegroundLocked(r.app, true);
9643 }
9644 }
9645 if (removeNotification) {
9646 r.cancelNotification();
9647 r.foregroundId = 0;
9648 r.foregroundNoti = null;
9649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009650 }
9651 }
9652 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009653 } finally {
9654 Binder.restoreCallingIdentity(origId);
9655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009656 }
9657
9658 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
9659 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -07009660 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009661 if (sr.isForeground) {
9662 anyForeground = true;
9663 break;
9664 }
9665 }
9666 if (anyForeground != proc.foregroundServices) {
9667 proc.foregroundServices = anyForeground;
9668 if (oomAdj) {
9669 updateOomAdjLocked();
9670 }
9671 }
9672 }
9673
9674 public int bindService(IApplicationThread caller, IBinder token,
9675 Intent service, String resolvedType,
9676 IServiceConnection connection, int flags) {
9677 // Refuse possible leaked file descriptors
9678 if (service != null && service.hasFileDescriptors() == true) {
9679 throw new IllegalArgumentException("File descriptors passed in Intent");
9680 }
9681
9682 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009683 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009684 + " type=" + resolvedType + " conn=" + connection.asBinder()
9685 + " flags=0x" + Integer.toHexString(flags));
9686 final ProcessRecord callerApp = getRecordForAppLocked(caller);
9687 if (callerApp == null) {
9688 throw new SecurityException(
9689 "Unable to find app for caller " + caller
9690 + " (pid=" + Binder.getCallingPid()
9691 + ") when binding service " + service);
9692 }
9693
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009694 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009695 if (token != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009696 int aindex = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009697 if (aindex < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009698 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009699 return 0;
9700 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009701 activity = (ActivityRecord)mMainStack.mHistory.get(aindex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009702 }
9703
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009704 int clientLabel = 0;
9705 PendingIntent clientIntent = null;
9706
9707 if (callerApp.info.uid == Process.SYSTEM_UID) {
9708 // Hacky kind of thing -- allow system stuff to tell us
9709 // what they are, so we can report this elsewhere for
9710 // others to know why certain services are running.
9711 try {
9712 clientIntent = (PendingIntent)service.getParcelableExtra(
9713 Intent.EXTRA_CLIENT_INTENT);
9714 } catch (RuntimeException e) {
9715 }
9716 if (clientIntent != null) {
9717 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
9718 if (clientLabel != 0) {
9719 // There are no useful extras in the intent, trash them.
9720 // System code calling with this stuff just needs to know
9721 // this will happen.
9722 service = service.cloneFilter();
9723 }
9724 }
9725 }
9726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009727 ServiceLookupResult res =
9728 retrieveServiceLocked(service, resolvedType,
9729 Binder.getCallingPid(), Binder.getCallingUid());
9730 if (res == null) {
9731 return 0;
9732 }
9733 if (res.record == null) {
9734 return -1;
9735 }
9736 ServiceRecord s = res.record;
9737
9738 final long origId = Binder.clearCallingIdentity();
9739
9740 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009741 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009742 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009743 }
9744
9745 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
9746 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009747 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009748
9749 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009750 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
9751 if (clist == null) {
9752 clist = new ArrayList<ConnectionRecord>();
9753 s.connections.put(binder, clist);
9754 }
9755 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009756 b.connections.add(c);
9757 if (activity != null) {
9758 if (activity.connections == null) {
9759 activity.connections = new HashSet<ConnectionRecord>();
9760 }
9761 activity.connections.add(c);
9762 }
9763 b.client.connections.add(c);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009764 clist = mServiceConnections.get(binder);
9765 if (clist == null) {
9766 clist = new ArrayList<ConnectionRecord>();
9767 mServiceConnections.put(binder, clist);
9768 }
9769 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009770
9771 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
9772 s.lastActivity = SystemClock.uptimeMillis();
9773 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
9774 return 0;
9775 }
9776 }
9777
9778 if (s.app != null) {
9779 // This could have made the service more important.
9780 updateOomAdjLocked(s.app);
9781 }
9782
Joe Onorato8a9b2202010-02-26 18:56:32 -08009783 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009784 + ": received=" + b.intent.received
9785 + " apps=" + b.intent.apps.size()
9786 + " doRebind=" + b.intent.doRebind);
9787
9788 if (s.app != null && b.intent.received) {
9789 // Service is already running, so we can immediately
9790 // publish the connection.
9791 try {
9792 c.conn.connected(s.name, b.intent.binder);
9793 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009794 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009795 + " to connection " + c.conn.asBinder()
9796 + " (in " + c.binding.client.processName + ")", e);
9797 }
9798
9799 // If this is the first app connected back to this binding,
9800 // and the service had previously asked to be told when
9801 // rebound, then do so.
9802 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
9803 requestServiceBindingLocked(s, b.intent, true);
9804 }
9805 } else if (!b.intent.requested) {
9806 requestServiceBindingLocked(s, b.intent, false);
9807 }
9808
9809 Binder.restoreCallingIdentity(origId);
9810 }
9811
9812 return 1;
9813 }
9814
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009815 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009816 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009817 IBinder binder = c.conn.asBinder();
9818 AppBindRecord b = c.binding;
9819 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009820 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
9821 if (clist != null) {
9822 clist.remove(c);
9823 if (clist.size() == 0) {
9824 s.connections.remove(binder);
9825 }
9826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009827 b.connections.remove(c);
9828 if (c.activity != null && c.activity != skipAct) {
9829 if (c.activity.connections != null) {
9830 c.activity.connections.remove(c);
9831 }
9832 }
9833 if (b.client != skipApp) {
9834 b.client.connections.remove(c);
9835 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009836 clist = mServiceConnections.get(binder);
9837 if (clist != null) {
9838 clist.remove(c);
9839 if (clist.size() == 0) {
9840 mServiceConnections.remove(binder);
9841 }
9842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009843
9844 if (b.connections.size() == 0) {
9845 b.intent.apps.remove(b.client);
9846 }
9847
Joe Onorato8a9b2202010-02-26 18:56:32 -08009848 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009849 + ": shouldUnbind=" + b.intent.hasBound);
9850 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
9851 && b.intent.hasBound) {
9852 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009853 bumpServiceExecutingLocked(s, "unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009854 updateOomAdjLocked(s.app);
9855 b.intent.hasBound = false;
9856 // Assume the client doesn't want to know about a rebind;
9857 // we will deal with that later if it asks for one.
9858 b.intent.doRebind = false;
9859 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
9860 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009861 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009862 serviceDoneExecutingLocked(s, true);
9863 }
9864 }
9865
9866 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
9867 bringDownServiceLocked(s, false);
9868 }
9869 }
9870
9871 public boolean unbindService(IServiceConnection connection) {
9872 synchronized (this) {
9873 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -08009874 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009875 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
9876 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009877 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009878 + connection.asBinder());
9879 return false;
9880 }
9881
9882 final long origId = Binder.clearCallingIdentity();
9883
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009884 while (clist.size() > 0) {
9885 ConnectionRecord r = clist.get(0);
9886 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009887
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009888 if (r.binding.service.app != null) {
9889 // This could have made the service less important.
9890 updateOomAdjLocked(r.binding.service.app);
9891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009892 }
9893
9894 Binder.restoreCallingIdentity(origId);
9895 }
9896
9897 return true;
9898 }
9899
9900 public void publishService(IBinder token, Intent intent, IBinder service) {
9901 // Refuse possible leaked file descriptors
9902 if (intent != null && intent.hasFileDescriptors() == true) {
9903 throw new IllegalArgumentException("File descriptors passed in Intent");
9904 }
9905
9906 synchronized(this) {
9907 if (!(token instanceof ServiceRecord)) {
9908 throw new IllegalArgumentException("Invalid service token");
9909 }
9910 ServiceRecord r = (ServiceRecord)token;
9911
9912 final long origId = Binder.clearCallingIdentity();
9913
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009914 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009915 + " " + intent + ": " + service);
9916 if (r != null) {
9917 Intent.FilterComparison filter
9918 = new Intent.FilterComparison(intent);
9919 IntentBindRecord b = r.bindings.get(filter);
9920 if (b != null && !b.received) {
9921 b.binder = service;
9922 b.requested = true;
9923 b.received = true;
9924 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009925 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009926 = r.connections.values().iterator();
9927 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009928 ArrayList<ConnectionRecord> clist = it.next();
9929 for (int i=0; i<clist.size(); i++) {
9930 ConnectionRecord c = clist.get(i);
9931 if (!filter.equals(c.binding.intent.intent)) {
9932 if (DEBUG_SERVICE) Slog.v(
9933 TAG, "Not publishing to: " + c);
9934 if (DEBUG_SERVICE) Slog.v(
9935 TAG, "Bound intent: " + c.binding.intent.intent);
9936 if (DEBUG_SERVICE) Slog.v(
9937 TAG, "Published intent: " + intent);
9938 continue;
9939 }
9940 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
9941 try {
9942 c.conn.connected(r.name, service);
9943 } catch (Exception e) {
9944 Slog.w(TAG, "Failure sending service " + r.name +
9945 " to connection " + c.conn.asBinder() +
9946 " (in " + c.binding.client.processName + ")", e);
9947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009948 }
9949 }
9950 }
9951 }
9952
9953 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
9954
9955 Binder.restoreCallingIdentity(origId);
9956 }
9957 }
9958 }
9959
9960 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
9961 // Refuse possible leaked file descriptors
9962 if (intent != null && intent.hasFileDescriptors() == true) {
9963 throw new IllegalArgumentException("File descriptors passed in Intent");
9964 }
9965
9966 synchronized(this) {
9967 if (!(token instanceof ServiceRecord)) {
9968 throw new IllegalArgumentException("Invalid service token");
9969 }
9970 ServiceRecord r = (ServiceRecord)token;
9971
9972 final long origId = Binder.clearCallingIdentity();
9973
9974 if (r != null) {
9975 Intent.FilterComparison filter
9976 = new Intent.FilterComparison(intent);
9977 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -08009978 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009979 + " at " + b + ": apps="
9980 + (b != null ? b.apps.size() : 0));
9981 if (b != null) {
9982 if (b.apps.size() > 0) {
9983 // Applications have already bound since the last
9984 // unbind, so just rebind right here.
9985 requestServiceBindingLocked(r, b, true);
9986 } else {
9987 // Note to tell the service the next time there is
9988 // a new client.
9989 b.doRebind = true;
9990 }
9991 }
9992
9993 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
9994
9995 Binder.restoreCallingIdentity(origId);
9996 }
9997 }
9998 }
9999
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010000 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010001 synchronized(this) {
10002 if (!(token instanceof ServiceRecord)) {
10003 throw new IllegalArgumentException("Invalid service token");
10004 }
10005 ServiceRecord r = (ServiceRecord)token;
10006 boolean inStopping = mStoppingServices.contains(token);
10007 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010008 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010009 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010010 + " with incorrect token: given " + token
10011 + ", expected " + r);
10012 return;
10013 }
10014
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010015 if (type == 1) {
10016 // This is a call from a service start... take care of
10017 // book-keeping.
10018 r.callStart = true;
10019 switch (res) {
10020 case Service.START_STICKY_COMPATIBILITY:
10021 case Service.START_STICKY: {
10022 // We are done with the associated start arguments.
10023 r.findDeliveredStart(startId, true);
10024 // Don't stop if killed.
10025 r.stopIfKilled = false;
10026 break;
10027 }
10028 case Service.START_NOT_STICKY: {
10029 // We are done with the associated start arguments.
10030 r.findDeliveredStart(startId, true);
10031 if (r.lastStartId == startId) {
10032 // There is no more work, and this service
10033 // doesn't want to hang around if killed.
10034 r.stopIfKilled = true;
10035 }
10036 break;
10037 }
10038 case Service.START_REDELIVER_INTENT: {
10039 // We'll keep this item until they explicitly
10040 // call stop for it, but keep track of the fact
10041 // that it was delivered.
10042 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
10043 if (si != null) {
10044 si.deliveryCount = 0;
10045 si.doneExecutingCount++;
10046 // Don't stop if killed.
10047 r.stopIfKilled = true;
10048 }
10049 break;
10050 }
10051 default:
10052 throw new IllegalArgumentException(
10053 "Unknown service start result: " + res);
10054 }
10055 if (res == Service.START_STICKY_COMPATIBILITY) {
10056 r.callStart = false;
10057 }
10058 }
10059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010060 final long origId = Binder.clearCallingIdentity();
10061 serviceDoneExecutingLocked(r, inStopping);
10062 Binder.restoreCallingIdentity(origId);
10063 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010064 Slog.w(TAG, "Done executing unknown service from pid "
10065 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010066 }
10067 }
10068 }
10069
10070 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010071 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
10072 + ": nesting=" + r.executeNesting
10073 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010074 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010075 r.executeNesting--;
10076 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010077 if (DEBUG_SERVICE) Slog.v(TAG,
10078 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010079 r.app.executingServices.remove(r);
10080 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010081 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
10082 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010083 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
10084 }
10085 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010086 if (DEBUG_SERVICE) Slog.v(TAG,
10087 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010088 mStoppingServices.remove(r);
10089 }
10090 updateOomAdjLocked(r.app);
10091 }
10092 }
10093
10094 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010095 String anrMessage = null;
10096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010097 synchronized(this) {
10098 if (proc.executingServices.size() == 0 || proc.thread == null) {
10099 return;
10100 }
10101 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
10102 Iterator<ServiceRecord> it = proc.executingServices.iterator();
10103 ServiceRecord timeout = null;
10104 long nextTime = 0;
10105 while (it.hasNext()) {
10106 ServiceRecord sr = it.next();
10107 if (sr.executingStart < maxTime) {
10108 timeout = sr;
10109 break;
10110 }
10111 if (sr.executingStart > nextTime) {
10112 nextTime = sr.executingStart;
10113 }
10114 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010115 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010116 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010117 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010118 } else {
10119 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10120 msg.obj = proc;
10121 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
10122 }
10123 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010124
10125 if (anrMessage != null) {
10126 appNotResponding(proc, null, null, anrMessage);
10127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010128 }
10129
10130 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010131 // BACKUP AND RESTORE
10132 // =========================================================
10133
10134 // Cause the target app to be launched if necessary and its backup agent
10135 // instantiated. The backup agent will invoke backupAgentCreated() on the
10136 // activity manager to announce its creation.
10137 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010138 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010139 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10140
10141 synchronized(this) {
10142 // !!! TODO: currently no check here that we're already bound
10143 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10144 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10145 synchronized (stats) {
10146 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10147 }
10148
10149 BackupRecord r = new BackupRecord(ss, app, backupMode);
10150 ComponentName hostingName = new ComponentName(app.packageName, app.backupAgentName);
10151 // startProcessLocked() returns existing proc's record if it's already running
10152 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070010153 false, 0, "backup", hostingName, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010154 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010155 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010156 return false;
10157 }
10158
10159 r.app = proc;
10160 mBackupTarget = r;
10161 mBackupAppName = app.packageName;
10162
Christopher Tate6fa95972009-06-05 18:43:55 -070010163 // Try not to kill the process during backup
10164 updateOomAdjLocked(proc);
10165
Christopher Tate181fafa2009-05-14 11:12:14 -070010166 // If the process is already attached, schedule the creation of the backup agent now.
10167 // If it is not yet live, this will be done when it attaches to the framework.
10168 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010169 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010170 try {
10171 proc.thread.scheduleCreateBackupAgent(app, backupMode);
10172 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070010173 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070010174 }
10175 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010176 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070010177 }
10178 // Invariants: at this point, the target app process exists and the application
10179 // is either already running or in the process of coming up. mBackupTarget and
10180 // mBackupAppName describe the app, so that when it binds back to the AM we
10181 // know that it's scheduled for a backup-agent operation.
10182 }
10183
10184 return true;
10185 }
10186
10187 // A backup agent has just come up
10188 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010189 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070010190 + " = " + agent);
10191
10192 synchronized(this) {
10193 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010194 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070010195 return;
10196 }
Dianne Hackborn06740692010-09-22 22:46:21 -070010197 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010198
Dianne Hackborn06740692010-09-22 22:46:21 -070010199 long oldIdent = Binder.clearCallingIdentity();
10200 try {
10201 IBackupManager bm = IBackupManager.Stub.asInterface(
10202 ServiceManager.getService(Context.BACKUP_SERVICE));
10203 bm.agentConnected(agentPackageName, agent);
10204 } catch (RemoteException e) {
10205 // can't happen; the backup manager service is local
10206 } catch (Exception e) {
10207 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
10208 e.printStackTrace();
10209 } finally {
10210 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070010211 }
10212 }
10213
10214 // done with this agent
10215 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010216 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070010217 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010218 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070010219 return;
10220 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010221
10222 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070010223 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010224 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070010225 return;
10226 }
10227
Christopher Tate181fafa2009-05-14 11:12:14 -070010228 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010229 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070010230 return;
10231 }
10232
Christopher Tate6fa95972009-06-05 18:43:55 -070010233 ProcessRecord proc = mBackupTarget.app;
10234 mBackupTarget = null;
10235 mBackupAppName = null;
10236
10237 // Not backing this app up any more; reset its OOM adjustment
10238 updateOomAdjLocked(proc);
10239
Christopher Tatec7b31e32009-06-10 15:49:30 -070010240 // If the app crashed during backup, 'thread' will be null here
10241 if (proc.thread != null) {
10242 try {
10243 proc.thread.scheduleDestroyBackupAgent(appInfo);
10244 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010245 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070010246 e.printStackTrace();
10247 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010248 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010249 }
10250 }
10251 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010252 // BROADCASTS
10253 // =========================================================
10254
Josh Bartel7f208742010-02-25 11:01:44 -060010255 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010256 List cur) {
10257 final ContentResolver resolver = mContext.getContentResolver();
10258 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
10259 if (list == null) {
10260 return cur;
10261 }
10262 int N = list.size();
10263 for (int i=0; i<N; i++) {
10264 Intent intent = list.get(i);
10265 if (filter.match(resolver, intent, true, TAG) >= 0) {
10266 if (cur == null) {
10267 cur = new ArrayList<Intent>();
10268 }
10269 cur.add(intent);
10270 }
10271 }
10272 return cur;
10273 }
10274
10275 private final void scheduleBroadcastsLocked() {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010276 if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts: current="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010277 + mBroadcastsScheduled);
10278
10279 if (mBroadcastsScheduled) {
10280 return;
10281 }
10282 mHandler.sendEmptyMessage(BROADCAST_INTENT_MSG);
10283 mBroadcastsScheduled = true;
10284 }
10285
10286 public Intent registerReceiver(IApplicationThread caller,
10287 IIntentReceiver receiver, IntentFilter filter, String permission) {
10288 synchronized(this) {
10289 ProcessRecord callerApp = null;
10290 if (caller != null) {
10291 callerApp = getRecordForAppLocked(caller);
10292 if (callerApp == null) {
10293 throw new SecurityException(
10294 "Unable to find app for caller " + caller
10295 + " (pid=" + Binder.getCallingPid()
10296 + ") when registering receiver " + receiver);
10297 }
10298 }
10299
10300 List allSticky = null;
10301
10302 // Look for any matching sticky broadcasts...
10303 Iterator actions = filter.actionsIterator();
10304 if (actions != null) {
10305 while (actions.hasNext()) {
10306 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060010307 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010308 }
10309 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060010310 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010311 }
10312
10313 // The first sticky in the list is returned directly back to
10314 // the client.
10315 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
10316
Joe Onorato8a9b2202010-02-26 18:56:32 -080010317 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010318 + ": " + sticky);
10319
10320 if (receiver == null) {
10321 return sticky;
10322 }
10323
10324 ReceiverList rl
10325 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
10326 if (rl == null) {
10327 rl = new ReceiverList(this, callerApp,
10328 Binder.getCallingPid(),
10329 Binder.getCallingUid(), receiver);
10330 if (rl.app != null) {
10331 rl.app.receivers.add(rl);
10332 } else {
10333 try {
10334 receiver.asBinder().linkToDeath(rl, 0);
10335 } catch (RemoteException e) {
10336 return sticky;
10337 }
10338 rl.linkedToDeath = true;
10339 }
10340 mRegisteredReceivers.put(receiver.asBinder(), rl);
10341 }
10342 BroadcastFilter bf = new BroadcastFilter(filter, rl, permission);
10343 rl.add(bf);
10344 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010345 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010346 }
10347 mReceiverResolver.addFilter(bf);
10348
10349 // Enqueue broadcasts for all existing stickies that match
10350 // this filter.
10351 if (allSticky != null) {
10352 ArrayList receivers = new ArrayList();
10353 receivers.add(bf);
10354
10355 int N = allSticky.size();
10356 for (int i=0; i<N; i++) {
10357 Intent intent = (Intent)allSticky.get(i);
10358 BroadcastRecord r = new BroadcastRecord(intent, null,
10359 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080010360 false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010361 if (mParallelBroadcasts.size() == 0) {
10362 scheduleBroadcastsLocked();
10363 }
10364 mParallelBroadcasts.add(r);
10365 }
10366 }
10367
10368 return sticky;
10369 }
10370 }
10371
10372 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010373 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010374
10375 boolean doNext = false;
10376
10377 synchronized(this) {
10378 ReceiverList rl
10379 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
10380 if (rl != null) {
10381 if (rl.curBroadcast != null) {
10382 BroadcastRecord r = rl.curBroadcast;
10383 doNext = finishReceiverLocked(
10384 receiver.asBinder(), r.resultCode, r.resultData,
10385 r.resultExtras, r.resultAbort, true);
10386 }
10387
10388 if (rl.app != null) {
10389 rl.app.receivers.remove(rl);
10390 }
10391 removeReceiverLocked(rl);
10392 if (rl.linkedToDeath) {
10393 rl.linkedToDeath = false;
10394 rl.receiver.asBinder().unlinkToDeath(rl, 0);
10395 }
10396 }
10397 }
10398
10399 if (!doNext) {
10400 return;
10401 }
10402
10403 final long origId = Binder.clearCallingIdentity();
10404 processNextBroadcast(false);
10405 trimApplications();
10406 Binder.restoreCallingIdentity(origId);
10407 }
10408
10409 void removeReceiverLocked(ReceiverList rl) {
10410 mRegisteredReceivers.remove(rl.receiver.asBinder());
10411 int N = rl.size();
10412 for (int i=0; i<N; i++) {
10413 mReceiverResolver.removeFilter(rl.get(i));
10414 }
10415 }
10416
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070010417 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
10418 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
10419 ProcessRecord r = mLruProcesses.get(i);
10420 if (r.thread != null) {
10421 try {
10422 r.thread.dispatchPackageBroadcast(cmd, packages);
10423 } catch (RemoteException ex) {
10424 }
10425 }
10426 }
10427 }
10428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010429 private final int broadcastIntentLocked(ProcessRecord callerApp,
10430 String callerPackage, Intent intent, String resolvedType,
10431 IIntentReceiver resultTo, int resultCode, String resultData,
10432 Bundle map, String requiredPermission,
10433 boolean ordered, boolean sticky, int callingPid, int callingUid) {
10434 intent = new Intent(intent);
10435
Joe Onorato8a9b2202010-02-26 18:56:32 -080010436 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010437 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
10438 + " ordered=" + ordered);
10439 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010440 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010441 }
10442
10443 // Handle special intents: if this broadcast is from the package
10444 // manager about a package being removed, we need to remove all of
10445 // its activities from the history stack.
10446 final boolean uidRemoved = intent.ACTION_UID_REMOVED.equals(
10447 intent.getAction());
10448 if (intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
10449 || intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010450 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010451 || uidRemoved) {
10452 if (checkComponentPermission(
10453 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
10454 callingPid, callingUid, -1)
10455 == PackageManager.PERMISSION_GRANTED) {
10456 if (uidRemoved) {
10457 final Bundle intentExtras = intent.getExtras();
10458 final int uid = intentExtras != null
10459 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
10460 if (uid >= 0) {
10461 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
10462 synchronized (bs) {
10463 bs.removeUidStatsLocked(uid);
10464 }
10465 }
10466 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010467 // If resources are unvailble just force stop all
10468 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010469 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010470 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
10471 if (list != null && (list.length > 0)) {
10472 for (String pkg : list) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080010473 forceStopPackageLocked(pkg, -1, false, true, true);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010474 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070010475 sendPackageBroadcastLocked(
10476 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010477 }
10478 } else {
10479 Uri data = intent.getData();
10480 String ssp;
10481 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
10482 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
10483 forceStopPackageLocked(ssp,
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080010484 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070010485 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070010486 if (intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
10487 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
10488 new String[] {ssp});
10489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010490 }
10491 }
10492 }
10493 } else {
10494 String msg = "Permission Denial: " + intent.getAction()
10495 + " broadcast from " + callerPackage + " (pid=" + callingPid
10496 + ", uid=" + callingUid + ")"
10497 + " requires "
10498 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010499 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010500 throw new SecurityException(msg);
10501 }
10502 }
10503
10504 /*
10505 * If this is the time zone changed action, queue up a message that will reset the timezone
10506 * of all currently running processes. This message will get queued up before the broadcast
10507 * happens.
10508 */
10509 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
10510 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
10511 }
10512
Robert Greenwalt03595d02010-11-02 14:08:23 -070010513 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
10514 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
10515 }
10516
Robert Greenwalt434203a2010-10-11 16:00:27 -070010517 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
10518 ProxyProperties proxy = intent.getParcelableExtra("proxy");
10519 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
10520 }
10521
Dianne Hackborn854060af2009-07-09 18:14:31 -070010522 /*
10523 * Prevent non-system code (defined here to be non-persistent
10524 * processes) from sending protected broadcasts.
10525 */
10526 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
10527 || callingUid == Process.SHELL_UID || callingUid == 0) {
10528 // Always okay.
10529 } else if (callerApp == null || !callerApp.persistent) {
10530 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010531 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070010532 intent.getAction())) {
10533 String msg = "Permission Denial: not allowed to send broadcast "
10534 + intent.getAction() + " from pid="
10535 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010536 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070010537 throw new SecurityException(msg);
10538 }
10539 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010540 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070010541 return BROADCAST_SUCCESS;
10542 }
10543 }
10544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010545 // Add to the sticky list if requested.
10546 if (sticky) {
10547 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
10548 callingPid, callingUid)
10549 != PackageManager.PERMISSION_GRANTED) {
10550 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
10551 + callingPid + ", uid=" + callingUid
10552 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010553 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010554 throw new SecurityException(msg);
10555 }
10556 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010557 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010558 + " and enforce permission " + requiredPermission);
10559 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
10560 }
10561 if (intent.getComponent() != null) {
10562 throw new SecurityException(
10563 "Sticky broadcasts can't target a specific component");
10564 }
10565 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
10566 if (list == null) {
10567 list = new ArrayList<Intent>();
10568 mStickyBroadcasts.put(intent.getAction(), list);
10569 }
10570 int N = list.size();
10571 int i;
10572 for (i=0; i<N; i++) {
10573 if (intent.filterEquals(list.get(i))) {
10574 // This sticky already exists, replace it.
10575 list.set(i, new Intent(intent));
10576 break;
10577 }
10578 }
10579 if (i >= N) {
10580 list.add(new Intent(intent));
10581 }
10582 }
10583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010584 // Figure out who all will receive this broadcast.
10585 List receivers = null;
10586 List<BroadcastFilter> registeredReceivers = null;
10587 try {
10588 if (intent.getComponent() != null) {
10589 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010590 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070010591 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010592 if (ai != null) {
10593 receivers = new ArrayList();
10594 ResolveInfo ri = new ResolveInfo();
10595 ri.activityInfo = ai;
10596 receivers.add(ri);
10597 }
10598 } else {
10599 // Need to resolve the intent to interested receivers...
10600 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
10601 == 0) {
10602 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010603 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010604 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 }
Mihai Preda074edef2009-05-18 17:13:31 +020010606 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010607 }
10608 } catch (RemoteException ex) {
10609 // pm is in same process, this will never happen.
10610 }
10611
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010612 final boolean replacePending =
10613 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
10614
Joe Onorato8a9b2202010-02-26 18:56:32 -080010615 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010616 + " replacePending=" + replacePending);
10617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010618 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
10619 if (!ordered && NR > 0) {
10620 // If we are not serializing this broadcast, then send the
10621 // registered receivers separately so they don't wait for the
10622 // components to be launched.
10623 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
10624 callerPackage, callingPid, callingUid, requiredPermission,
10625 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080010626 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010627 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628 TAG, "Enqueueing parallel broadcast " + r
10629 + ": prev had " + mParallelBroadcasts.size());
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010630 boolean replaced = false;
10631 if (replacePending) {
10632 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
10633 if (intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010634 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010635 "***** DROPPING PARALLEL: " + intent);
10636 mParallelBroadcasts.set(i, r);
10637 replaced = true;
10638 break;
10639 }
10640 }
10641 }
10642 if (!replaced) {
10643 mParallelBroadcasts.add(r);
10644 scheduleBroadcastsLocked();
10645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010646 registeredReceivers = null;
10647 NR = 0;
10648 }
10649
10650 // Merge into one list.
10651 int ir = 0;
10652 if (receivers != null) {
10653 // A special case for PACKAGE_ADDED: do not allow the package
10654 // being added to see this broadcast. This prevents them from
10655 // using this as a back door to get run as soon as they are
10656 // installed. Maybe in the future we want to have a special install
10657 // broadcast or such for apps, but we'd like to deliberately make
10658 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010659 String skipPackages[] = null;
10660 if (intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
10661 || intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
10662 || intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
10663 Uri data = intent.getData();
10664 if (data != null) {
10665 String pkgName = data.getSchemeSpecificPart();
10666 if (pkgName != null) {
10667 skipPackages = new String[] { pkgName };
10668 }
10669 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010670 } else if (intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010671 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070010672 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010673 if (skipPackages != null && (skipPackages.length > 0)) {
10674 for (String skipPackage : skipPackages) {
10675 if (skipPackage != null) {
10676 int NT = receivers.size();
10677 for (int it=0; it<NT; it++) {
10678 ResolveInfo curt = (ResolveInfo)receivers.get(it);
10679 if (curt.activityInfo.packageName.equals(skipPackage)) {
10680 receivers.remove(it);
10681 it--;
10682 NT--;
10683 }
10684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010685 }
10686 }
10687 }
10688
10689 int NT = receivers != null ? receivers.size() : 0;
10690 int it = 0;
10691 ResolveInfo curt = null;
10692 BroadcastFilter curr = null;
10693 while (it < NT && ir < NR) {
10694 if (curt == null) {
10695 curt = (ResolveInfo)receivers.get(it);
10696 }
10697 if (curr == null) {
10698 curr = registeredReceivers.get(ir);
10699 }
10700 if (curr.getPriority() >= curt.priority) {
10701 // Insert this broadcast record into the final list.
10702 receivers.add(it, curr);
10703 ir++;
10704 curr = null;
10705 it++;
10706 NT++;
10707 } else {
10708 // Skip to the next ResolveInfo in the final list.
10709 it++;
10710 curt = null;
10711 }
10712 }
10713 }
10714 while (ir < NR) {
10715 if (receivers == null) {
10716 receivers = new ArrayList();
10717 }
10718 receivers.add(registeredReceivers.get(ir));
10719 ir++;
10720 }
10721
10722 if ((receivers != null && receivers.size() > 0)
10723 || resultTo != null) {
10724 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
10725 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080010726 receivers, resultTo, resultCode, resultData, map, ordered,
10727 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010728 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010729 TAG, "Enqueueing ordered broadcast " + r
10730 + ": prev had " + mOrderedBroadcasts.size());
10731 if (DEBUG_BROADCAST) {
10732 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010733 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010734 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010735 boolean replaced = false;
10736 if (replacePending) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010737 for (int i=mOrderedBroadcasts.size()-1; i>0; i--) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010738 if (intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010739 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010740 "***** DROPPING ORDERED: " + intent);
10741 mOrderedBroadcasts.set(i, r);
10742 replaced = true;
10743 break;
10744 }
10745 }
10746 }
10747 if (!replaced) {
10748 mOrderedBroadcasts.add(r);
10749 scheduleBroadcastsLocked();
10750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010751 }
10752
10753 return BROADCAST_SUCCESS;
10754 }
10755
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010756 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010757 // Refuse possible leaked file descriptors
10758 if (intent != null && intent.hasFileDescriptors() == true) {
10759 throw new IllegalArgumentException("File descriptors passed in Intent");
10760 }
10761
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010762 int flags = intent.getFlags();
10763
10764 if (!mProcessesReady) {
10765 // if the caller really truly claims to know what they're doing, go
10766 // ahead and allow the broadcast without launching any receivers
10767 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
10768 intent = new Intent(intent);
10769 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
10770 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
10771 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
10772 + " before boot completion");
10773 throw new IllegalStateException("Cannot broadcast before boot completed");
10774 }
10775 }
10776
10777 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
10778 throw new IllegalArgumentException(
10779 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
10780 }
10781
10782 return intent;
10783 }
10784
10785 public final int broadcastIntent(IApplicationThread caller,
10786 Intent intent, String resolvedType, IIntentReceiver resultTo,
10787 int resultCode, String resultData, Bundle map,
10788 String requiredPermission, boolean serialized, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010789 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010790 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070010791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010792 final ProcessRecord callerApp = getRecordForAppLocked(caller);
10793 final int callingPid = Binder.getCallingPid();
10794 final int callingUid = Binder.getCallingUid();
10795 final long origId = Binder.clearCallingIdentity();
10796 int res = broadcastIntentLocked(callerApp,
10797 callerApp != null ? callerApp.info.packageName : null,
10798 intent, resolvedType, resultTo,
10799 resultCode, resultData, map, requiredPermission, serialized,
10800 sticky, callingPid, callingUid);
10801 Binder.restoreCallingIdentity(origId);
10802 return res;
10803 }
10804 }
10805
10806 int broadcastIntentInPackage(String packageName, int uid,
10807 Intent intent, String resolvedType, IIntentReceiver resultTo,
10808 int resultCode, String resultData, Bundle map,
10809 String requiredPermission, boolean serialized, boolean sticky) {
10810 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010811 intent = verifyBroadcastLocked(intent);
10812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010813 final long origId = Binder.clearCallingIdentity();
10814 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
10815 resultTo, resultCode, resultData, map, requiredPermission,
10816 serialized, sticky, -1, uid);
10817 Binder.restoreCallingIdentity(origId);
10818 return res;
10819 }
10820 }
10821
10822 public final void unbroadcastIntent(IApplicationThread caller,
10823 Intent intent) {
10824 // Refuse possible leaked file descriptors
10825 if (intent != null && intent.hasFileDescriptors() == true) {
10826 throw new IllegalArgumentException("File descriptors passed in Intent");
10827 }
10828
10829 synchronized(this) {
10830 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
10831 != PackageManager.PERMISSION_GRANTED) {
10832 String msg = "Permission Denial: unbroadcastIntent() from pid="
10833 + Binder.getCallingPid()
10834 + ", uid=" + Binder.getCallingUid()
10835 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010836 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010837 throw new SecurityException(msg);
10838 }
10839 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
10840 if (list != null) {
10841 int N = list.size();
10842 int i;
10843 for (i=0; i<N; i++) {
10844 if (intent.filterEquals(list.get(i))) {
10845 list.remove(i);
10846 break;
10847 }
10848 }
10849 }
10850 }
10851 }
10852
10853 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
10854 String resultData, Bundle resultExtras, boolean resultAbort,
10855 boolean explicit) {
10856 if (mOrderedBroadcasts.size() == 0) {
10857 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010858 Slog.w(TAG, "finishReceiver called but no pending broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010859 }
10860 return false;
10861 }
10862 BroadcastRecord r = mOrderedBroadcasts.get(0);
10863 if (r.receiver == null) {
10864 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010865 Slog.w(TAG, "finishReceiver called but none active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866 }
10867 return false;
10868 }
10869 if (r.receiver != receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010870 Slog.w(TAG, "finishReceiver called but active receiver is different");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010871 return false;
10872 }
10873 int state = r.state;
10874 r.state = r.IDLE;
10875 if (state == r.IDLE) {
10876 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010877 Slog.w(TAG, "finishReceiver called but state is IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010878 }
10879 }
10880 r.receiver = null;
10881 r.intent.setComponent(null);
10882 if (r.curApp != null) {
10883 r.curApp.curReceiver = null;
10884 }
10885 if (r.curFilter != null) {
10886 r.curFilter.receiverList.curBroadcast = null;
10887 }
10888 r.curFilter = null;
10889 r.curApp = null;
10890 r.curComponent = null;
10891 r.curReceiver = null;
10892 mPendingBroadcast = null;
10893
10894 r.resultCode = resultCode;
10895 r.resultData = resultData;
10896 r.resultExtras = resultExtras;
10897 r.resultAbort = resultAbort;
10898
10899 // We will process the next receiver right now if this is finishing
10900 // an app receiver (which is always asynchronous) or after we have
10901 // come back from calling a receiver.
10902 return state == BroadcastRecord.APP_RECEIVE
10903 || state == BroadcastRecord.CALL_DONE_RECEIVE;
10904 }
10905
10906 public void finishReceiver(IBinder who, int resultCode, String resultData,
10907 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010908 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010909
10910 // Refuse possible leaked file descriptors
10911 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
10912 throw new IllegalArgumentException("File descriptors passed in Bundle");
10913 }
10914
10915 boolean doNext;
10916
10917 final long origId = Binder.clearCallingIdentity();
10918
10919 synchronized(this) {
10920 doNext = finishReceiverLocked(
10921 who, resultCode, resultData, resultExtras, resultAbort, true);
10922 }
10923
10924 if (doNext) {
10925 processNextBroadcast(false);
10926 }
10927 trimApplications();
10928
10929 Binder.restoreCallingIdentity(origId);
10930 }
10931
Jeff Brown4d94a762010-09-23 11:33:28 -070010932 private final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010933 if (r.nextReceiver > 0) {
10934 Object curReceiver = r.receivers.get(r.nextReceiver-1);
10935 if (curReceiver instanceof BroadcastFilter) {
10936 BroadcastFilter bf = (BroadcastFilter) curReceiver;
Doug Zongker2bec3d42009-12-04 12:52:44 -080010937 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010938 System.identityHashCode(r),
10939 r.intent.getAction(),
10940 r.nextReceiver - 1,
10941 System.identityHashCode(bf));
10942 } else {
Doug Zongker2bec3d42009-12-04 12:52:44 -080010943 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010944 System.identityHashCode(r),
10945 r.intent.getAction(),
10946 r.nextReceiver - 1,
10947 ((ResolveInfo)curReceiver).toString());
10948 }
10949 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010950 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010951 + r);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010952 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010953 System.identityHashCode(r),
10954 r.intent.getAction(),
10955 r.nextReceiver,
10956 "NONE");
10957 }
10958 }
10959
Jeff Brown4d94a762010-09-23 11:33:28 -070010960 private final void setBroadcastTimeoutLocked(long timeoutTime) {
10961 if (! mPendingBroadcastTimeoutMessage) {
10962 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
10963 mHandler.sendMessageAtTime(msg, timeoutTime);
10964 mPendingBroadcastTimeoutMessage = true;
10965 }
10966 }
10967
10968 private final void cancelBroadcastTimeoutLocked() {
10969 if (mPendingBroadcastTimeoutMessage) {
10970 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG);
10971 mPendingBroadcastTimeoutMessage = false;
10972 }
10973 }
10974
10975 private final void broadcastTimeoutLocked(boolean fromMsg) {
10976 if (fromMsg) {
10977 mPendingBroadcastTimeoutMessage = false;
10978 }
10979
10980 if (mOrderedBroadcasts.size() == 0) {
10981 return;
10982 }
10983
10984 long now = SystemClock.uptimeMillis();
10985 BroadcastRecord r = mOrderedBroadcasts.get(0);
10986 if (fromMsg) {
10987 if (mDidDexOpt) {
10988 // Delay timeouts until dexopt finishes.
10989 mDidDexOpt = false;
10990 long timeoutTime = SystemClock.uptimeMillis() + BROADCAST_TIMEOUT;
10991 setBroadcastTimeoutLocked(timeoutTime);
10992 return;
10993 }
10994 if (! mProcessesReady) {
10995 // Only process broadcast timeouts if the system is ready. That way
10996 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
10997 // to do heavy lifting for system up.
10998 return;
10999 }
11000
11001 long timeoutTime = r.receiverTime + BROADCAST_TIMEOUT;
11002 if (timeoutTime > now) {
11003 // We can observe premature timeouts because we do not cancel and reset the
11004 // broadcast timeout message after each receiver finishes. Instead, we set up
11005 // an initial timeout then kick it down the road a little further as needed
11006 // when it expires.
11007 if (DEBUG_BROADCAST) Slog.v(TAG,
11008 "Premature timeout @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
11009 + timeoutTime);
11010 setBroadcastTimeoutLocked(timeoutTime);
11011 return;
11012 }
11013 }
11014
11015 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
11016 + ", started " + (now - r.receiverTime) + "ms ago");
11017 r.receiverTime = now;
11018 r.anrCount++;
11019
11020 // Current receiver has passed its expiration date.
11021 if (r.nextReceiver <= 0) {
11022 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
11023 return;
11024 }
11025
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011026 ProcessRecord app = null;
11027 String anrMessage = null;
11028
Jeff Brown4d94a762010-09-23 11:33:28 -070011029 Object curReceiver = r.receivers.get(r.nextReceiver-1);
11030 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
11031 logBroadcastReceiverDiscardLocked(r);
11032 if (curReceiver instanceof BroadcastFilter) {
11033 BroadcastFilter bf = (BroadcastFilter)curReceiver;
11034 if (bf.receiverList.pid != 0
11035 && bf.receiverList.pid != MY_PID) {
11036 synchronized (this.mPidsSelfLocked) {
11037 app = this.mPidsSelfLocked.get(
11038 bf.receiverList.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011040 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011041 } else {
11042 app = r.curApp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011043 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011044
Jeff Brown4d94a762010-09-23 11:33:28 -070011045 if (app != null) {
11046 anrMessage = "Broadcast of " + r.intent.toString();
11047 }
11048
11049 if (mPendingBroadcast == r) {
11050 mPendingBroadcast = null;
11051 }
11052
11053 // Move on to the next receiver.
11054 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
11055 r.resultExtras, r.resultAbort, true);
11056 scheduleBroadcastsLocked();
11057
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011058 if (anrMessage != null) {
Jeff Brown4d94a762010-09-23 11:33:28 -070011059 // Post the ANR to the handler since we do not want to process ANRs while
11060 // potentially holding our lock.
11061 mHandler.post(new AppNotResponding(app, anrMessage));
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011063 }
11064
11065 private final void processCurBroadcastLocked(BroadcastRecord r,
11066 ProcessRecord app) throws RemoteException {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011067 if (DEBUG_BROADCAST) Slog.v(TAG,
11068 "Process cur broadcast " + r + " for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011069 if (app.thread == null) {
11070 throw new RemoteException();
11071 }
11072 r.receiver = app.thread.asBinder();
11073 r.curApp = app;
11074 app.curReceiver = r;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011075 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011076
11077 // Tell the application to launch this receiver.
11078 r.intent.setComponent(r.curComponent);
11079
11080 boolean started = false;
11081 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011082 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011083 "Delivering to component " + r.curComponent
11084 + ": " + r);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011085 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011086 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
11087 r.resultCode, r.resultData, r.resultExtras, r.ordered);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011088 if (DEBUG_BROADCAST) Slog.v(TAG,
11089 "Process cur broadcast " + r + " DELIVERED for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011090 started = true;
11091 } finally {
11092 if (!started) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011093 if (DEBUG_BROADCAST) Slog.v(TAG,
11094 "Process cur broadcast " + r + ": NOT STARTED!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011095 r.receiver = null;
11096 r.curApp = null;
11097 app.curReceiver = null;
11098 }
11099 }
11100
11101 }
11102
Jeff Brown4d94a762010-09-23 11:33:28 -070011103 static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011104 Intent intent, int resultCode, String data, Bundle extras,
11105 boolean ordered, boolean sticky) throws RemoteException {
Jeff Brown4d94a762010-09-23 11:33:28 -070011106 // Send the intent to the receiver asynchronously using one-way binder calls.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011107 if (app != null && app.thread != null) {
11108 // If we have an app thread, do the call through that so it is
11109 // correctly ordered with other one-way calls.
11110 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011111 data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011112 } else {
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011113 receiver.performReceive(intent, resultCode, data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114 }
11115 }
11116
Jeff Brown4d94a762010-09-23 11:33:28 -070011117 private final void deliverToRegisteredReceiverLocked(BroadcastRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011118 BroadcastFilter filter, boolean ordered) {
11119 boolean skip = false;
11120 if (filter.requiredPermission != null) {
11121 int perm = checkComponentPermission(filter.requiredPermission,
11122 r.callingPid, r.callingUid, -1);
11123 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011124 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011125 + r.intent.toString()
11126 + " from " + r.callerPackage + " (pid="
11127 + r.callingPid + ", uid=" + r.callingUid + ")"
11128 + " requires " + filter.requiredPermission
11129 + " due to registered receiver " + filter);
11130 skip = true;
11131 }
11132 }
11133 if (r.requiredPermission != null) {
11134 int perm = checkComponentPermission(r.requiredPermission,
11135 filter.receiverList.pid, filter.receiverList.uid, -1);
11136 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011137 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011138 + r.intent.toString()
11139 + " to " + filter.receiverList.app
11140 + " (pid=" + filter.receiverList.pid
11141 + ", uid=" + filter.receiverList.uid + ")"
11142 + " requires " + r.requiredPermission
11143 + " due to sender " + r.callerPackage
11144 + " (uid " + r.callingUid + ")");
11145 skip = true;
11146 }
11147 }
11148
11149 if (!skip) {
11150 // If this is not being sent as an ordered broadcast, then we
11151 // don't want to touch the fields that keep track of the current
11152 // state of ordered broadcasts.
11153 if (ordered) {
11154 r.receiver = filter.receiverList.receiver.asBinder();
11155 r.curFilter = filter;
11156 filter.receiverList.curBroadcast = r;
11157 r.state = BroadcastRecord.CALL_IN_RECEIVE;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011158 if (filter.receiverList.app != null) {
11159 // Bump hosting application to no longer be in background
11160 // scheduling class. Note that we can't do that if there
11161 // isn't an app... but we can only be in that case for
11162 // things that directly call the IActivityManager API, which
11163 // are already core system stuff so don't matter for this.
11164 r.curApp = filter.receiverList.app;
11165 filter.receiverList.app.curReceiver = r;
11166 updateOomAdjLocked();
11167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011168 }
11169 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011170 if (DEBUG_BROADCAST_LIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011171 int seq = r.intent.getIntExtra("seq", -1);
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011172 Slog.i(TAG, "Delivering to " + filter
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011173 + " (seq=" + seq + "): " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011174 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011175 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011176 new Intent(r.intent), r.resultCode,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011177 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011178 if (ordered) {
11179 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
11180 }
11181 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011182 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011183 if (ordered) {
11184 r.receiver = null;
11185 r.curFilter = null;
11186 filter.receiverList.curBroadcast = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011187 if (filter.receiverList.app != null) {
11188 filter.receiverList.app.curReceiver = null;
11189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011190 }
11191 }
11192 }
11193 }
11194
Dianne Hackborn12527f92009-11-11 17:39:50 -080011195 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
11196 if (r.callingUid < 0) {
11197 // This was from a registerReceiver() call; ignore it.
11198 return;
11199 }
11200 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
11201 MAX_BROADCAST_HISTORY-1);
11202 r.finishTime = SystemClock.uptimeMillis();
11203 mBroadcastHistory[0] = r;
11204 }
11205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011206 private final void processNextBroadcast(boolean fromMsg) {
11207 synchronized(this) {
11208 BroadcastRecord r;
11209
Joe Onorato8a9b2202010-02-26 18:56:32 -080011210 if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 + mParallelBroadcasts.size() + " broadcasts, "
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011212 + mOrderedBroadcasts.size() + " ordered broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011213
11214 updateCpuStats();
11215
11216 if (fromMsg) {
11217 mBroadcastsScheduled = false;
11218 }
11219
11220 // First, deliver any non-serialized broadcasts right away.
11221 while (mParallelBroadcasts.size() > 0) {
11222 r = mParallelBroadcasts.remove(0);
Dianne Hackborn12527f92009-11-11 17:39:50 -080011223 r.dispatchTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011224 final int N = r.receivers.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011225 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011226 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011227 for (int i=0; i<N; i++) {
11228 Object target = r.receivers.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011229 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011230 "Delivering non-ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011231 + target + ": " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070011232 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011233 }
Dianne Hackborn12527f92009-11-11 17:39:50 -080011234 addBroadcastToHistoryLocked(r);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011235 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011236 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011237 }
11238
11239 // Now take care of the next serialized one...
11240
11241 // If we are waiting for a process to come up to handle the next
11242 // broadcast, then do nothing at this point. Just in case, we
11243 // check that the process we're waiting for still exists.
11244 if (mPendingBroadcast != null) {
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070011245 if (DEBUG_BROADCAST_LIGHT) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011246 Slog.v(TAG, "processNextBroadcast: waiting for "
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070011247 + mPendingBroadcast.curApp);
11248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011249
11250 boolean isDead;
11251 synchronized (mPidsSelfLocked) {
11252 isDead = (mPidsSelfLocked.get(mPendingBroadcast.curApp.pid) == null);
11253 }
11254 if (!isDead) {
11255 // It's still alive, so keep waiting
11256 return;
11257 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011258 Slog.w(TAG, "pending app " + mPendingBroadcast.curApp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011259 + " died before responding to broadcast");
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011260 mPendingBroadcast.state = BroadcastRecord.IDLE;
11261 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011262 mPendingBroadcast = null;
11263 }
11264 }
11265
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011266 boolean looped = false;
11267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011268 do {
11269 if (mOrderedBroadcasts.size() == 0) {
11270 // No more broadcasts pending, so all done!
11271 scheduleAppGcsLocked();
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011272 if (looped) {
11273 // If we had finished the last ordered broadcast, then
11274 // make sure all processes have correct oom and sched
11275 // adjustments.
11276 updateOomAdjLocked();
11277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011278 return;
11279 }
11280 r = mOrderedBroadcasts.get(0);
11281 boolean forceReceive = false;
11282
11283 // Ensure that even if something goes awry with the timeout
11284 // detection, we catch "hung" broadcasts here, discard them,
Jeff Hamiltonacf84742010-05-25 22:10:18 -050011285 // and continue to make progress.
11286 //
11287 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
Jeff Brown4d94a762010-09-23 11:33:28 -070011288 // receivers don't get executed with timeouts. They're intended for
Jeff Hamiltonacf84742010-05-25 22:10:18 -050011289 // one time heavy lifting after system upgrades and can take
11290 // significant amounts of time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011291 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011292 if (mProcessesReady && r.dispatchTime > 0) {
Jeff Hamiltonacf84742010-05-25 22:10:18 -050011293 long now = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011294 if ((numReceivers > 0) &&
11295 (now > r.dispatchTime + (2*BROADCAST_TIMEOUT*numReceivers))) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011296 Slog.w(TAG, "Hung broadcast discarded after timeout failure:"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297 + " now=" + now
11298 + " dispatchTime=" + r.dispatchTime
Dianne Hackborn12527f92009-11-11 17:39:50 -080011299 + " startTime=" + r.receiverTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011300 + " intent=" + r.intent
11301 + " numReceivers=" + numReceivers
11302 + " nextReceiver=" + r.nextReceiver
11303 + " state=" + r.state);
Jeff Brown4d94a762010-09-23 11:33:28 -070011304 broadcastTimeoutLocked(false); // forcibly finish this broadcast
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011305 forceReceive = true;
11306 r.state = BroadcastRecord.IDLE;
11307 }
11308 }
11309
11310 if (r.state != BroadcastRecord.IDLE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011311 if (DEBUG_BROADCAST) Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011312 "processNextBroadcast() called when not idle (state="
11313 + r.state + ")");
11314 return;
11315 }
11316
11317 if (r.receivers == null || r.nextReceiver >= numReceivers
11318 || r.resultAbort || forceReceive) {
11319 // No more receivers for this broadcast! Send the final
11320 // result if requested...
11321 if (r.resultTo != null) {
11322 try {
11323 if (DEBUG_BROADCAST) {
11324 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011325 Slog.i(TAG, "Finishing broadcast " + r.intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011326 + " seq=" + seq + " app=" + r.callerApp);
11327 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011328 performReceiveLocked(r.callerApp, r.resultTo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011329 new Intent(r.intent), r.resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011330 r.resultData, r.resultExtras, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011332 Slog.w(TAG, "Failure sending broadcast result of " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 }
11334 }
11335
Joe Onorato8a9b2202010-02-26 18:56:32 -080011336 if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
Jeff Brown4d94a762010-09-23 11:33:28 -070011337 cancelBroadcastTimeoutLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011338
Joe Onorato8a9b2202010-02-26 18:56:32 -080011339 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011340 + r);
11341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011342 // ... and on to the next...
Dianne Hackborn12527f92009-11-11 17:39:50 -080011343 addBroadcastToHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011344 mOrderedBroadcasts.remove(0);
11345 r = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011346 looped = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011347 continue;
11348 }
11349 } while (r == null);
11350
11351 // Get the next receiver...
11352 int recIdx = r.nextReceiver++;
11353
11354 // Keep track of when this receiver started, and make sure there
11355 // is a timeout message pending to kill it if need be.
Dianne Hackborn12527f92009-11-11 17:39:50 -080011356 r.receiverTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011357 if (recIdx == 0) {
Dianne Hackborn12527f92009-11-11 17:39:50 -080011358 r.dispatchTime = r.receiverTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011359
Joe Onorato8a9b2202010-02-26 18:56:32 -080011360 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011361 + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070011362 }
11363 if (! mPendingBroadcastTimeoutMessage) {
11364 long timeoutTime = r.receiverTime + BROADCAST_TIMEOUT;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011365 if (DEBUG_BROADCAST) Slog.v(TAG,
Jeff Brown4d94a762010-09-23 11:33:28 -070011366 "Submitting BROADCAST_TIMEOUT_MSG for " + r + " at " + timeoutTime);
11367 setBroadcastTimeoutLocked(timeoutTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011368 }
11369
11370 Object nextReceiver = r.receivers.get(recIdx);
11371 if (nextReceiver instanceof BroadcastFilter) {
11372 // Simple case: this is a registered receiver who gets
11373 // a direct call.
11374 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011375 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011376 "Delivering ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011377 + filter + ": " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070011378 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 if (r.receiver == null || !r.ordered) {
11380 // The receiver has already finished, so schedule to
11381 // process the next one.
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011382 if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing: ordered="
11383 + r.ordered + " receiver=" + r.receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011384 r.state = BroadcastRecord.IDLE;
11385 scheduleBroadcastsLocked();
11386 }
11387 return;
11388 }
11389
11390 // Hard case: need to instantiate the receiver, possibly
11391 // starting its application process to host it.
11392
11393 ResolveInfo info =
11394 (ResolveInfo)nextReceiver;
11395
11396 boolean skip = false;
11397 int perm = checkComponentPermission(info.activityInfo.permission,
11398 r.callingPid, r.callingUid,
11399 info.activityInfo.exported
11400 ? -1 : info.activityInfo.applicationInfo.uid);
11401 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011402 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011403 + r.intent.toString()
11404 + " from " + r.callerPackage + " (pid=" + r.callingPid
11405 + ", uid=" + r.callingUid + ")"
11406 + " requires " + info.activityInfo.permission
11407 + " due to receiver " + info.activityInfo.packageName
11408 + "/" + info.activityInfo.name);
11409 skip = true;
11410 }
11411 if (r.callingUid != Process.SYSTEM_UID &&
11412 r.requiredPermission != null) {
11413 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011414 perm = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011415 checkPermission(r.requiredPermission,
11416 info.activityInfo.applicationInfo.packageName);
11417 } catch (RemoteException e) {
11418 perm = PackageManager.PERMISSION_DENIED;
11419 }
11420 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011421 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011422 + r.intent + " to "
11423 + info.activityInfo.applicationInfo.packageName
11424 + " requires " + r.requiredPermission
11425 + " due to sender " + r.callerPackage
11426 + " (uid " + r.callingUid + ")");
11427 skip = true;
11428 }
11429 }
11430 if (r.curApp != null && r.curApp.crashing) {
11431 // If the target process is crashing, just skip it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011432 if (DEBUG_BROADCAST) Slog.v(TAG,
11433 "Skipping deliver ordered " + r + " to " + r.curApp
11434 + ": process crashing");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011435 skip = true;
11436 }
11437
11438 if (skip) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011439 if (DEBUG_BROADCAST) Slog.v(TAG,
11440 "Skipping delivery of ordered " + r + " for whatever reason");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011441 r.receiver = null;
11442 r.curFilter = null;
11443 r.state = BroadcastRecord.IDLE;
11444 scheduleBroadcastsLocked();
11445 return;
11446 }
11447
11448 r.state = BroadcastRecord.APP_RECEIVE;
11449 String targetProcess = info.activityInfo.processName;
11450 r.curComponent = new ComponentName(
11451 info.activityInfo.applicationInfo.packageName,
11452 info.activityInfo.name);
11453 r.curReceiver = info.activityInfo;
11454
11455 // Is this receiver's application already running?
11456 ProcessRecord app = getProcessRecordLocked(targetProcess,
11457 info.activityInfo.applicationInfo.uid);
11458 if (app != null && app.thread != null) {
11459 try {
11460 processCurBroadcastLocked(r, app);
11461 return;
11462 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011463 Slog.w(TAG, "Exception when sending broadcast to "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011464 + r.curComponent, e);
11465 }
11466
11467 // If a dead object exception was thrown -- fall through to
11468 // restart the application.
11469 }
11470
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011471 // Not running -- get it started, to be executed when the app comes up.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011472 if (DEBUG_BROADCAST) Slog.v(TAG,
11473 "Need to start app " + targetProcess + " for broadcast " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011474 if ((r.curApp=startProcessLocked(targetProcess,
11475 info.activityInfo.applicationInfo, true,
11476 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011477 "broadcast", r.curComponent,
11478 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0))
11479 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011480 // Ah, this recipient is unavailable. Finish it if necessary,
11481 // and mark the broadcast record as ready for the next.
Joe Onorato8a9b2202010-02-26 18:56:32 -080011482 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011483 + info.activityInfo.applicationInfo.packageName + "/"
11484 + info.activityInfo.applicationInfo.uid + " for broadcast "
11485 + r.intent + ": process is bad");
Jeff Brown4d94a762010-09-23 11:33:28 -070011486 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011487 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
11488 r.resultExtras, r.resultAbort, true);
11489 scheduleBroadcastsLocked();
11490 r.state = BroadcastRecord.IDLE;
11491 return;
11492 }
11493
11494 mPendingBroadcast = r;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011495 mPendingBroadcastRecvIndex = recIdx;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011496 }
11497 }
11498
11499 // =========================================================
11500 // INSTRUMENTATION
11501 // =========================================================
11502
11503 public boolean startInstrumentation(ComponentName className,
11504 String profileFile, int flags, Bundle arguments,
11505 IInstrumentationWatcher watcher) {
11506 // Refuse possible leaked file descriptors
11507 if (arguments != null && arguments.hasFileDescriptors()) {
11508 throw new IllegalArgumentException("File descriptors passed in Bundle");
11509 }
11510
11511 synchronized(this) {
11512 InstrumentationInfo ii = null;
11513 ApplicationInfo ai = null;
11514 try {
11515 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011516 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011517 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011518 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011519 } catch (PackageManager.NameNotFoundException e) {
11520 }
11521 if (ii == null) {
11522 reportStartInstrumentationFailure(watcher, className,
11523 "Unable to find instrumentation info for: " + className);
11524 return false;
11525 }
11526 if (ai == null) {
11527 reportStartInstrumentationFailure(watcher, className,
11528 "Unable to find instrumentation target package: " + ii.targetPackage);
11529 return false;
11530 }
11531
11532 int match = mContext.getPackageManager().checkSignatures(
11533 ii.targetPackage, ii.packageName);
11534 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11535 String msg = "Permission Denial: starting instrumentation "
11536 + className + " from pid="
11537 + Binder.getCallingPid()
11538 + ", uid=" + Binder.getCallingPid()
11539 + " not allowed because package " + ii.packageName
11540 + " does not have a signature matching the target "
11541 + ii.targetPackage;
11542 reportStartInstrumentationFailure(watcher, className, msg);
11543 throw new SecurityException(msg);
11544 }
11545
11546 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080011547 forceStopPackageLocked(ii.targetPackage, -1, true, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011548 ProcessRecord app = addAppLocked(ai);
11549 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011550 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011551 app.instrumentationProfileFile = profileFile;
11552 app.instrumentationArguments = arguments;
11553 app.instrumentationWatcher = watcher;
11554 app.instrumentationResultClass = className;
11555 Binder.restoreCallingIdentity(origId);
11556 }
11557
11558 return true;
11559 }
11560
11561 /**
11562 * Report errors that occur while attempting to start Instrumentation. Always writes the
11563 * error to the logs, but if somebody is watching, send the report there too. This enables
11564 * the "am" command to report errors with more information.
11565 *
11566 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11567 * @param cn The component name of the instrumentation.
11568 * @param report The error report.
11569 */
11570 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11571 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011572 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011573 try {
11574 if (watcher != null) {
11575 Bundle results = new Bundle();
11576 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11577 results.putString("Error", report);
11578 watcher.instrumentationStatus(cn, -1, results);
11579 }
11580 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011581 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011582 }
11583 }
11584
11585 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11586 if (app.instrumentationWatcher != null) {
11587 try {
11588 // NOTE: IInstrumentationWatcher *must* be oneway here
11589 app.instrumentationWatcher.instrumentationFinished(
11590 app.instrumentationClass,
11591 resultCode,
11592 results);
11593 } catch (RemoteException e) {
11594 }
11595 }
11596 app.instrumentationWatcher = null;
11597 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011598 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011599 app.instrumentationProfileFile = null;
11600 app.instrumentationArguments = null;
11601
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080011602 forceStopPackageLocked(app.processName, -1, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011603 }
11604
11605 public void finishInstrumentation(IApplicationThread target,
11606 int resultCode, Bundle results) {
11607 // Refuse possible leaked file descriptors
11608 if (results != null && results.hasFileDescriptors()) {
11609 throw new IllegalArgumentException("File descriptors passed in Intent");
11610 }
11611
11612 synchronized(this) {
11613 ProcessRecord app = getRecordForAppLocked(target);
11614 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011615 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011616 return;
11617 }
11618 final long origId = Binder.clearCallingIdentity();
11619 finishInstrumentationLocked(app, resultCode, results);
11620 Binder.restoreCallingIdentity(origId);
11621 }
11622 }
11623
11624 // =========================================================
11625 // CONFIGURATION
11626 // =========================================================
11627
11628 public ConfigurationInfo getDeviceConfigurationInfo() {
11629 ConfigurationInfo config = new ConfigurationInfo();
11630 synchronized (this) {
11631 config.reqTouchScreen = mConfiguration.touchscreen;
11632 config.reqKeyboardType = mConfiguration.keyboard;
11633 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011634 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
11635 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
11637 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011638 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
11639 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011640 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
11641 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070011642 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011643 }
11644 return config;
11645 }
11646
11647 public Configuration getConfiguration() {
11648 Configuration ci;
11649 synchronized(this) {
11650 ci = new Configuration(mConfiguration);
11651 }
11652 return ci;
11653 }
11654
11655 public void updateConfiguration(Configuration values) {
11656 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11657 "updateConfiguration()");
11658
11659 synchronized(this) {
11660 if (values == null && mWindowManager != null) {
11661 // sentinel: fetch the current configuration from the window manager
11662 values = mWindowManager.computeNewConfiguration();
11663 }
11664
11665 final long origId = Binder.clearCallingIdentity();
11666 updateConfigurationLocked(values, null);
11667 Binder.restoreCallingIdentity(origId);
11668 }
11669 }
11670
11671 /**
11672 * Do either or both things: (1) change the current configuration, and (2)
11673 * make sure the given activity is running with the (now) current
11674 * configuration. Returns true if the activity has been left running, or
11675 * false if <var>starting</var> is being destroyed to match the new
11676 * configuration.
11677 */
11678 public boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011679 ActivityRecord starting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011680 int changes = 0;
11681
11682 boolean kept = true;
11683
11684 if (values != null) {
11685 Configuration newConfig = new Configuration(mConfiguration);
11686 changes = newConfig.updateFrom(values);
11687 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011688 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011689 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011690 }
11691
Doug Zongker2bec3d42009-12-04 12:52:44 -080011692 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011693
11694 if (values.locale != null) {
11695 saveLocaleLocked(values.locale,
11696 !values.locale.equals(mConfiguration.locale),
11697 values.userSetLocale);
11698 }
11699
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011700 mConfigurationSeq++;
11701 if (mConfigurationSeq <= 0) {
11702 mConfigurationSeq = 1;
11703 }
11704 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011705 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011706 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011707
11708 AttributeCache ac = AttributeCache.instance();
11709 if (ac != null) {
11710 ac.updateConfiguration(mConfiguration);
11711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011712
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011713 if (Settings.System.hasInterestingConfigurationChanges(changes)) {
11714 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
11715 msg.obj = new Configuration(mConfiguration);
11716 mHandler.sendMessage(msg);
11717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011719 for (int i=mLruProcesses.size()-1; i>=0; i--) {
11720 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011721 try {
11722 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011723 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011724 + app.processName + " new config " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011725 app.thread.scheduleConfigurationChanged(mConfiguration);
11726 }
11727 } catch (Exception e) {
11728 }
11729 }
11730 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011731 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
11732 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011733 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
11734 null, false, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011735 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
11736 broadcastIntentLocked(null, null,
11737 new Intent(Intent.ACTION_LOCALE_CHANGED),
11738 null, null, 0, null, null,
11739 null, false, false, MY_PID, Process.SYSTEM_UID);
11740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011741 }
11742 }
11743
11744 if (changes != 0 && starting == null) {
11745 // If the configuration changed, and the caller is not already
11746 // in the process of starting an activity, then find the top
11747 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011748 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011749 }
11750
11751 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011752 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011753 if (kept) {
11754 // If this didn't result in the starting activity being
11755 // destroyed, then we need to make sure at this point that all
11756 // other activities are made visible.
Joe Onorato8a9b2202010-02-26 18:56:32 -080011757 if (DEBUG_SWITCH) Slog.i(TAG, "Config didn't destroy " + starting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011758 + ", ensuring others are correct.");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011759 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011760 }
11761 }
11762
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011763 if (values != null && mWindowManager != null) {
11764 mWindowManager.setNewConfiguration(mConfiguration);
11765 }
11766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011767 return kept;
11768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011769
11770 /**
11771 * Save the locale. You must be inside a synchronized (this) block.
11772 */
11773 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
11774 if(isDiff) {
11775 SystemProperties.set("user.language", l.getLanguage());
11776 SystemProperties.set("user.region", l.getCountry());
11777 }
11778
11779 if(isPersist) {
11780 SystemProperties.set("persist.sys.language", l.getLanguage());
11781 SystemProperties.set("persist.sys.country", l.getCountry());
11782 SystemProperties.set("persist.sys.localevar", l.getVariant());
11783 }
11784 }
11785
11786 // =========================================================
11787 // LIFETIME MANAGEMENT
11788 // =========================================================
11789
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011790 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
11791 ProcessRecord TOP_APP, boolean recursed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011792 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011793 // This adjustment has already been computed. If we are calling
11794 // from the top, we may have already computed our adjustment with
11795 // an earlier hidden adjustment that isn't really for us... if
11796 // so, use the new hidden adjustment.
11797 if (!recursed && app.hidden) {
11798 app.curAdj = hiddenAdj;
11799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011800 return app.curAdj;
11801 }
11802
11803 if (app.thread == null) {
11804 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011805 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011806 return (app.curAdj=EMPTY_APP_ADJ);
11807 }
11808
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011809 if (app.maxAdj <= FOREGROUND_APP_ADJ) {
11810 // The max adjustment doesn't allow this app to be anything
11811 // below foreground, so it is not worth doing work for it.
11812 app.adjType = "fixed";
11813 app.adjSeq = mAdjSeq;
11814 app.curRawAdj = app.maxAdj;
Dianne Hackborn287952c2010-09-22 22:34:31 -070011815 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011816 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
11817 return (app.curAdj=app.maxAdj);
11818 }
11819
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011820 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011821 app.adjSource = null;
11822 app.adjTarget = null;
Dianne Hackborn287952c2010-09-22 22:34:31 -070011823 app.keeping = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011824 app.empty = false;
11825 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011826
The Android Open Source Project4df24232009-03-05 14:34:35 -080011827 // Determine the importance of the process, starting with most
11828 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011829 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011830 int schedGroup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011831 int N;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011832 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011833 // The last app on the list is the foreground app.
11834 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011835 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011836 app.adjType = "top-activity";
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011837 } else if (app.instrumentationClass != null) {
11838 // Don't want to kill running instrumentation.
11839 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011840 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011841 app.adjType = "instrumentation";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011842 } else if (app.curReceiver != null ||
11843 (mPendingBroadcast != null && mPendingBroadcast.curApp == app)) {
11844 // An app that is currently receiving a broadcast also
11845 // counts as being in the foreground.
11846 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011847 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011848 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011849 } else if (app.executingServices.size() > 0) {
11850 // An app that is currently executing a service callback also
11851 // counts as being in the foreground.
11852 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011853 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011854 app.adjType = "exec-service";
11855 } else if (app.foregroundServices) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856 // The user is aware of this app, so make it visible.
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011857 adj = PERCEPTIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011858 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011859 app.adjType = "foreground-service";
11860 } else if (app.forcingToForeground != null) {
11861 // The user is aware of this app, so make it visible.
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011862 adj = PERCEPTIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011863 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011864 app.adjType = "force-foreground";
11865 app.adjSource = app.forcingToForeground;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011866 } else if (app == mHeavyWeightProcess) {
11867 // We don't want to kill the current heavy-weight process.
11868 adj = HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080011869 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011870 app.adjType = "heavy";
The Android Open Source Project4df24232009-03-05 14:34:35 -080011871 } else if (app == mHomeProcess) {
11872 // This process is hosting what we currently consider to be the
11873 // home app, so we don't want to let it go into the background.
11874 adj = HOME_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011875 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011876 app.adjType = "home";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011877 } else if ((N=app.activities.size()) != 0) {
11878 // This app is in the background with paused activities.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011879 app.hidden = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011880 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011881 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011882 app.adjType = "bg-activities";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011883 N = app.activities.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011884 for (int j=0; j<N; j++) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080011885 ActivityRecord r = app.activities.get(j);
11886 if (r.visible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011887 // This app has a visible activity!
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011888 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011889 adj = VISIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011890 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011891 app.adjType = "visible";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011892 break;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080011893 } else if (r.state == ActivityState.PAUSING
11894 || r.state == ActivityState.PAUSED
11895 || r.state == ActivityState.STOPPING) {
11896 adj = PERCEPTIBLE_APP_ADJ;
11897 app.adjType = "stopping";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011898 }
11899 }
11900 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011901 // A very not-needed process. If this is lower in the lru list,
11902 // we will push it in to the empty bucket.
11903 app.hidden = true;
11904 app.empty = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011905 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011906 adj = hiddenAdj;
11907 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011908 }
11909
Joe Onorato8a9b2202010-02-26 18:56:32 -080011910 //Slog.i(TAG, "OOM " + app + ": initial adj=" + adj);
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011911
The Android Open Source Project4df24232009-03-05 14:34:35 -080011912 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011913 // there are applications dependent on our services or providers, but
11914 // this gives us a baseline and makes sure we don't get into an
11915 // infinite recursion.
11916 app.adjSeq = mAdjSeq;
11917 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011918
Christopher Tate6fa95972009-06-05 18:43:55 -070011919 if (mBackupTarget != null && app == mBackupTarget.app) {
11920 // If possible we want to avoid killing apps while they're being backed up
11921 if (adj > BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011922 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Christopher Tate6fa95972009-06-05 18:43:55 -070011923 adj = BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011924 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011925 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070011926 }
11927 }
11928
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011929 if (app.services.size() != 0 && (adj > FOREGROUND_APP_ADJ
11930 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011931 final long now = SystemClock.uptimeMillis();
11932 // This process is more important if the top activity is
11933 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070011934 Iterator<ServiceRecord> jt = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011935 while (jt.hasNext() && adj > FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011936 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011937 if (s.startRequested) {
11938 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
11939 // This service has seen some activity within
11940 // recent memory, so we will keep its process ahead
11941 // of the background processes.
11942 if (adj > SECONDARY_SERVER_ADJ) {
11943 adj = SECONDARY_SERVER_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011944 app.adjType = "started-services";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011945 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011946 }
11947 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080011948 // If we have let the service slide into the background
11949 // state, still have some text describing what it is doing
11950 // even though the service no longer has an impact.
11951 if (adj > SECONDARY_SERVER_ADJ) {
11952 app.adjType = "started-bg-services";
11953 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011954 // Don't kill this process because it is doing work; it
11955 // has said it is doing work.
11956 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011957 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011958 if (s.connections.size() > 0 && (adj > FOREGROUND_APP_ADJ
11959 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011960 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011961 = s.connections.values().iterator();
11962 while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011963 ArrayList<ConnectionRecord> clist = kt.next();
11964 for (int i=0; i<clist.size() && adj > FOREGROUND_APP_ADJ; i++) {
11965 // XXX should compute this based on the max of
11966 // all connected clients.
11967 ConnectionRecord cr = clist.get(i);
11968 if (cr.binding.client == app) {
11969 // Binding to ourself is not interesting.
11970 continue;
11971 }
11972 if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
11973 ProcessRecord client = cr.binding.client;
11974 int myHiddenAdj = hiddenAdj;
11975 if (myHiddenAdj > client.hiddenAdj) {
11976 if (client.hiddenAdj >= VISIBLE_APP_ADJ) {
11977 myHiddenAdj = client.hiddenAdj;
11978 } else {
11979 myHiddenAdj = VISIBLE_APP_ADJ;
11980 }
11981 }
11982 int clientAdj = computeOomAdjLocked(
11983 client, myHiddenAdj, TOP_APP, true);
11984 if (adj > clientAdj) {
11985 adj = clientAdj >= VISIBLE_APP_ADJ
11986 ? clientAdj : VISIBLE_APP_ADJ;
11987 if (!client.hidden) {
11988 app.hidden = false;
11989 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011990 if (client.keeping) {
11991 app.keeping = true;
11992 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011993 app.adjType = "service";
11994 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
11995 .REASON_SERVICE_IN_USE;
11996 app.adjSource = cr.binding.client;
11997 app.adjTarget = s.name;
11998 }
11999 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12000 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12001 schedGroup = Process.THREAD_GROUP_DEFAULT;
12002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012003 }
12004 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012005 ActivityRecord a = cr.activity;
12006 //if (a != null) {
12007 // Slog.i(TAG, "Connection to " + a ": state=" + a.state);
12008 //}
12009 if (a != null && adj > FOREGROUND_APP_ADJ &&
12010 (a.state == ActivityState.RESUMED
12011 || a.state == ActivityState.PAUSING)) {
12012 adj = FOREGROUND_APP_ADJ;
12013 schedGroup = Process.THREAD_GROUP_DEFAULT;
12014 app.hidden = false;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012015 app.adjType = "service";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012016 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12017 .REASON_SERVICE_IN_USE;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012018 app.adjSource = a;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012019 app.adjTarget = s.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012021 }
12022 }
12023 }
12024 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012025
Dianne Hackborn287952c2010-09-22 22:34:31 -070012026 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012027 // would like to avoid killing it unless it would prevent the current
12028 // application from running. By default we put the process in
12029 // with the rest of the background processes; as we scan through
12030 // its services we may bump it up from there.
12031 if (adj > hiddenAdj) {
12032 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012033 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012034 app.adjType = "bg-services";
12035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012036 }
12037
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012038 if (app.pubProviders.size() != 0 && (adj > FOREGROUND_APP_ADJ
12039 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012040 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012041 while (jt.hasNext() && (adj > FOREGROUND_APP_ADJ
12042 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012043 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012044 if (cpr.clients.size() != 0) {
12045 Iterator<ProcessRecord> kt = cpr.clients.iterator();
12046 while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
12047 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070012048 if (client == app) {
12049 // Being our own client is not interesting.
12050 continue;
12051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012052 int myHiddenAdj = hiddenAdj;
12053 if (myHiddenAdj > client.hiddenAdj) {
12054 if (client.hiddenAdj > FOREGROUND_APP_ADJ) {
12055 myHiddenAdj = client.hiddenAdj;
12056 } else {
12057 myHiddenAdj = FOREGROUND_APP_ADJ;
12058 }
12059 }
12060 int clientAdj = computeOomAdjLocked(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012061 client, myHiddenAdj, TOP_APP, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012062 if (adj > clientAdj) {
12063 adj = clientAdj > FOREGROUND_APP_ADJ
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012064 ? clientAdj : FOREGROUND_APP_ADJ;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012065 if (!client.hidden) {
12066 app.hidden = false;
12067 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012068 if (client.keeping) {
12069 app.keeping = true;
12070 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012071 app.adjType = "provider";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012072 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12073 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012074 app.adjSource = client;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012075 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012076 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012077 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12078 schedGroup = Process.THREAD_GROUP_DEFAULT;
12079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012080 }
12081 }
12082 // If the provider has external (non-framework) process
12083 // dependencies, ensure that its adjustment is at least
12084 // FOREGROUND_APP_ADJ.
12085 if (cpr.externals != 0) {
12086 if (adj > FOREGROUND_APP_ADJ) {
12087 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012088 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012089 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012090 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012091 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012092 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012093 }
12094 }
12095 }
12096 }
12097
12098 app.curRawAdj = adj;
12099
Joe Onorato8a9b2202010-02-26 18:56:32 -080012100 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012101 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12102 if (adj > app.maxAdj) {
12103 adj = app.maxAdj;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012104 if (app.maxAdj <= PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012105 schedGroup = Process.THREAD_GROUP_DEFAULT;
12106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012107 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012108 if (adj < HIDDEN_APP_MIN_ADJ) {
12109 app.keeping = true;
12110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012111
12112 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012113 app.curSchedGroup = schedGroup;
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012115 return adj;
12116 }
12117
12118 /**
12119 * Ask a given process to GC right now.
12120 */
12121 final void performAppGcLocked(ProcessRecord app) {
12122 try {
12123 app.lastRequestedGc = SystemClock.uptimeMillis();
12124 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012125 if (app.reportLowMemory) {
12126 app.reportLowMemory = false;
12127 app.thread.scheduleLowMemory();
12128 } else {
12129 app.thread.processInBackground();
12130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012131 }
12132 } catch (Exception e) {
12133 // whatever.
12134 }
12135 }
12136
12137 /**
12138 * Returns true if things are idle enough to perform GCs.
12139 */
Josh Bartel7f208742010-02-25 11:01:44 -060012140 private final boolean canGcNowLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012141 return mParallelBroadcasts.size() == 0
12142 && mOrderedBroadcasts.size() == 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012143 && (mSleeping || (mMainStack.mResumedActivity != null &&
12144 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012145 }
12146
12147 /**
12148 * Perform GCs on all processes that are waiting for it, but only
12149 * if things are idle.
12150 */
12151 final void performAppGcsLocked() {
12152 final int N = mProcessesToGc.size();
12153 if (N <= 0) {
12154 return;
12155 }
Josh Bartel7f208742010-02-25 11:01:44 -060012156 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012157 while (mProcessesToGc.size() > 0) {
12158 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012159 if (proc.curRawAdj > PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012160 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
12161 <= SystemClock.uptimeMillis()) {
12162 // To avoid spamming the system, we will GC processes one
12163 // at a time, waiting a few seconds between each.
12164 performAppGcLocked(proc);
12165 scheduleAppGcsLocked();
12166 return;
12167 } else {
12168 // It hasn't been long enough since we last GCed this
12169 // process... put it in the list to wait for its time.
12170 addProcessToGcListLocked(proc);
12171 break;
12172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012173 }
12174 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012175
12176 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012177 }
12178 }
12179
12180 /**
12181 * If all looks good, perform GCs on all processes waiting for them.
12182 */
12183 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060012184 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012185 performAppGcsLocked();
12186 return;
12187 }
12188 // Still not idle, wait some more.
12189 scheduleAppGcsLocked();
12190 }
12191
12192 /**
12193 * Schedule the execution of all pending app GCs.
12194 */
12195 final void scheduleAppGcsLocked() {
12196 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012197
12198 if (mProcessesToGc.size() > 0) {
12199 // Schedule a GC for the time to the next process.
12200 ProcessRecord proc = mProcessesToGc.get(0);
12201 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
12202
12203 long when = mProcessesToGc.get(0).lastRequestedGc + GC_MIN_INTERVAL;
12204 long now = SystemClock.uptimeMillis();
12205 if (when < (now+GC_TIMEOUT)) {
12206 when = now + GC_TIMEOUT;
12207 }
12208 mHandler.sendMessageAtTime(msg, when);
12209 }
12210 }
12211
12212 /**
12213 * Add a process to the array of processes waiting to be GCed. Keeps the
12214 * list in sorted order by the last GC time. The process can't already be
12215 * on the list.
12216 */
12217 final void addProcessToGcListLocked(ProcessRecord proc) {
12218 boolean added = false;
12219 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
12220 if (mProcessesToGc.get(i).lastRequestedGc <
12221 proc.lastRequestedGc) {
12222 added = true;
12223 mProcessesToGc.add(i+1, proc);
12224 break;
12225 }
12226 }
12227 if (!added) {
12228 mProcessesToGc.add(0, proc);
12229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012230 }
12231
12232 /**
12233 * Set up to ask a process to GC itself. This will either do it
12234 * immediately, or put it on the list of processes to gc the next
12235 * time things are idle.
12236 */
12237 final void scheduleAppGcLocked(ProcessRecord app) {
12238 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012239 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012240 return;
12241 }
12242 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012243 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012244 scheduleAppGcsLocked();
12245 }
12246 }
12247
Dianne Hackborn287952c2010-09-22 22:34:31 -070012248 final void checkExcessivePowerUsageLocked(boolean doKills) {
12249 updateCpuStatsNow();
12250
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012251 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012252 boolean doWakeKills = doKills;
12253 boolean doCpuKills = doKills;
12254 if (mLastPowerCheckRealtime == 0) {
12255 doWakeKills = false;
12256 }
12257 if (mLastPowerCheckUptime == 0) {
12258 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012259 }
12260 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012261 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012262 }
12263 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012264 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
12265 final long curUptime = SystemClock.uptimeMillis();
12266 final long uptimeSince = curUptime - mLastPowerCheckUptime;
12267 mLastPowerCheckRealtime = curRealtime;
12268 mLastPowerCheckUptime = curUptime;
12269 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
12270 doWakeKills = false;
12271 }
12272 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
12273 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012274 }
12275 int i = mLruProcesses.size();
12276 while (i > 0) {
12277 i--;
12278 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012279 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012280 long wtime;
12281 synchronized (stats) {
12282 wtime = stats.getProcessWakeTime(app.info.uid,
12283 app.pid, curRealtime);
12284 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012285 long wtimeUsed = wtime - app.lastWakeTime;
12286 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
12287 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012288 StringBuilder sb = new StringBuilder(128);
12289 sb.append("Wake for ");
12290 app.toShortString(sb);
12291 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012292 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012293 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012294 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012295 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012296 sb.append((wtimeUsed*100)/realtimeSince);
12297 sb.append("%)");
12298 Slog.i(TAG, sb.toString());
12299 sb.setLength(0);
12300 sb.append("CPU for ");
12301 app.toShortString(sb);
12302 sb.append(": over ");
12303 TimeUtils.formatDuration(uptimeSince, sb);
12304 sb.append(" used ");
12305 TimeUtils.formatDuration(cputimeUsed, sb);
12306 sb.append(" (");
12307 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012308 sb.append("%)");
12309 Slog.i(TAG, sb.toString());
12310 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012311 // If a process has held a wake lock for more
12312 // than 50% of the time during this period,
12313 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070012314 if (doWakeKills && realtimeSince > 0
12315 && ((wtimeUsed*100)/realtimeSince) >= 50) {
12316 synchronized (stats) {
12317 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
12318 realtimeSince, wtimeUsed);
12319 }
12320 Slog.w(TAG, "Excessive wake lock in " + app.processName
12321 + " (pid " + app.pid + "): held " + wtimeUsed
12322 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012323 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12324 app.processName, app.setAdj, "excessive wake lock");
12325 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012326 } else if (doCpuKills && uptimeSince > 0
12327 && ((cputimeUsed*100)/uptimeSince) >= 50) {
12328 synchronized (stats) {
12329 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
12330 uptimeSince, cputimeUsed);
12331 }
12332 Slog.w(TAG, "Excessive CPU in " + app.processName
12333 + " (pid " + app.pid + "): used " + cputimeUsed
12334 + " during " + uptimeSince);
12335 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12336 app.processName, app.setAdj, "excessive cpu");
12337 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012338 } else {
12339 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012340 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012341 }
12342 }
12343 }
12344 }
12345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012346 private final boolean updateOomAdjLocked(
12347 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP) {
12348 app.hiddenAdj = hiddenAdj;
12349
12350 if (app.thread == null) {
12351 return true;
12352 }
12353
Dianne Hackborn287952c2010-09-22 22:34:31 -070012354 final boolean wasKeeping = app.keeping;
12355
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012356 int adj = computeOomAdjLocked(app, hiddenAdj, TOP_APP, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012357
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012358 if ((app.pid != 0 && app.pid != MY_PID) || Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012359 if (app.curRawAdj != app.setRawAdj) {
12360 if (app.curRawAdj > FOREGROUND_APP_ADJ
12361 && app.setRawAdj <= FOREGROUND_APP_ADJ) {
12362 // If this app is transitioning from foreground to
12363 // non-foreground, have it do a gc.
12364 scheduleAppGcLocked(app);
12365 } else if (app.curRawAdj >= HIDDEN_APP_MIN_ADJ
12366 && app.setRawAdj < HIDDEN_APP_MIN_ADJ) {
12367 // Likewise do a gc when an app is moving in to the
12368 // background (such as a service stopping).
12369 scheduleAppGcLocked(app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012370 }
12371
12372 if (wasKeeping && !app.keeping) {
12373 // This app is no longer something we want to keep. Note
12374 // its current wake lock time to later know to kill it if
12375 // it is not behaving well.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012376 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12377 synchronized (stats) {
12378 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
12379 app.pid, SystemClock.elapsedRealtime());
12380 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012381 app.lastCpuTime = app.curCpuTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012382 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012384 app.setRawAdj = app.curRawAdj;
12385 }
12386 if (adj != app.setAdj) {
12387 if (Process.setOomAdj(app.pid, adj)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012388 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012389 TAG, "Set app " + app.processName +
12390 " oom adj to " + adj);
12391 app.setAdj = adj;
12392 } else {
12393 return false;
12394 }
12395 }
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012396 if (app.setSchedGroup != app.curSchedGroup) {
12397 app.setSchedGroup = app.curSchedGroup;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012398 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012399 "Setting process group of " + app.processName
12400 + " to " + app.curSchedGroup);
12401 if (true) {
San Mehat9438de22009-06-10 09:11:28 -070012402 long oldId = Binder.clearCallingIdentity();
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012403 try {
12404 Process.setProcessGroup(app.pid, app.curSchedGroup);
12405 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012406 Slog.w(TAG, "Failed setting process group of " + app.pid
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012407 + " to " + app.curSchedGroup);
San Mehat9438de22009-06-10 09:11:28 -070012408 e.printStackTrace();
12409 } finally {
12410 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012411 }
12412 }
12413 if (false) {
12414 if (app.thread != null) {
12415 try {
12416 app.thread.setSchedulingGroup(app.curSchedGroup);
12417 } catch (RemoteException e) {
12418 }
12419 }
12420 }
12421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012422 }
12423
12424 return true;
12425 }
12426
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012427 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012428 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012429 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012430 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012431 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012432 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012433 }
12434 }
12435 return resumedActivity;
12436 }
12437
12438 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012439 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012440 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12441 int curAdj = app.curAdj;
12442 final boolean wasHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
12443 && app.curAdj <= HIDDEN_APP_MAX_ADJ;
12444
12445 mAdjSeq++;
12446
12447 final boolean res = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP);
12448 if (res) {
12449 final boolean nowHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
12450 && app.curAdj <= HIDDEN_APP_MAX_ADJ;
12451 if (nowHidden != wasHidden) {
12452 // Changed to/from hidden state, so apps after it in the LRU
12453 // list may also be changed.
12454 updateOomAdjLocked();
12455 }
12456 }
12457 return res;
12458 }
12459
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012460 final boolean updateOomAdjLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012461 boolean didOomAdj = true;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012462 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012463 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12464
12465 if (false) {
12466 RuntimeException e = new RuntimeException();
12467 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012468 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012469 }
12470
12471 mAdjSeq++;
12472
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012473 // Let's determine how many processes we have running vs.
12474 // how many slots we have for background processes; we may want
12475 // to put multiple processes in a slot of there are enough of
12476 // them.
12477 int numSlots = HIDDEN_APP_MAX_ADJ - HIDDEN_APP_MIN_ADJ + 1;
12478 int factor = (mLruProcesses.size()-4)/numSlots;
12479 if (factor < 1) factor = 1;
12480 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070012481 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012483 // First try updating the OOM adjustment for each of the
12484 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012485 int i = mLruProcesses.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012486 int curHiddenAdj = HIDDEN_APP_MIN_ADJ;
12487 while (i > 0) {
12488 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012489 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012490 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012491 if (updateOomAdjLocked(app, curHiddenAdj, TOP_APP)) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012492 if (curHiddenAdj < EMPTY_APP_ADJ
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012493 && app.curAdj == curHiddenAdj) {
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012494 step++;
12495 if (step >= factor) {
12496 step = 0;
12497 curHiddenAdj++;
12498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012499 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070012500 if (app.curAdj >= HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn149427c2010-04-23 14:20:03 -070012501 if (!app.killedBackground) {
12502 numHidden++;
12503 if (numHidden > MAX_HIDDEN_APPS) {
Dianne Hackborn906497c2010-05-10 15:57:38 -070012504 Slog.i(TAG, "No longer want " + app.processName
12505 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackborn149427c2010-04-23 14:20:03 -070012506 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12507 app.processName, app.setAdj, "too many background");
12508 app.killedBackground = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -070012509 Process.killProcessQuiet(app.pid);
Dianne Hackborn149427c2010-04-23 14:20:03 -070012510 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070012511 }
12512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012513 } else {
12514 didOomAdj = false;
12515 }
12516 }
12517
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012518 // If we return false, we will fall back on killing processes to
12519 // have a fixed limit. Do this if a limit has been requested; else
12520 // only return false if one of the adjustments failed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012521 return ENFORCE_PROCESS_LIMIT || mProcessLimit > 0 ? false : didOomAdj;
12522 }
12523
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012524 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012525 synchronized (this) {
12526 int i;
12527
12528 // First remove any unused application processes whose package
12529 // has been removed.
12530 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
12531 final ProcessRecord app = mRemovedProcesses.get(i);
12532 if (app.activities.size() == 0
12533 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012534 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012535 TAG, "Exiting empty application process "
12536 + app.processName + " ("
12537 + (app.thread != null ? app.thread.asBinder() : null)
12538 + ")\n");
12539 if (app.pid > 0 && app.pid != MY_PID) {
12540 Process.killProcess(app.pid);
12541 } else {
12542 try {
12543 app.thread.scheduleExit();
12544 } catch (Exception e) {
12545 // Ignore exceptions.
12546 }
12547 }
12548 cleanUpApplicationRecordLocked(app, false, -1);
12549 mRemovedProcesses.remove(i);
12550
12551 if (app.persistent) {
12552 if (app.persistent) {
12553 addAppLocked(app.info);
12554 }
12555 }
12556 }
12557 }
12558
12559 // Now try updating the OOM adjustment for each of the
12560 // application processes based on their current state.
12561 // If the setOomAdj() API is not supported, then go with our
12562 // back-up plan...
12563 if (!updateOomAdjLocked()) {
12564
12565 // Count how many processes are running services.
12566 int numServiceProcs = 0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012567 for (i=mLruProcesses.size()-1; i>=0; i--) {
12568 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012569
12570 if (app.persistent || app.services.size() != 0
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -070012571 || app.curReceiver != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012572 // Don't count processes holding services against our
12573 // maximum process count.
Joe Onorato8a9b2202010-02-26 18:56:32 -080012574 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012575 TAG, "Not trimming app " + app + " with services: "
12576 + app.services);
12577 numServiceProcs++;
12578 }
12579 }
12580
12581 int curMaxProcs = mProcessLimit;
12582 if (curMaxProcs <= 0) curMaxProcs = MAX_PROCESSES;
12583 if (mAlwaysFinishActivities) {
12584 curMaxProcs = 1;
12585 }
12586 curMaxProcs += numServiceProcs;
12587
12588 // Quit as many processes as we can to get down to the desired
12589 // process count. First remove any processes that no longer
12590 // have activites running in them.
12591 for ( i=0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012592 i<mLruProcesses.size()
12593 && mLruProcesses.size() > curMaxProcs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012594 i++) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012595 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012596 // Quit an application only if it is not currently
12597 // running any activities.
12598 if (!app.persistent && app.activities.size() == 0
12599 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012600 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012601 TAG, "Exiting empty application process "
12602 + app.processName + " ("
12603 + (app.thread != null ? app.thread.asBinder() : null)
12604 + ")\n");
12605 if (app.pid > 0 && app.pid != MY_PID) {
12606 Process.killProcess(app.pid);
12607 } else {
12608 try {
12609 app.thread.scheduleExit();
12610 } catch (Exception e) {
12611 // Ignore exceptions.
12612 }
12613 }
12614 // todo: For now we assume the application is not buggy
12615 // or evil, and will quit as a result of our request.
12616 // Eventually we need to drive this off of the death
12617 // notification, and kill the process if it takes too long.
12618 cleanUpApplicationRecordLocked(app, false, i);
12619 i--;
12620 }
12621 }
12622
12623 // If we still have too many processes, now from the least
12624 // recently used process we start finishing activities.
Joe Onorato8a9b2202010-02-26 18:56:32 -080012625 if (Config.LOGV) Slog.v(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012626 TAG, "*** NOW HAVE " + mLruProcesses.size() +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012627 " of " + curMaxProcs + " processes");
12628 for ( i=0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012629 i<mLruProcesses.size()
12630 && mLruProcesses.size() > curMaxProcs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012631 i++) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012632 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012633 // Quit the application only if we have a state saved for
12634 // all of its activities.
12635 boolean canQuit = !app.persistent && app.curReceiver == null
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -070012636 && app.services.size() == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012637 int NUMA = app.activities.size();
12638 int j;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012639 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012640 TAG, "Looking to quit " + app.processName);
12641 for (j=0; j<NUMA && canQuit; j++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012642 ActivityRecord r = app.activities.get(j);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012643 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012644 TAG, " " + r.intent.getComponent().flattenToShortString()
12645 + ": frozen=" + r.haveState + ", visible=" + r.visible);
12646 canQuit = (r.haveState || !r.stateNotNeeded)
12647 && !r.visible && r.stopped;
12648 }
12649 if (canQuit) {
12650 // Finish all of the activities, and then the app itself.
12651 for (j=0; j<NUMA; j++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012652 ActivityRecord r = app.activities.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012653 if (!r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012654 r.stack.destroyActivityLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012655 }
12656 r.resultTo = null;
12657 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080012658 Slog.i(TAG, "Exiting application process "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012659 + app.processName + " ("
12660 + (app.thread != null ? app.thread.asBinder() : null)
12661 + ")\n");
12662 if (app.pid > 0 && app.pid != MY_PID) {
12663 Process.killProcess(app.pid);
12664 } else {
12665 try {
12666 app.thread.scheduleExit();
12667 } catch (Exception e) {
12668 // Ignore exceptions.
12669 }
12670 }
12671 // todo: For now we assume the application is not buggy
12672 // or evil, and will quit as a result of our request.
12673 // Eventually we need to drive this off of the death
12674 // notification, and kill the process if it takes too long.
12675 cleanUpApplicationRecordLocked(app, false, i);
12676 i--;
12677 //dump();
12678 }
12679 }
12680
12681 }
12682
12683 int curMaxActivities = MAX_ACTIVITIES;
12684 if (mAlwaysFinishActivities) {
12685 curMaxActivities = 1;
12686 }
12687
12688 // Finally, if there are too many activities now running, try to
12689 // finish as many as we can to get back down to the limit.
12690 for ( i=0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012691 i<mMainStack.mLRUActivities.size()
12692 && mMainStack.mLRUActivities.size() > curMaxActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012693 i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012694 final ActivityRecord r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012695 = (ActivityRecord)mMainStack.mLRUActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012696
12697 // We can finish this one if we have its icicle saved and
12698 // it is not persistent.
12699 if ((r.haveState || !r.stateNotNeeded) && !r.visible
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -070012700 && r.stopped && !r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012701 final int origSize = mMainStack.mLRUActivities.size();
12702 r.stack.destroyActivityLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012703
12704 // This will remove it from the LRU list, so keep
12705 // our index at the same value. Note that this check to
12706 // see if the size changes is just paranoia -- if
12707 // something unexpected happens, we don't want to end up
12708 // in an infinite loop.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012709 if (origSize > mMainStack.mLRUActivities.size()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012710 i--;
12711 }
12712 }
12713 }
12714 }
12715 }
12716
12717 /** This method sends the specified signal to each of the persistent apps */
12718 public void signalPersistentProcesses(int sig) throws RemoteException {
12719 if (sig != Process.SIGNAL_USR1) {
12720 throw new SecurityException("Only SIGNAL_USR1 is allowed");
12721 }
12722
12723 synchronized (this) {
12724 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
12725 != PackageManager.PERMISSION_GRANTED) {
12726 throw new SecurityException("Requires permission "
12727 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
12728 }
12729
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012730 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12731 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012732 if (r.thread != null && r.persistent) {
12733 Process.sendSignal(r.pid, sig);
12734 }
12735 }
12736 }
12737 }
12738
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012739 public boolean profileControl(String process, boolean start,
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012740 String path, ParcelFileDescriptor fd) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012741
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012742 try {
12743 synchronized (this) {
12744 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
12745 // its own permission.
12746 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
12747 != PackageManager.PERMISSION_GRANTED) {
12748 throw new SecurityException("Requires permission "
12749 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012750 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012751
12752 if (start && fd == null) {
12753 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012754 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012755
12756 ProcessRecord proc = null;
12757 try {
12758 int pid = Integer.parseInt(process);
12759 synchronized (mPidsSelfLocked) {
12760 proc = mPidsSelfLocked.get(pid);
12761 }
12762 } catch (NumberFormatException e) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012763 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012764
12765 if (proc == null) {
12766 HashMap<String, SparseArray<ProcessRecord>> all
12767 = mProcessNames.getMap();
12768 SparseArray<ProcessRecord> procs = all.get(process);
12769 if (procs != null && procs.size() > 0) {
12770 proc = procs.valueAt(0);
12771 }
12772 }
12773
12774 if (proc == null || proc.thread == null) {
12775 throw new IllegalArgumentException("Unknown process: " + process);
12776 }
12777
12778 boolean isSecure = "1".equals(SystemProperties.get(SYSTEM_SECURE, "0"));
12779 if (isSecure) {
12780 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
12781 throw new SecurityException("Process not debuggable: " + proc);
12782 }
12783 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012784
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012785 proc.thread.profilerControl(start, path, fd);
12786 fd = null;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012787 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012788 }
12789 } catch (RemoteException e) {
12790 throw new IllegalStateException("Process disappeared");
12791 } finally {
12792 if (fd != null) {
12793 try {
12794 fd.close();
12795 } catch (IOException e) {
12796 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012797 }
12798 }
12799 }
Andy McFadden824c5102010-07-09 16:26:57 -070012800
12801 public boolean dumpHeap(String process, boolean managed,
12802 String path, ParcelFileDescriptor fd) throws RemoteException {
12803
12804 try {
12805 synchronized (this) {
12806 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
12807 // its own permission (same as profileControl).
12808 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
12809 != PackageManager.PERMISSION_GRANTED) {
12810 throw new SecurityException("Requires permission "
12811 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
12812 }
12813
12814 if (fd == null) {
12815 throw new IllegalArgumentException("null fd");
12816 }
12817
12818 ProcessRecord proc = null;
12819 try {
12820 int pid = Integer.parseInt(process);
12821 synchronized (mPidsSelfLocked) {
12822 proc = mPidsSelfLocked.get(pid);
12823 }
12824 } catch (NumberFormatException e) {
12825 }
12826
12827 if (proc == null) {
12828 HashMap<String, SparseArray<ProcessRecord>> all
12829 = mProcessNames.getMap();
12830 SparseArray<ProcessRecord> procs = all.get(process);
12831 if (procs != null && procs.size() > 0) {
12832 proc = procs.valueAt(0);
12833 }
12834 }
12835
12836 if (proc == null || proc.thread == null) {
12837 throw new IllegalArgumentException("Unknown process: " + process);
12838 }
12839
12840 boolean isSecure = "1".equals(SystemProperties.get(SYSTEM_SECURE, "0"));
12841 if (isSecure) {
12842 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
12843 throw new SecurityException("Process not debuggable: " + proc);
12844 }
12845 }
12846
12847 proc.thread.dumpHeap(managed, path, fd);
12848 fd = null;
12849 return true;
12850 }
12851 } catch (RemoteException e) {
12852 throw new IllegalStateException("Process disappeared");
12853 } finally {
12854 if (fd != null) {
12855 try {
12856 fd.close();
12857 } catch (IOException e) {
12858 }
12859 }
12860 }
12861 }
12862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012863 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
12864 public void monitor() {
12865 synchronized (this) { }
12866 }
12867}