blob: 1bfdcae7660dd454639a33180cefdc50869a378e [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 // Remove any existing entries that are the same kind of task.
2318 int N = mRecentTasks.size();
2319 for (int i=0; i<N; i++) {
2320 TaskRecord tr = mRecentTasks.get(i);
2321 if ((task.affinity != null && task.affinity.equals(tr.affinity))
2322 || (task.intent != null && task.intent.filterEquals(tr.intent))) {
2323 mRecentTasks.remove(i);
2324 i--;
2325 N--;
2326 if (task.intent == null) {
2327 // If the new recent task we are adding is not fully
2328 // specified, then replace it with the existing recent task.
2329 task = tr;
2330 }
2331 }
2332 }
2333 if (N >= MAX_RECENT_TASKS) {
2334 mRecentTasks.remove(N-1);
2335 }
2336 mRecentTasks.add(0, task);
2337 }
2338
2339 public void setRequestedOrientation(IBinder token,
2340 int requestedOrientation) {
2341 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002342 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 if (index < 0) {
2344 return;
2345 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002346 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 final long origId = Binder.clearCallingIdentity();
2348 mWindowManager.setAppOrientation(r, requestedOrientation);
2349 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002350 mConfiguration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 r.mayFreezeScreenLocked(r.app) ? r : null);
2352 if (config != null) {
2353 r.frozenBeforeDestroy = true;
2354 if (!updateConfigurationLocked(config, r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002355 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 }
2357 }
2358 Binder.restoreCallingIdentity(origId);
2359 }
2360 }
2361
2362 public int getRequestedOrientation(IBinder token) {
2363 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002364 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 if (index < 0) {
2366 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2367 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002368 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 return mWindowManager.getAppOrientation(r);
2370 }
2371 }
2372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 /**
2374 * This is the internal entry point for handling Activity.finish().
2375 *
2376 * @param token The Binder token referencing the Activity we want to finish.
2377 * @param resultCode Result code, if any, from this Activity.
2378 * @param resultData Result data (Intent), if any, from this Activity.
2379 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002380 * @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 -08002381 */
2382 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2383 // Refuse possible leaked file descriptors
2384 if (resultData != null && resultData.hasFileDescriptors() == true) {
2385 throw new IllegalArgumentException("File descriptors passed in Intent");
2386 }
2387
2388 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002389 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002391 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 if (next != null) {
2393 // ask watcher if this is allowed
2394 boolean resumeOK = true;
2395 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002396 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002398 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399 }
2400
2401 if (!resumeOK) {
2402 return false;
2403 }
2404 }
2405 }
2406 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002407 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 resultData, "app-request");
2409 Binder.restoreCallingIdentity(origId);
2410 return res;
2411 }
2412 }
2413
Dianne Hackborn860755f2010-06-03 18:47:52 -07002414 public final void finishHeavyWeightApp() {
2415 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2416 != PackageManager.PERMISSION_GRANTED) {
2417 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2418 + Binder.getCallingPid()
2419 + ", uid=" + Binder.getCallingUid()
2420 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2421 Slog.w(TAG, msg);
2422 throw new SecurityException(msg);
2423 }
2424
2425 synchronized(this) {
2426 if (mHeavyWeightProcess == null) {
2427 return;
2428 }
2429
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002430 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002431 mHeavyWeightProcess.activities);
2432 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002433 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002434 if (!r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002435 int index = mMainStack.indexOfTokenLocked(r);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002436 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002437 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002438 null, "finish-heavy");
2439 }
2440 }
2441 }
2442
2443 mHeavyWeightProcess = null;
2444 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2445 }
2446 }
2447
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002448 public void crashApplication(int uid, int initialPid, String packageName,
2449 String message) {
2450 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2451 != PackageManager.PERMISSION_GRANTED) {
2452 String msg = "Permission Denial: crashApplication() from pid="
2453 + Binder.getCallingPid()
2454 + ", uid=" + Binder.getCallingUid()
2455 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2456 Slog.w(TAG, msg);
2457 throw new SecurityException(msg);
2458 }
2459
2460 synchronized(this) {
2461 ProcessRecord proc = null;
2462
2463 // Figure out which process to kill. We don't trust that initialPid
2464 // still has any relation to current pids, so must scan through the
2465 // list.
2466 synchronized (mPidsSelfLocked) {
2467 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2468 ProcessRecord p = mPidsSelfLocked.valueAt(i);
2469 if (p.info.uid != uid) {
2470 continue;
2471 }
2472 if (p.pid == initialPid) {
2473 proc = p;
2474 break;
2475 }
2476 for (String str : p.pkgList) {
2477 if (str.equals(packageName)) {
2478 proc = p;
2479 }
2480 }
2481 }
2482 }
2483
2484 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002485 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002486 + " initialPid=" + initialPid
2487 + " packageName=" + packageName);
2488 return;
2489 }
2490
2491 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002492 if (proc.pid == Process.myPid()) {
2493 Log.w(TAG, "crashApplication: trying to crash self!");
2494 return;
2495 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002496 long ident = Binder.clearCallingIdentity();
2497 try {
2498 proc.thread.scheduleCrash(message);
2499 } catch (RemoteException e) {
2500 }
2501 Binder.restoreCallingIdentity(ident);
2502 }
2503 }
2504 }
2505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 public final void finishSubActivity(IBinder token, String resultWho,
2507 int requestCode) {
2508 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002509 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 if (index < 0) {
2511 return;
2512 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002513 ActivityRecord self = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514
2515 final long origId = Binder.clearCallingIdentity();
2516
2517 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002518 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2519 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 if (r.resultTo == self && r.requestCode == requestCode) {
2521 if ((r.resultWho == null && resultWho == null) ||
2522 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002523 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 Activity.RESULT_CANCELED, null, "request-sub");
2525 }
2526 }
2527 }
2528
2529 Binder.restoreCallingIdentity(origId);
2530 }
2531 }
2532
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002533 public boolean willActivityBeVisible(IBinder token) {
2534 synchronized(this) {
2535 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002536 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2537 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002538 if (r == token) {
2539 return true;
2540 }
2541 if (r.fullscreen && !r.finishing) {
2542 return false;
2543 }
2544 }
2545 return true;
2546 }
2547 }
2548
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002549 public void overridePendingTransition(IBinder token, String packageName,
2550 int enterAnim, int exitAnim) {
2551 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002552 int index = mMainStack.indexOfTokenLocked(token);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002553 if (index < 0) {
2554 return;
2555 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002556 ActivityRecord self = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002557
2558 final long origId = Binder.clearCallingIdentity();
2559
2560 if (self.state == ActivityState.RESUMED
2561 || self.state == ActivityState.PAUSING) {
2562 mWindowManager.overridePendingAppTransition(packageName,
2563 enterAnim, exitAnim);
2564 }
2565
2566 Binder.restoreCallingIdentity(origId);
2567 }
2568 }
2569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 * Main function for removing an existing process from the activity manager
2572 * as a result of that process going away. Clears out all connections
2573 * to the process.
2574 */
2575 private final void handleAppDiedLocked(ProcessRecord app,
2576 boolean restarting) {
2577 cleanUpApplicationRecordLocked(app, restarting, -1);
2578 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002579 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 }
2581
2582 // Just in case...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002583 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2584 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2585 mMainStack.mPausingActivity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002587 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2588 mMainStack.mLastPausedActivity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 }
2590
2591 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002592 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593
2594 boolean atTop = true;
2595 boolean hasVisibleActivities = false;
2596
2597 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002598 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002599 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 TAG, "Removing app " + app + " from history with " + i + " entries");
2601 while (i > 0) {
2602 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002603 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002604 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2606 if (r.app == app) {
2607 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002608 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 TAG, "Removing this entry! frozen=" + r.haveState
2610 + " finishing=" + r.finishing);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002611 mMainStack.mHistory.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612
2613 r.inHistory = false;
2614 mWindowManager.removeAppToken(r);
2615 if (VALIDATE_TOKENS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002616 mWindowManager.validateAppTokens(mMainStack.mHistory);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002618 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619
2620 } else {
2621 // We have the current state for this activity, so
2622 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002623 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 TAG, "Keeping entry, setting app to null");
2625 if (r.visible) {
2626 hasVisibleActivities = true;
2627 }
2628 r.app = null;
2629 r.nowVisible = false;
2630 if (!r.haveState) {
2631 r.icicle = null;
2632 }
2633 }
2634
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002635 r.stack.cleanUpActivityLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 r.state = ActivityState.STOPPED;
2637 }
2638 atTop = false;
2639 }
2640
2641 app.activities.clear();
2642
2643 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002644 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 + " running instrumentation " + app.instrumentationClass);
2646 Bundle info = new Bundle();
2647 info.putString("shortMsg", "Process crashed.");
2648 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2649 }
2650
2651 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002652 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 // If there was nothing to resume, and we are not already
2654 // restarting this process, but there is a visible activity that
2655 // is hosted by the process... then make sure all visible
2656 // activities are running, taking care of restarting this
2657 // process.
2658 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002659 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 }
2661 }
2662 }
2663 }
2664
2665 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2666 IBinder threadBinder = thread.asBinder();
2667
2668 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002669 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2670 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2672 return i;
2673 }
2674 }
2675 return -1;
2676 }
2677
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002678 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 IApplicationThread thread) {
2680 if (thread == null) {
2681 return null;
2682 }
2683
2684 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002685 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 }
2687
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002688 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 IApplicationThread thread) {
2690
2691 mProcDeaths[0]++;
2692
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002693 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2694 synchronized (stats) {
2695 stats.noteProcessDiedLocked(app.info.uid, pid);
2696 }
2697
Magnus Edlund7bb25812010-02-24 15:45:06 +01002698 // Clean up already done if the process has been re-started.
2699 if (app.pid == pid && app.thread != null &&
2700 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002701 if (!app.killedBackground) {
2702 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2703 + ") has died.");
2704 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002705 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002706 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 TAG, "Dying app: " + app + ", pid: " + pid
2708 + ", thread: " + thread.asBinder());
2709 boolean doLowMem = app.instrumentationClass == null;
2710 handleAppDiedLocked(app, false);
2711
2712 if (doLowMem) {
2713 // If there are no longer any background processes running,
2714 // and the app that died was not running instrumentation,
2715 // then tell everyone we are now low on memory.
2716 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002717 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2718 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 if (rec.thread != null && rec.setAdj >= HIDDEN_APP_MIN_ADJ) {
2720 haveBg = true;
2721 break;
2722 }
2723 }
2724
2725 if (!haveBg) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002726 Slog.i(TAG, "Low Memory: No more background processes.");
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002727 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002728 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002729 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2730 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002731 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002732 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2733 // The low memory report is overriding any current
2734 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002735 // heavy/important/visible/foreground processes first.
2736 if (rec.setAdj <= HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002737 rec.lastRequestedGc = 0;
2738 } else {
2739 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002741 rec.reportLowMemory = true;
2742 rec.lastLowMemory = now;
2743 mProcessesToGc.remove(rec);
2744 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 }
2746 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002747 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 }
2749 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002750 } else if (app.pid != pid) {
2751 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002752 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002753 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002754 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002755 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002756 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 + thread.asBinder());
2758 }
2759 }
2760
Dan Egnor42471dd2010-01-07 17:25:22 -08002761 /**
2762 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002763 * @param clearTraces causes the dump file to be erased prior to the new
2764 * traces being written, if true; when false, the new traces will be
2765 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002766 * @param firstPids of dalvik VM processes to dump stack traces for first
2767 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002768 * @return file containing stack traces, or null if no dump file is configured
2769 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002770 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2771 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002772 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2773 if (tracesPath == null || tracesPath.length() == 0) {
2774 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002776
2777 File tracesFile = new File(tracesPath);
2778 try {
2779 File tracesDir = tracesFile.getParentFile();
2780 if (!tracesDir.exists()) tracesFile.mkdirs();
2781 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2782
Christopher Tate6ee412d2010-05-28 12:01:56 -07002783 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002784 tracesFile.createNewFile();
2785 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2786 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002787 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002788 return null;
2789 }
2790
2791 // Use a FileObserver to detect when traces finish writing.
2792 // The order of traces is considered important to maintain for legibility.
2793 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2794 public synchronized void onEvent(int event, String path) { notify(); }
2795 };
2796
2797 try {
2798 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002799
2800 // First collect all of the stacks of the most important pids.
2801 try {
2802 int num = firstPids.size();
2803 for (int i = 0; i < num; i++) {
2804 synchronized (observer) {
2805 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2806 observer.wait(200); // Wait for write-close, give up after 200msec
2807 }
2808 }
2809 } catch (InterruptedException e) {
2810 Log.wtf(TAG, e);
2811 }
2812
2813 // Next measure CPU usage.
2814 if (processStats != null) {
2815 processStats.init();
2816 System.gc();
2817 processStats.update();
2818 try {
2819 synchronized (processStats) {
2820 processStats.wait(500); // measure over 1/2 second.
2821 }
2822 } catch (InterruptedException e) {
2823 }
2824 processStats.update();
2825
2826 // We'll take the stack crawls of just the top apps using CPU.
2827 final int N = processStats.countWorkingStats();
2828 int numProcs = 0;
2829 for (int i=0; i<N && numProcs<5; i++) {
2830 ProcessStats.Stats stats = processStats.getWorkingStats(i);
2831 if (lastPids.indexOfKey(stats.pid) >= 0) {
2832 numProcs++;
2833 try {
2834 synchronized (observer) {
2835 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
2836 observer.wait(200); // Wait for write-close, give up after 200msec
2837 }
2838 } catch (InterruptedException e) {
2839 Log.wtf(TAG, e);
2840 }
2841
2842 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002843 }
2844 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002845
2846 return tracesFile;
2847
Dan Egnor42471dd2010-01-07 17:25:22 -08002848 } finally {
2849 observer.stopWatching();
2850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 }
2852
Jeff Brown4d94a762010-09-23 11:33:28 -07002853 private final class AppNotResponding implements Runnable {
2854 private final ProcessRecord mApp;
2855 private final String mAnnotation;
2856
2857 public AppNotResponding(ProcessRecord app, String annotation) {
2858 mApp = app;
2859 mAnnotation = annotation;
2860 }
2861
2862 @Override
2863 public void run() {
2864 appNotResponding(mApp, null, null, mAnnotation);
2865 }
2866 }
2867
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002868 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
2869 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002870 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
2871 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
2872
Dianne Hackborn287952c2010-09-22 22:34:31 -07002873 if (mController != null) {
2874 try {
2875 // 0 == continue, -1 = kill process immediately
2876 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
2877 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
2878 } catch (RemoteException e) {
2879 mController = null;
2880 }
2881 }
2882
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002883 long anrTime = SystemClock.uptimeMillis();
2884 if (MONITOR_CPU_USAGE) {
2885 updateCpuStatsNow();
2886 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002887
2888 synchronized (this) {
2889 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
2890 if (mShuttingDown) {
2891 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
2892 return;
2893 } else if (app.notResponding) {
2894 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
2895 return;
2896 } else if (app.crashing) {
2897 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
2898 return;
2899 }
2900
2901 // In case we come through here for the same app before completing
2902 // this one, mark as anring now so we will bail out.
2903 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08002904
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002905 // Log the ANR to the event log.
2906 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
2907 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08002908
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002909 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002910 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002911
2912 int parentPid = app.pid;
2913 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002914 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002915
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002916 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08002917
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002918 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
2919 ProcessRecord r = mLruProcesses.get(i);
2920 if (r != null && r.thread != null) {
2921 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002922 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
2923 if (r.persistent) {
2924 firstPids.add(pid);
2925 } else {
2926 lastPids.put(pid, Boolean.TRUE);
2927 }
2928 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 }
2931 }
2932
Dan Egnor42471dd2010-01-07 17:25:22 -08002933 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002934 StringBuilder info = mStringBuilder;
2935 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08002936 info.append("ANR in ").append(app.processName);
2937 if (activity != null && activity.shortComponentName != null) {
2938 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07002939 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08002940 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08002942 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002944 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08002945 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947
Dianne Hackborn287952c2010-09-22 22:34:31 -07002948 final ProcessStats processStats = new ProcessStats(true);
2949
2950 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
2951
Dan Egnor42471dd2010-01-07 17:25:22 -08002952 String cpuInfo = null;
2953 if (MONITOR_CPU_USAGE) {
2954 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002955 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002956 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002957 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002958 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08002959 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 }
2961
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002962 info.append(processStats.printCurrentState(anrTime));
2963
Joe Onorato8a9b2202010-02-26 18:56:32 -08002964 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08002965 if (tracesFile == null) {
2966 // There is no trace file, so dump (only) the alleged culprit's threads to the log
2967 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
2968 }
2969
2970 addErrorToDropBox("anr", app, activity, parent, annotation, cpuInfo, tracesFile, null);
2971
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002972 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08002974 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
2975 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002977 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
2978 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 }
2980 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002981 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 }
2983 }
2984
Dan Egnor42471dd2010-01-07 17:25:22 -08002985 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
2986 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
2987 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002988
2989 synchronized (this) {
2990 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
2991 Process.killProcess(app.pid);
2992 return;
2993 }
2994
2995 // Set the app's notResponding state, and look up the errorReportReceiver
2996 makeAppNotRespondingLocked(app,
2997 activity != null ? activity.shortComponentName : null,
2998 annotation != null ? "ANR " + annotation : "ANR",
2999 info.toString());
3000
3001 // Bring up the infamous App Not Responding dialog
3002 Message msg = Message.obtain();
3003 HashMap map = new HashMap();
3004 msg.what = SHOW_NOT_RESPONDING_MSG;
3005 msg.obj = map;
3006 map.put("app", app);
3007 if (activity != null) {
3008 map.put("activity", activity);
3009 }
3010
3011 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 }
3014
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003015 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3016 if (!mLaunchWarningShown) {
3017 mLaunchWarningShown = true;
3018 mHandler.post(new Runnable() {
3019 @Override
3020 public void run() {
3021 synchronized (ActivityManagerService.this) {
3022 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3023 d.show();
3024 mHandler.postDelayed(new Runnable() {
3025 @Override
3026 public void run() {
3027 synchronized (ActivityManagerService.this) {
3028 d.dismiss();
3029 mLaunchWarningShown = false;
3030 }
3031 }
3032 }, 4000);
3033 }
3034 }
3035 });
3036 }
3037 }
3038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 public boolean clearApplicationUserData(final String packageName,
3040 final IPackageDataObserver observer) {
3041 int uid = Binder.getCallingUid();
3042 int pid = Binder.getCallingPid();
3043 long callingId = Binder.clearCallingIdentity();
3044 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003045 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 int pkgUid = -1;
3047 synchronized(this) {
3048 try {
3049 pkgUid = pm.getPackageUid(packageName);
3050 } catch (RemoteException e) {
3051 }
3052 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003053 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 return false;
3055 }
3056 if (uid == pkgUid || checkComponentPermission(
3057 android.Manifest.permission.CLEAR_APP_USER_DATA,
3058 pid, uid, -1)
3059 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003060 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 } else {
3062 throw new SecurityException(pid+" does not have permission:"+
3063 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3064 "for process:"+packageName);
3065 }
3066 }
3067
3068 try {
3069 //clear application user data
3070 pm.clearApplicationUserData(packageName, observer);
3071 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3072 Uri.fromParts("package", packageName, null));
3073 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003074 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
3075 null, null, 0, null, null, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 } catch (RemoteException e) {
3077 }
3078 } finally {
3079 Binder.restoreCallingIdentity(callingId);
3080 }
3081 return true;
3082 }
3083
Dianne Hackborn03abb812010-01-04 18:43:19 -08003084 public void killBackgroundProcesses(final String packageName) {
3085 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3086 != PackageManager.PERMISSION_GRANTED &&
3087 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3088 != PackageManager.PERMISSION_GRANTED) {
3089 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 + Binder.getCallingPid()
3091 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003092 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003093 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 throw new SecurityException(msg);
3095 }
3096
3097 long callingId = Binder.clearCallingIdentity();
3098 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003099 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 int pkgUid = -1;
3101 synchronized(this) {
3102 try {
3103 pkgUid = pm.getPackageUid(packageName);
3104 } catch (RemoteException e) {
3105 }
3106 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003107 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 return;
3109 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003110 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003111 SECONDARY_SERVER_ADJ, false, true);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003112 }
3113 } finally {
3114 Binder.restoreCallingIdentity(callingId);
3115 }
3116 }
3117
3118 public void forceStopPackage(final String packageName) {
3119 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3120 != PackageManager.PERMISSION_GRANTED) {
3121 String msg = "Permission Denial: forceStopPackage() from pid="
3122 + Binder.getCallingPid()
3123 + ", uid=" + Binder.getCallingUid()
3124 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003125 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003126 throw new SecurityException(msg);
3127 }
3128
3129 long callingId = Binder.clearCallingIdentity();
3130 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003131 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003132 int pkgUid = -1;
3133 synchronized(this) {
3134 try {
3135 pkgUid = pm.getPackageUid(packageName);
3136 } catch (RemoteException e) {
3137 }
3138 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003139 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003140 return;
3141 }
3142 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 }
3144 } finally {
3145 Binder.restoreCallingIdentity(callingId);
3146 }
3147 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003148
3149 /*
3150 * The pkg name and uid have to be specified.
3151 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3152 */
3153 public void killApplicationWithUid(String pkg, int uid) {
3154 if (pkg == null) {
3155 return;
3156 }
3157 // Make sure the uid is valid.
3158 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003159 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003160 return;
3161 }
3162 int callerUid = Binder.getCallingUid();
3163 // Only the system server can kill an application
3164 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003165 // Post an aysnc message to kill the application
3166 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3167 msg.arg1 = uid;
3168 msg.arg2 = 0;
3169 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003170 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003171 } else {
3172 throw new SecurityException(callerUid + " cannot kill pkg: " +
3173 pkg);
3174 }
3175 }
3176
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003177 public void closeSystemDialogs(String reason) {
3178 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003179 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003180 if (reason != null) {
3181 intent.putExtra("reason", reason);
3182 }
3183
3184 final int uid = Binder.getCallingUid();
3185 final long origId = Binder.clearCallingIdentity();
3186 synchronized (this) {
3187 int i = mWatchers.beginBroadcast();
3188 while (i > 0) {
3189 i--;
3190 IActivityWatcher w = mWatchers.getBroadcastItem(i);
3191 if (w != null) {
3192 try {
3193 w.closingSystemDialogs(reason);
3194 } catch (RemoteException e) {
3195 }
3196 }
3197 }
3198 mWatchers.finishBroadcast();
3199
Dianne Hackbornffa42482009-09-23 22:20:11 -07003200 mWindowManager.closeSystemDialogs(reason);
3201
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003202 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3203 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003204 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003205 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003206 Activity.RESULT_CANCELED, null, "close-sys");
3207 }
3208 }
3209
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003210 broadcastIntentLocked(null, null, intent, null,
3211 null, 0, null, null, null, false, false, -1, uid);
3212 }
3213 Binder.restoreCallingIdentity(origId);
3214 }
3215
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003216 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003217 throws RemoteException {
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003218 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3219 for (int i=pids.length-1; i>=0; i--) {
3220 infos[i] = new Debug.MemoryInfo();
3221 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003222 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003223 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003224 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003225
3226 public void killApplicationProcess(String processName, int uid) {
3227 if (processName == null) {
3228 return;
3229 }
3230
3231 int callerUid = Binder.getCallingUid();
3232 // Only the system server can kill an application
3233 if (callerUid == Process.SYSTEM_UID) {
3234 synchronized (this) {
3235 ProcessRecord app = getProcessRecordLocked(processName, uid);
3236 if (app != null) {
3237 try {
3238 app.thread.scheduleSuicide();
3239 } catch (RemoteException e) {
3240 // If the other end already died, then our work here is done.
3241 }
3242 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003243 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003244 + processName + " / " + uid);
3245 }
3246 }
3247 } else {
3248 throw new SecurityException(callerUid + " cannot kill app process: " +
3249 processName);
3250 }
3251 }
3252
Dianne Hackborn03abb812010-01-04 18:43:19 -08003253 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003254 forceStopPackageLocked(packageName, uid, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3256 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003257 if (!mProcessesReady) {
3258 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 intent.putExtra(Intent.EXTRA_UID, uid);
3261 broadcastIntentLocked(null, null, intent,
3262 null, null, 0, null, null, null,
3263 false, false, MY_PID, Process.SYSTEM_UID);
3264 }
3265
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003266 private final boolean killPackageProcessesLocked(String packageName, int uid,
3267 int minOomAdj, boolean callerWillRestart, boolean doit) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003268 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269
Dianne Hackborn03abb812010-01-04 18:43:19 -08003270 // Remove all processes this package may have touched: all with the
3271 // same UID (except for the system or root user), and all whose name
3272 // matches the package name.
3273 final String procNamePrefix = packageName + ":";
3274 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3275 final int NA = apps.size();
3276 for (int ia=0; ia<NA; ia++) {
3277 ProcessRecord app = apps.valueAt(ia);
3278 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003279 if (doit) {
3280 procs.add(app);
3281 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003282 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3283 || app.processName.equals(packageName)
3284 || app.processName.startsWith(procNamePrefix)) {
3285 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003286 if (!doit) {
3287 return true;
3288 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003289 app.removed = true;
3290 procs.add(app);
3291 }
3292 }
3293 }
3294 }
3295
3296 int N = procs.size();
3297 for (int i=0; i<N; i++) {
3298 removeProcessLocked(procs.get(i), callerWillRestart);
3299 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003300 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003301 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003302
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003303 private final boolean forceStopPackageLocked(String name, int uid,
3304 boolean callerWillRestart, boolean purgeCache, boolean doit) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 int i, N;
3306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 if (uid < 0) {
3308 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003309 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 } catch (RemoteException e) {
3311 }
3312 }
3313
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003314 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003315 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003316
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003317 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3318 while (badApps.hasNext()) {
3319 SparseArray<Long> ba = badApps.next();
3320 if (ba.get(uid) != null) {
3321 badApps.remove();
3322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 }
3324 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003325
3326 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
3327 callerWillRestart, doit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003329 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3330 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 if (r.packageName.equals(name)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003332 if (!doit) {
3333 return true;
3334 }
3335 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003336 Slog.i(TAG, " Force finishing activity " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 if (r.app != null) {
3338 r.app.removed = true;
3339 }
3340 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003341 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "uninstall");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 }
3343 }
3344
3345 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3346 for (ServiceRecord service : mServices.values()) {
3347 if (service.packageName.equals(name)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003348 if (!doit) {
3349 return true;
3350 }
3351 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003352 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 if (service.app != null) {
3354 service.app.removed = true;
3355 }
3356 service.app = null;
3357 services.add(service);
3358 }
3359 }
3360
3361 N = services.size();
3362 for (i=0; i<N; i++) {
3363 bringDownServiceLocked(services.get(i), true);
3364 }
3365
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003366 if (doit) {
3367 if (purgeCache) {
3368 AttributeCache ac = AttributeCache.instance();
3369 if (ac != null) {
3370 ac.removePackage(name);
3371 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003372 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003373 mMainStack.resumeTopActivityLocked(null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003374 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003375
3376 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 }
3378
3379 private final boolean removeProcessLocked(ProcessRecord app, boolean callerWillRestart) {
3380 final String name = app.processName;
3381 final int uid = app.info.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003382 if (DEBUG_PROCESSES) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 TAG, "Force removing process " + app + " (" + name
3384 + "/" + uid + ")");
3385
3386 mProcessNames.remove(name, uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003387 if (mHeavyWeightProcess == app) {
3388 mHeavyWeightProcess = null;
3389 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 boolean needRestart = false;
3392 if (app.pid > 0 && app.pid != MY_PID) {
3393 int pid = app.pid;
3394 synchronized (mPidsSelfLocked) {
3395 mPidsSelfLocked.remove(pid);
3396 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3397 }
3398 handleAppDiedLocked(app, true);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003399 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 Process.killProcess(pid);
3401
3402 if (app.persistent) {
3403 if (!callerWillRestart) {
3404 addAppLocked(app.info);
3405 } else {
3406 needRestart = true;
3407 }
3408 }
3409 } else {
3410 mRemovedProcesses.add(app);
3411 }
3412
3413 return needRestart;
3414 }
3415
3416 private final void processStartTimedOutLocked(ProcessRecord app) {
3417 final int pid = app.pid;
3418 boolean gone = false;
3419 synchronized (mPidsSelfLocked) {
3420 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3421 if (knownApp != null && knownApp.thread == null) {
3422 mPidsSelfLocked.remove(pid);
3423 gone = true;
3424 }
3425 }
3426
3427 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003428 Slog.w(TAG, "Process " + app + " failed to attach");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003429 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.info.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003430 app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003432 if (mHeavyWeightProcess == app) {
3433 mHeavyWeightProcess = null;
3434 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3435 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003436 // Take care of any launching providers waiting for this process.
3437 checkAppInLaunchingProvidersLocked(app, true);
3438 // Take care of any services that are waiting for the process.
3439 for (int i=0; i<mPendingServices.size(); i++) {
3440 ServiceRecord sr = mPendingServices.get(i);
3441 if (app.info.uid == sr.appInfo.uid
3442 && app.processName.equals(sr.processName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003443 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003444 mPendingServices.remove(i);
3445 i--;
3446 bringDownServiceLocked(sr, true);
3447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003449 Process.killProcess(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003450 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003451 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003452 try {
3453 IBackupManager bm = IBackupManager.Stub.asInterface(
3454 ServiceManager.getService(Context.BACKUP_SERVICE));
3455 bm.agentDisconnected(app.info.packageName);
3456 } catch (RemoteException e) {
3457 // Can't happen; the backup manager is local
3458 }
3459 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003460 if (mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003461 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003462 mPendingBroadcast.state = BroadcastRecord.IDLE;
3463 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003464 mPendingBroadcast = null;
3465 scheduleBroadcastsLocked();
3466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003468 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 }
3470 }
3471
3472 private final boolean attachApplicationLocked(IApplicationThread thread,
3473 int pid) {
3474
3475 // Find the application record that is being attached... either via
3476 // the pid if we are running in multiple processes, or just pull the
3477 // next app record if we are emulating process with anonymous threads.
3478 ProcessRecord app;
3479 if (pid != MY_PID && pid >= 0) {
3480 synchronized (mPidsSelfLocked) {
3481 app = mPidsSelfLocked.get(pid);
3482 }
3483 } else if (mStartingProcesses.size() > 0) {
3484 app = mStartingProcesses.remove(0);
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003485 app.setPid(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 } else {
3487 app = null;
3488 }
3489
3490 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003491 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003493 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 if (pid > 0 && pid != MY_PID) {
3495 Process.killProcess(pid);
3496 } else {
3497 try {
3498 thread.scheduleExit();
3499 } catch (Exception e) {
3500 // Ignore exceptions.
3501 }
3502 }
3503 return false;
3504 }
3505
3506 // If this application record is still attached to a previous
3507 // process, clean it up now.
3508 if (app.thread != null) {
3509 handleAppDiedLocked(app, true);
3510 }
3511
3512 // Tell the process all about itself.
3513
Joe Onorato8a9b2202010-02-26 18:56:32 -08003514 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 TAG, "Binding process pid " + pid + " to record " + app);
3516
3517 String processName = app.processName;
3518 try {
3519 thread.asBinder().linkToDeath(new AppDeathRecipient(
3520 app, pid, thread), 0);
3521 } catch (RemoteException e) {
3522 app.resetPackageList();
3523 startProcessLocked(app, "link fail", processName);
3524 return false;
3525 }
3526
Doug Zongker2bec3d42009-12-04 12:52:44 -08003527 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528
3529 app.thread = thread;
3530 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003531 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3532 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 app.forcingToForeground = null;
3534 app.foregroundServices = false;
3535 app.debugging = false;
3536
3537 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3538
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003539 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003540 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003542 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003543 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003544 }
3545
Joe Onorato8a9b2202010-02-26 18:56:32 -08003546 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 TAG, "New app record " + app
3548 + " thread=" + thread.asBinder() + " pid=" + pid);
3549 try {
3550 int testMode = IApplicationThread.DEBUG_OFF;
3551 if (mDebugApp != null && mDebugApp.equals(processName)) {
3552 testMode = mWaitForDebugger
3553 ? IApplicationThread.DEBUG_WAIT
3554 : IApplicationThread.DEBUG_ON;
3555 app.debugging = true;
3556 if (mDebugTransient) {
3557 mDebugApp = mOrigDebugApp;
3558 mWaitForDebugger = mOrigWaitForDebugger;
3559 }
3560 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003561
Christopher Tate181fafa2009-05-14 11:12:14 -07003562 // If the app is being launched for restore or full backup, set it up specially
3563 boolean isRestrictedBackupMode = false;
3564 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3565 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
3566 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3567 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003568
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003569 ensurePackageDexOpt(app.instrumentationInfo != null
3570 ? app.instrumentationInfo.packageName
3571 : app.info.packageName);
3572 if (app.instrumentationClass != null) {
3573 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003574 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003575 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003576 + processName + " with config " + mConfiguration);
Dianne Hackborn1655be42009-05-08 14:29:01 -07003577 thread.bindApplication(processName, app.instrumentationInfo != null
3578 ? app.instrumentationInfo : app.info, providers,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 app.instrumentationClass, app.instrumentationProfileFile,
3580 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003581 isRestrictedBackupMode || !normalMode,
3582 mConfiguration, getCommonServicesLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003583 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003584 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 } catch (Exception e) {
3586 // todo: Yikes! What should we do? For now we will try to
3587 // start another process, but that could easily get us in
3588 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003589 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003590
3591 app.resetPackageList();
3592 startProcessLocked(app, "bind fail", processName);
3593 return false;
3594 }
3595
3596 // Remove this record from the list of starting applications.
3597 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003598 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3599 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600 mProcessesOnHold.remove(app);
3601
3602 boolean badApp = false;
3603 boolean didSomething = false;
3604
3605 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003606 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003607 if (hr != null && normalMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003608 if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
3609 && processName.equals(hr.processName)) {
3610 try {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003611 if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 didSomething = true;
3613 }
3614 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003615 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 + hr.intent.getComponent().flattenToShortString(), e);
3617 badApp = true;
3618 }
3619 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003620 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 }
3622 }
3623
3624 // Find any services that should be running in this process...
3625 if (!badApp && mPendingServices.size() > 0) {
3626 ServiceRecord sr = null;
3627 try {
3628 for (int i=0; i<mPendingServices.size(); i++) {
3629 sr = mPendingServices.get(i);
3630 if (app.info.uid != sr.appInfo.uid
3631 || !processName.equals(sr.processName)) {
3632 continue;
3633 }
3634
3635 mPendingServices.remove(i);
3636 i--;
3637 realStartServiceLocked(sr, app);
3638 didSomething = true;
3639 }
3640 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003641 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 + sr.shortName, e);
3643 badApp = true;
3644 }
3645 }
3646
3647 // Check if the next broadcast receiver is in this process...
3648 BroadcastRecord br = mPendingBroadcast;
3649 if (!badApp && br != null && br.curApp == app) {
3650 try {
3651 mPendingBroadcast = null;
3652 processCurBroadcastLocked(br, app);
3653 didSomething = true;
3654 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003655 Slog.w(TAG, "Exception in new application when starting receiver "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 + br.curComponent.flattenToShortString(), e);
3657 badApp = true;
Jeff Brown4d94a762010-09-23 11:33:28 -07003658 logBroadcastReceiverDiscardLocked(br);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 finishReceiverLocked(br.receiver, br.resultCode, br.resultData,
3660 br.resultExtras, br.resultAbort, true);
3661 scheduleBroadcastsLocked();
Magnus Edlund7bb25812010-02-24 15:45:06 +01003662 // We need to reset the state if we fails to start the receiver.
3663 br.state = BroadcastRecord.IDLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 }
3665 }
3666
Christopher Tate181fafa2009-05-14 11:12:14 -07003667 // Check whether the next backup agent is in this process...
3668 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.info.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003669 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003670 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003671 try {
3672 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, mBackupTarget.backupMode);
3673 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003674 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003675 e.printStackTrace();
3676 }
3677 }
3678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 if (badApp) {
3680 // todo: Also need to kill application to deal with all
3681 // kinds of exceptions.
3682 handleAppDiedLocked(app, false);
3683 return false;
3684 }
3685
3686 if (!didSomething) {
3687 updateOomAdjLocked();
3688 }
3689
3690 return true;
3691 }
3692
3693 public final void attachApplication(IApplicationThread thread) {
3694 synchronized (this) {
3695 int callingPid = Binder.getCallingPid();
3696 final long origId = Binder.clearCallingIdentity();
3697 attachApplicationLocked(thread, callingPid);
3698 Binder.restoreCallingIdentity(origId);
3699 }
3700 }
3701
Dianne Hackborne88846e2009-09-30 21:34:25 -07003702 public final void activityIdle(IBinder token, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003704 mMainStack.activityIdleInternal(token, false, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 Binder.restoreCallingIdentity(origId);
3706 }
3707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003709 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003710 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003711 mWindowManager.enableScreenAfterBoot();
3712 }
3713
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003714 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003715 IntentFilter pkgFilter = new IntentFilter();
3716 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
3717 pkgFilter.addDataScheme("package");
3718 mContext.registerReceiver(new BroadcastReceiver() {
3719 @Override
3720 public void onReceive(Context context, Intent intent) {
3721 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3722 if (pkgs != null) {
3723 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07003724 synchronized (ActivityManagerService.this) {
3725 if (forceStopPackageLocked(pkg, -1, false, false, false)) {
3726 setResultCode(Activity.RESULT_OK);
3727 return;
3728 }
3729 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003730 }
3731 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003732 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003733 }, pkgFilter);
3734
3735 synchronized (this) {
3736 // Ensure that any processes we had put on hold are now started
3737 // up.
3738 final int NP = mProcessesOnHold.size();
3739 if (NP > 0) {
3740 ArrayList<ProcessRecord> procs =
3741 new ArrayList<ProcessRecord>(mProcessesOnHold);
3742 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003743 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
3744 + procs.get(ip));
3745 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003746 }
3747 }
3748
3749 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003750 // Start looking for apps that are abusing wake locks.
3751 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003752 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003753 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07003754 SystemProperties.set("sys.boot_completed", "1");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003755 broadcastIntentLocked(null, null,
3756 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
3757 null, null, 0, null, null,
3758 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
3759 false, false, MY_PID, Process.SYSTEM_UID);
3760 }
3761 }
3762 }
3763
3764 final void ensureBootCompleted() {
3765 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003766 boolean enableScreen;
3767 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003768 booting = mBooting;
3769 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003770 enableScreen = !mBooted;
3771 mBooted = true;
3772 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003773
3774 if (booting) {
3775 finishBooting();
3776 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003777
3778 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003779 enableScreenAfterBoot();
3780 }
3781 }
3782
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003783 public final void activityPaused(IBinder token) {
3784 final long origId = Binder.clearCallingIdentity();
3785 mMainStack.activityPaused(token, false);
3786 Binder.restoreCallingIdentity(origId);
3787 }
3788
3789 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
3790 CharSequence description) {
3791 if (localLOGV) Slog.v(
3792 TAG, "Activity stopped: token=" + token);
3793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 // Refuse possible leaked file descriptors
3795 if (icicle != null && icicle.hasFileDescriptors()) {
3796 throw new IllegalArgumentException("File descriptors passed in Bundle");
3797 }
3798
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003799 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800
3801 final long origId = Binder.clearCallingIdentity();
3802
3803 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003804 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003806 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003807 r.icicle = icicle;
3808 r.haveState = true;
3809 if (thumbnail != null) {
3810 r.thumbnail = thumbnail;
3811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 r.description = description;
3813 r.stopped = true;
3814 r.state = ActivityState.STOPPED;
3815 if (!r.finishing) {
3816 if (r.configDestroy) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003817 r.stack.destroyActivityLocked(r, true);
3818 r.stack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819 }
3820 }
3821 }
3822 }
3823
3824 if (r != null) {
3825 sendPendingThumbnail(r, null, null, null, false);
3826 }
3827
3828 trimApplications();
3829
3830 Binder.restoreCallingIdentity(origId);
3831 }
3832
3833 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003834 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003835 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 }
3837
3838 public String getCallingPackage(IBinder token) {
3839 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003840 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07003841 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 }
3843 }
3844
3845 public ComponentName getCallingActivity(IBinder token) {
3846 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003847 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003848 return r != null ? r.intent.getComponent() : null;
3849 }
3850 }
3851
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003852 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003853 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003855 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 if (r != null) {
3857 return r.resultTo;
3858 }
3859 }
3860 return null;
3861 }
3862
3863 public ComponentName getActivityClassForToken(IBinder token) {
3864 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003865 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003867 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 return r.intent.getComponent();
3869 }
3870 return null;
3871 }
3872 }
3873
3874 public String getPackageForToken(IBinder token) {
3875 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003876 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003878 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 return r.packageName;
3880 }
3881 return null;
3882 }
3883 }
3884
3885 public IIntentSender getIntentSender(int type,
3886 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003887 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003889 if (intents != null) {
3890 if (intents.length < 1) {
3891 throw new IllegalArgumentException("Intents array length must be >= 1");
3892 }
3893 for (int i=0; i<intents.length; i++) {
3894 Intent intent = intents[i];
3895 if (intent == null) {
3896 throw new IllegalArgumentException("Null intent at index " + i);
3897 }
3898 if (intent.hasFileDescriptors()) {
3899 throw new IllegalArgumentException("File descriptors passed in Intent");
3900 }
3901 if (type == INTENT_SENDER_BROADCAST &&
3902 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
3903 throw new IllegalArgumentException(
3904 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
3905 }
3906 intents[i] = new Intent(intent);
3907 }
3908 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003909 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003910 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003911 }
3912 }
3913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 synchronized(this) {
3915 int callingUid = Binder.getCallingUid();
3916 try {
3917 if (callingUid != 0 && callingUid != Process.SYSTEM_UID &&
3918 Process.supportsProcesses()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003919 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 .getPackageUid(packageName);
3921 if (uid != Binder.getCallingUid()) {
3922 String msg = "Permission Denial: getIntentSender() from pid="
3923 + Binder.getCallingPid()
3924 + ", uid=" + Binder.getCallingUid()
3925 + ", (need uid=" + uid + ")"
3926 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003927 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 throw new SecurityException(msg);
3929 }
3930 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003931
3932 return getIntentSenderLocked(type, packageName, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003933 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 } catch (RemoteException e) {
3936 throw new SecurityException(e);
3937 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003938 }
3939 }
3940
3941 IIntentSender getIntentSenderLocked(int type,
3942 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003943 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003944 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003945 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003946 int index = mMainStack.indexOfTokenLocked(token);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003947 if (index < 0) {
3948 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003950 activity = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003951 if (activity.finishing) {
3952 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003954 }
3955
3956 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
3957 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
3958 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
3959 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
3960 |PendingIntent.FLAG_UPDATE_CURRENT);
3961
3962 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
3963 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003964 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003965 WeakReference<PendingIntentRecord> ref;
3966 ref = mIntentSenderRecords.get(key);
3967 PendingIntentRecord rec = ref != null ? ref.get() : null;
3968 if (rec != null) {
3969 if (!cancelCurrent) {
3970 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003971 if (rec.key.requestIntent != null) {
3972 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
3973 }
3974 if (intents != null) {
3975 intents[intents.length-1] = rec.key.requestIntent;
3976 rec.key.allIntents = intents;
3977 rec.key.allResolvedTypes = resolvedTypes;
3978 } else {
3979 rec.key.allIntents = null;
3980 rec.key.allResolvedTypes = null;
3981 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 return rec;
3984 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003985 rec.canceled = true;
3986 mIntentSenderRecords.remove(key);
3987 }
3988 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 return rec;
3990 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003991 rec = new PendingIntentRecord(this, key, callingUid);
3992 mIntentSenderRecords.put(key, rec.ref);
3993 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
3994 if (activity.pendingResults == null) {
3995 activity.pendingResults
3996 = new HashSet<WeakReference<PendingIntentRecord>>();
3997 }
3998 activity.pendingResults.add(rec.ref);
3999 }
4000 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 }
4002
4003 public void cancelIntentSender(IIntentSender sender) {
4004 if (!(sender instanceof PendingIntentRecord)) {
4005 return;
4006 }
4007 synchronized(this) {
4008 PendingIntentRecord rec = (PendingIntentRecord)sender;
4009 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004010 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 .getPackageUid(rec.key.packageName);
4012 if (uid != Binder.getCallingUid()) {
4013 String msg = "Permission Denial: cancelIntentSender() from pid="
4014 + Binder.getCallingPid()
4015 + ", uid=" + Binder.getCallingUid()
4016 + " is not allowed to cancel packges "
4017 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004018 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 throw new SecurityException(msg);
4020 }
4021 } catch (RemoteException e) {
4022 throw new SecurityException(e);
4023 }
4024 cancelIntentSenderLocked(rec, true);
4025 }
4026 }
4027
4028 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4029 rec.canceled = true;
4030 mIntentSenderRecords.remove(rec.key);
4031 if (cleanActivity && rec.key.activity != null) {
4032 rec.key.activity.pendingResults.remove(rec.ref);
4033 }
4034 }
4035
4036 public String getPackageForIntentSender(IIntentSender pendingResult) {
4037 if (!(pendingResult instanceof PendingIntentRecord)) {
4038 return null;
4039 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004040 try {
4041 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4042 return res.key.packageName;
4043 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 }
4045 return null;
4046 }
4047
4048 public void setProcessLimit(int max) {
4049 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4050 "setProcessLimit()");
4051 mProcessLimit = max;
4052 }
4053
4054 public int getProcessLimit() {
4055 return mProcessLimit;
4056 }
4057
4058 void foregroundTokenDied(ForegroundToken token) {
4059 synchronized (ActivityManagerService.this) {
4060 synchronized (mPidsSelfLocked) {
4061 ForegroundToken cur
4062 = mForegroundProcesses.get(token.pid);
4063 if (cur != token) {
4064 return;
4065 }
4066 mForegroundProcesses.remove(token.pid);
4067 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4068 if (pr == null) {
4069 return;
4070 }
4071 pr.forcingToForeground = null;
4072 pr.foregroundServices = false;
4073 }
4074 updateOomAdjLocked();
4075 }
4076 }
4077
4078 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4079 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4080 "setProcessForeground()");
4081 synchronized(this) {
4082 boolean changed = false;
4083
4084 synchronized (mPidsSelfLocked) {
4085 ProcessRecord pr = mPidsSelfLocked.get(pid);
4086 if (pr == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004087 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 return;
4089 }
4090 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4091 if (oldToken != null) {
4092 oldToken.token.unlinkToDeath(oldToken, 0);
4093 mForegroundProcesses.remove(pid);
4094 pr.forcingToForeground = null;
4095 changed = true;
4096 }
4097 if (isForeground && token != null) {
4098 ForegroundToken newToken = new ForegroundToken() {
4099 public void binderDied() {
4100 foregroundTokenDied(this);
4101 }
4102 };
4103 newToken.pid = pid;
4104 newToken.token = token;
4105 try {
4106 token.linkToDeath(newToken, 0);
4107 mForegroundProcesses.put(pid, newToken);
4108 pr.forcingToForeground = token;
4109 changed = true;
4110 } catch (RemoteException e) {
4111 // If the process died while doing this, we will later
4112 // do the cleanup with the process death link.
4113 }
4114 }
4115 }
4116
4117 if (changed) {
4118 updateOomAdjLocked();
4119 }
4120 }
4121 }
4122
4123 // =========================================================
4124 // PERMISSIONS
4125 // =========================================================
4126
4127 static class PermissionController extends IPermissionController.Stub {
4128 ActivityManagerService mActivityManagerService;
4129 PermissionController(ActivityManagerService activityManagerService) {
4130 mActivityManagerService = activityManagerService;
4131 }
4132
4133 public boolean checkPermission(String permission, int pid, int uid) {
4134 return mActivityManagerService.checkPermission(permission, pid,
4135 uid) == PackageManager.PERMISSION_GRANTED;
4136 }
4137 }
4138
4139 /**
4140 * This can be called with or without the global lock held.
4141 */
4142 int checkComponentPermission(String permission, int pid, int uid,
4143 int reqUid) {
4144 // We might be performing an operation on behalf of an indirect binder
4145 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4146 // client identity accordingly before proceeding.
4147 Identity tlsIdentity = sCallerIdentity.get();
4148 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004149 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4151 uid = tlsIdentity.uid;
4152 pid = tlsIdentity.pid;
4153 }
4154
4155 // Root, system server and our own process get to do everything.
4156 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID ||
4157 !Process.supportsProcesses()) {
4158 return PackageManager.PERMISSION_GRANTED;
4159 }
4160 // If the target requires a specific UID, always fail for others.
4161 if (reqUid >= 0 && uid != reqUid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004162 Slog.w(TAG, "Permission denied: checkComponentPermission() reqUid=" + reqUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 return PackageManager.PERMISSION_DENIED;
4164 }
4165 if (permission == null) {
4166 return PackageManager.PERMISSION_GRANTED;
4167 }
4168 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004169 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 .checkUidPermission(permission, uid);
4171 } catch (RemoteException e) {
4172 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004173 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 }
4175 return PackageManager.PERMISSION_DENIED;
4176 }
4177
4178 /**
4179 * As the only public entry point for permissions checking, this method
4180 * can enforce the semantic that requesting a check on a null global
4181 * permission is automatically denied. (Internally a null permission
4182 * string is used when calling {@link #checkComponentPermission} in cases
4183 * when only uid-based security is needed.)
4184 *
4185 * This can be called with or without the global lock held.
4186 */
4187 public int checkPermission(String permission, int pid, int uid) {
4188 if (permission == null) {
4189 return PackageManager.PERMISSION_DENIED;
4190 }
4191 return checkComponentPermission(permission, pid, uid, -1);
4192 }
4193
4194 /**
4195 * Binder IPC calls go through the public entry point.
4196 * This can be called with or without the global lock held.
4197 */
4198 int checkCallingPermission(String permission) {
4199 return checkPermission(permission,
4200 Binder.getCallingPid(),
4201 Binder.getCallingUid());
4202 }
4203
4204 /**
4205 * This can be called with or without the global lock held.
4206 */
4207 void enforceCallingPermission(String permission, String func) {
4208 if (checkCallingPermission(permission)
4209 == PackageManager.PERMISSION_GRANTED) {
4210 return;
4211 }
4212
4213 String msg = "Permission Denial: " + func + " from pid="
4214 + Binder.getCallingPid()
4215 + ", uid=" + Binder.getCallingUid()
4216 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004217 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218 throw new SecurityException(msg);
4219 }
4220
4221 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07004222 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
4223 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4224 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
4225 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4226 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004227 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004228 // Is the component private from the target uid?
4229 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
4230
4231 // Acceptable if the there is no read permission needed from the
4232 // target or the target is holding the read permission.
4233 if (!readPerm) {
4234 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004236 == PackageManager.PERMISSION_GRANTED)) {
4237 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 }
4239 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004240
4241 // Acceptable if the there is no write permission needed from the
4242 // target or the target is holding the read permission.
4243 if (!writePerm) {
4244 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004246 == PackageManager.PERMISSION_GRANTED)) {
4247 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 }
4249 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004250
4251 // Acceptable if there is a path permission matching the URI that
4252 // the target holds the permission on.
4253 PathPermission[] pps = pi.pathPermissions;
4254 if (pps != null && (!readPerm || !writePerm)) {
4255 final String path = uri.getPath();
4256 int i = pps.length;
4257 while (i > 0 && (!readPerm || !writePerm)) {
4258 i--;
4259 PathPermission pp = pps[i];
4260 if (!readPerm) {
4261 final String pprperm = pp.getReadPermission();
4262 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4263 + pprperm + " for " + pp.getPath()
4264 + ": match=" + pp.match(path)
4265 + " check=" + pm.checkUidPermission(pprperm, uid));
4266 if (pprperm != null && pp.match(path) &&
4267 (pm.checkUidPermission(pprperm, uid)
4268 == PackageManager.PERMISSION_GRANTED)) {
4269 readPerm = true;
4270 }
4271 }
4272 if (!writePerm) {
4273 final String ppwperm = pp.getWritePermission();
4274 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4275 + ppwperm + " for " + pp.getPath()
4276 + ": match=" + pp.match(path)
4277 + " check=" + pm.checkUidPermission(ppwperm, uid));
4278 if (ppwperm != null && pp.match(path) &&
4279 (pm.checkUidPermission(ppwperm, uid)
4280 == PackageManager.PERMISSION_GRANTED)) {
4281 writePerm = true;
4282 }
4283 }
4284 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004286 } catch (RemoteException e) {
4287 return false;
4288 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004289
4290 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 }
4292
4293 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4294 int modeFlags) {
4295 // Root gets to do everything.
4296 if (uid == 0 || !Process.supportsProcesses()) {
4297 return true;
4298 }
4299 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4300 if (perms == null) return false;
4301 UriPermission perm = perms.get(uri);
4302 if (perm == null) return false;
4303 return (modeFlags&perm.modeFlags) == modeFlags;
4304 }
4305
4306 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
4307 // Another redirected-binder-call permissions check as in
4308 // {@link checkComponentPermission}.
4309 Identity tlsIdentity = sCallerIdentity.get();
4310 if (tlsIdentity != null) {
4311 uid = tlsIdentity.uid;
4312 pid = tlsIdentity.pid;
4313 }
4314
4315 // Our own process gets to do everything.
4316 if (pid == MY_PID) {
4317 return PackageManager.PERMISSION_GRANTED;
4318 }
4319 synchronized(this) {
4320 return checkUriPermissionLocked(uri, uid, modeFlags)
4321 ? PackageManager.PERMISSION_GRANTED
4322 : PackageManager.PERMISSION_DENIED;
4323 }
4324 }
4325
Dianne Hackborn39792d22010-08-19 18:01:52 -07004326 /**
4327 * Check if the targetPkg can be granted permission to access uri by
4328 * the callingUid using the given modeFlags. Throws a security exception
4329 * if callingUid is not allowed to do this. Returns the uid of the target
4330 * if the URI permission grant should be performed; returns -1 if it is not
4331 * needed (for example targetPkg already has permission to access the URI).
4332 */
4333 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
4334 Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4336 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4337 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004338 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 }
4340
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004341 if (targetPkg != null) {
4342 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4343 "Checking grant " + targetPkg + " permission to " + uri);
4344 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004345
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004346 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347
4348 // If this is not a content: uri, we can't do anything with it.
4349 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004350 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004351 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004352 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 }
4354
4355 String name = uri.getAuthority();
4356 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004357 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 if (cpr != null) {
4359 pi = cpr.info;
4360 } else {
4361 try {
4362 pi = pm.resolveContentProvider(name,
4363 PackageManager.GET_URI_PERMISSION_PATTERNS);
4364 } catch (RemoteException ex) {
4365 }
4366 }
4367 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004368 Slog.w(TAG, "No content provider found for: " + name);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004369 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004370 }
4371
4372 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004373 if (targetPkg != null) {
4374 try {
4375 targetUid = pm.getPackageUid(targetPkg);
4376 if (targetUid < 0) {
4377 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4378 "Can't grant URI permission no uid for: " + targetPkg);
4379 return -1;
4380 }
4381 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004382 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004384 } else {
4385 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 }
4387
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004388 if (targetUid >= 0) {
4389 // First... does the target actually need this permission?
4390 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4391 // No need to grant the target this permission.
4392 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4393 "Target " + targetPkg + " already has full permission to " + uri);
4394 return -1;
4395 }
4396 } else {
4397 // First... there is no target package, so can anyone access it?
4398 boolean allowed = pi.exported;
4399 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4400 if (pi.readPermission != null) {
4401 allowed = false;
4402 }
4403 }
4404 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4405 if (pi.writePermission != null) {
4406 allowed = false;
4407 }
4408 }
4409 if (allowed) {
4410 return -1;
4411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412 }
4413
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004414 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004415 if (!pi.grantUriPermissions) {
4416 throw new SecurityException("Provider " + pi.packageName
4417 + "/" + pi.name
4418 + " does not allow granting of Uri permissions (uri "
4419 + uri + ")");
4420 }
4421 if (pi.uriPermissionPatterns != null) {
4422 final int N = pi.uriPermissionPatterns.length;
4423 boolean allowed = false;
4424 for (int i=0; i<N; i++) {
4425 if (pi.uriPermissionPatterns[i] != null
4426 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4427 allowed = true;
4428 break;
4429 }
4430 }
4431 if (!allowed) {
4432 throw new SecurityException("Provider " + pi.packageName
4433 + "/" + pi.name
4434 + " does not allow granting of permission to path of Uri "
4435 + uri);
4436 }
4437 }
4438
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004439 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004441 if (callingUid != Process.myUid()) {
4442 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4443 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4444 throw new SecurityException("Uid " + callingUid
4445 + " does not have permission to uri " + uri);
4446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 }
4448 }
4449
Dianne Hackborn39792d22010-08-19 18:01:52 -07004450 return targetUid;
4451 }
4452
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004453 public int checkGrantUriPermission(int callingUid, String targetPkg,
4454 Uri uri, int modeFlags) {
4455 synchronized(this) {
4456 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4457 }
4458 }
4459
Dianne Hackborn39792d22010-08-19 18:01:52 -07004460 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4461 Uri uri, int modeFlags, UriPermissionOwner owner) {
4462 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4463 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4464 if (modeFlags == 0) {
4465 return;
4466 }
4467
4468 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 // to the uri, and the target doesn't. Let's now give this to
4470 // the target.
4471
Joe Onorato8a9b2202010-02-26 18:56:32 -08004472 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004473 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 HashMap<Uri, UriPermission> targetUris
4476 = mGrantedUriPermissions.get(targetUid);
4477 if (targetUris == null) {
4478 targetUris = new HashMap<Uri, UriPermission>();
4479 mGrantedUriPermissions.put(targetUid, targetUris);
4480 }
4481
4482 UriPermission perm = targetUris.get(uri);
4483 if (perm == null) {
4484 perm = new UriPermission(targetUid, uri);
4485 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004486 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004489 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004490 perm.globalModeFlags |= modeFlags;
4491 } else if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004492 perm.readOwners.add(owner);
4493 owner.addReadPermission(perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 } else if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004495 perm.writeOwners.add(owner);
4496 owner.addWritePermission(perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 }
4498 }
4499
Dianne Hackborn39792d22010-08-19 18:01:52 -07004500 void grantUriPermissionLocked(int callingUid,
4501 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004502 if (targetPkg == null) {
4503 throw new NullPointerException("targetPkg");
4504 }
4505
Dianne Hackborn39792d22010-08-19 18:01:52 -07004506 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4507 if (targetUid < 0) {
4508 return;
4509 }
4510
4511 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4512 }
4513
4514 /**
4515 * Like checkGrantUriPermissionLocked, but takes an Intent.
4516 */
4517 int checkGrantUriPermissionFromIntentLocked(int callingUid,
4518 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004519 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004520 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004521 + " from " + intent + "; flags=0x"
4522 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4523
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004524 if (targetPkg == null) {
4525 throw new NullPointerException("targetPkg");
4526 }
4527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004528 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004529 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 }
4531 Uri data = intent.getData();
4532 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004533 return -1;
4534 }
4535 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4536 intent.getFlags());
4537 }
4538
4539 /**
4540 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4541 */
4542 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
4543 String targetPkg, Intent intent, UriPermissionOwner owner) {
4544 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
4545 intent.getFlags(), owner);
4546 }
4547
4548 void grantUriPermissionFromIntentLocked(int callingUid,
4549 String targetPkg, Intent intent, UriPermissionOwner owner) {
4550 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
4551 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 return;
4553 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004554
4555 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004556 }
4557
4558 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4559 Uri uri, int modeFlags) {
4560 synchronized(this) {
4561 final ProcessRecord r = getRecordForAppLocked(caller);
4562 if (r == null) {
4563 throw new SecurityException("Unable to find app for caller "
4564 + caller
4565 + " when granting permission to uri " + uri);
4566 }
4567 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004568 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004569 }
4570 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004571 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 }
4573
4574 grantUriPermissionLocked(r.info.uid, targetPkg, uri, modeFlags,
4575 null);
4576 }
4577 }
4578
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004579 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4581 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4582 HashMap<Uri, UriPermission> perms
4583 = mGrantedUriPermissions.get(perm.uid);
4584 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004585 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004586 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 perms.remove(perm.uri);
4588 if (perms.size() == 0) {
4589 mGrantedUriPermissions.remove(perm.uid);
4590 }
4591 }
4592 }
4593 }
4594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 private void revokeUriPermissionLocked(int callingUid, Uri uri,
4596 int modeFlags) {
4597 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4598 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4599 if (modeFlags == 0) {
4600 return;
4601 }
4602
Joe Onorato8a9b2202010-02-26 18:56:32 -08004603 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004604 "Revoking all granted permissions to " + uri);
4605
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004606 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607
4608 final String authority = uri.getAuthority();
4609 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004610 ContentProviderRecord cpr = mProvidersByName.get(authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611 if (cpr != null) {
4612 pi = cpr.info;
4613 } else {
4614 try {
4615 pi = pm.resolveContentProvider(authority,
4616 PackageManager.GET_URI_PERMISSION_PATTERNS);
4617 } catch (RemoteException ex) {
4618 }
4619 }
4620 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004621 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 return;
4623 }
4624
4625 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07004626 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004627 // Right now, if you are not the original owner of the permission,
4628 // you are not allowed to revoke it.
4629 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4630 throw new SecurityException("Uid " + callingUid
4631 + " does not have permission to uri " + uri);
4632 //}
4633 }
4634
4635 // Go through all of the permissions and remove any that match.
4636 final List<String> SEGMENTS = uri.getPathSegments();
4637 if (SEGMENTS != null) {
4638 final int NS = SEGMENTS.size();
4639 int N = mGrantedUriPermissions.size();
4640 for (int i=0; i<N; i++) {
4641 HashMap<Uri, UriPermission> perms
4642 = mGrantedUriPermissions.valueAt(i);
4643 Iterator<UriPermission> it = perms.values().iterator();
4644 toploop:
4645 while (it.hasNext()) {
4646 UriPermission perm = it.next();
4647 Uri targetUri = perm.uri;
4648 if (!authority.equals(targetUri.getAuthority())) {
4649 continue;
4650 }
4651 List<String> targetSegments = targetUri.getPathSegments();
4652 if (targetSegments == null) {
4653 continue;
4654 }
4655 if (targetSegments.size() < NS) {
4656 continue;
4657 }
4658 for (int j=0; j<NS; j++) {
4659 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
4660 continue toploop;
4661 }
4662 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004663 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004664 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 perm.clearModes(modeFlags);
4666 if (perm.modeFlags == 0) {
4667 it.remove();
4668 }
4669 }
4670 if (perms.size() == 0) {
4671 mGrantedUriPermissions.remove(
4672 mGrantedUriPermissions.keyAt(i));
4673 N--;
4674 i--;
4675 }
4676 }
4677 }
4678 }
4679
4680 public void revokeUriPermission(IApplicationThread caller, Uri uri,
4681 int modeFlags) {
4682 synchronized(this) {
4683 final ProcessRecord r = getRecordForAppLocked(caller);
4684 if (r == null) {
4685 throw new SecurityException("Unable to find app for caller "
4686 + caller
4687 + " when revoking permission to uri " + uri);
4688 }
4689 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004690 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004691 return;
4692 }
4693
4694 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4695 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4696 if (modeFlags == 0) {
4697 return;
4698 }
4699
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004700 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004701
4702 final String authority = uri.getAuthority();
4703 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004704 ContentProviderRecord cpr = mProvidersByName.get(authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 if (cpr != null) {
4706 pi = cpr.info;
4707 } else {
4708 try {
4709 pi = pm.resolveContentProvider(authority,
4710 PackageManager.GET_URI_PERMISSION_PATTERNS);
4711 } catch (RemoteException ex) {
4712 }
4713 }
4714 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004715 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004716 return;
4717 }
4718
4719 revokeUriPermissionLocked(r.info.uid, uri, modeFlags);
4720 }
4721 }
4722
Dianne Hackborn7e269642010-08-25 19:50:20 -07004723 @Override
4724 public IBinder newUriPermissionOwner(String name) {
4725 synchronized(this) {
4726 UriPermissionOwner owner = new UriPermissionOwner(this, name);
4727 return owner.getExternalTokenLocked();
4728 }
4729 }
4730
4731 @Override
4732 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
4733 Uri uri, int modeFlags) {
4734 synchronized(this) {
4735 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
4736 if (owner == null) {
4737 throw new IllegalArgumentException("Unknown owner: " + token);
4738 }
4739 if (fromUid != Binder.getCallingUid()) {
4740 if (Binder.getCallingUid() != Process.myUid()) {
4741 // Only system code can grant URI permissions on behalf
4742 // of other users.
4743 throw new SecurityException("nice try");
4744 }
4745 }
4746 if (targetPkg == null) {
4747 throw new IllegalArgumentException("null target");
4748 }
4749 if (uri == null) {
4750 throw new IllegalArgumentException("null uri");
4751 }
4752
4753 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
4754 }
4755 }
4756
4757 @Override
4758 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
4759 synchronized(this) {
4760 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
4761 if (owner == null) {
4762 throw new IllegalArgumentException("Unknown owner: " + token);
4763 }
4764
4765 if (uri == null) {
4766 owner.removeUriPermissionsLocked(mode);
4767 } else {
4768 owner.removeUriPermissionLocked(uri, mode);
4769 }
4770 }
4771 }
4772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004773 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
4774 synchronized (this) {
4775 ProcessRecord app =
4776 who != null ? getRecordForAppLocked(who) : null;
4777 if (app == null) return;
4778
4779 Message msg = Message.obtain();
4780 msg.what = WAIT_FOR_DEBUGGER_MSG;
4781 msg.obj = app;
4782 msg.arg1 = waiting ? 1 : 0;
4783 mHandler.sendMessage(msg);
4784 }
4785 }
4786
4787 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
4788 outInfo.availMem = Process.getFreeMemory();
The Android Open Source Project4df24232009-03-05 14:34:35 -08004789 outInfo.threshold = HOME_APP_MEM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004790 outInfo.lowMemory = outInfo.availMem <
The Android Open Source Project4df24232009-03-05 14:34:35 -08004791 (HOME_APP_MEM + ((HIDDEN_APP_MEM-HOME_APP_MEM)/2));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004792 }
4793
4794 // =========================================================
4795 // TASK MANAGEMENT
4796 // =========================================================
4797
4798 public List getTasks(int maxNum, int flags,
4799 IThumbnailReceiver receiver) {
4800 ArrayList list = new ArrayList();
4801
4802 PendingThumbnailsRecord pending = null;
4803 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004804 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004805
4806 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004807 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004808 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
4809 + ", receiver=" + receiver);
4810
4811 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
4812 != PackageManager.PERMISSION_GRANTED) {
4813 if (receiver != null) {
4814 // If the caller wants to wait for pending thumbnails,
4815 // it ain't gonna get them.
4816 try {
4817 receiver.finished();
4818 } catch (RemoteException ex) {
4819 }
4820 }
4821 String msg = "Permission Denial: getTasks() from pid="
4822 + Binder.getCallingPid()
4823 + ", uid=" + Binder.getCallingUid()
4824 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004825 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826 throw new SecurityException(msg);
4827 }
4828
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004829 final boolean canReadFb = checkCallingPermission(
4830 android.Manifest.permission.READ_FRAME_BUFFER)
4831 == PackageManager.PERMISSION_GRANTED;
4832
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004833 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004834 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004835 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004836 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 CharSequence topDescription = null;
4838 TaskRecord curTask = null;
4839 int numActivities = 0;
4840 int numRunning = 0;
4841 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004842 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004843 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004844 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004845
4846 // Initialize state for next task if needed.
4847 if (top == null ||
4848 (top.state == ActivityState.INITIALIZING
4849 && top.task == r.task)) {
4850 top = r;
4851 topDescription = r.description;
4852 curTask = r.task;
4853 numActivities = numRunning = 0;
4854 }
4855
4856 // Add 'r' into the current task.
4857 numActivities++;
4858 if (r.app != null && r.app.thread != null) {
4859 numRunning++;
4860 }
4861 if (topDescription == null) {
4862 topDescription = r.description;
4863 }
4864
Joe Onorato8a9b2202010-02-26 18:56:32 -08004865 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004866 TAG, r.intent.getComponent().flattenToShortString()
4867 + ": task=" + r.task);
4868
4869 // If the next one is a different task, generate a new
4870 // TaskInfo entry for what we have.
4871 if (next == null || next.task != curTask) {
4872 ActivityManager.RunningTaskInfo ci
4873 = new ActivityManager.RunningTaskInfo();
4874 ci.id = curTask.taskId;
4875 ci.baseActivity = r.intent.getComponent();
4876 ci.topActivity = top.intent.getComponent();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004877 if (canReadFb) {
4878 if (top.thumbnail != null) {
4879 ci.thumbnail = top.thumbnail;
4880 } else if (top.state == ActivityState.RESUMED) {
4881 ci.thumbnail = top.stack.screenshotActivities();
4882 }
4883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 ci.description = topDescription;
4885 ci.numActivities = numActivities;
4886 ci.numRunning = numRunning;
4887 //System.out.println(
4888 // "#" + maxNum + ": " + " descr=" + ci.description);
4889 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004890 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 TAG, "State=" + top.state + "Idle=" + top.idle
4892 + " app=" + top.app
4893 + " thr=" + (top.app != null ? top.app.thread : null));
4894 if (top.state == ActivityState.RESUMED
4895 || top.state == ActivityState.PAUSING) {
4896 if (top.idle && top.app != null
4897 && top.app.thread != null) {
4898 topRecord = top;
4899 topThumbnail = top.app.thread;
4900 } else {
4901 top.thumbnailNeeded = true;
4902 }
4903 }
4904 if (pending == null) {
4905 pending = new PendingThumbnailsRecord(receiver);
4906 }
4907 pending.pendingRecords.add(top);
4908 }
4909 list.add(ci);
4910 maxNum--;
4911 top = null;
4912 }
4913 }
4914
4915 if (pending != null) {
4916 mPendingThumbnails.add(pending);
4917 }
4918 }
4919
Joe Onorato8a9b2202010-02-26 18:56:32 -08004920 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004921
4922 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004923 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004924 try {
4925 topThumbnail.requestThumbnail(topRecord);
4926 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004927 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004928 sendPendingThumbnail(null, topRecord, null, null, true);
4929 }
4930 }
4931
4932 if (pending == null && receiver != null) {
4933 // In this case all thumbnails were available and the client
4934 // is being asked to be told when the remaining ones come in...
4935 // which is unusually, since the top-most currently running
4936 // activity should never have a canned thumbnail! Oh well.
4937 try {
4938 receiver.finished();
4939 } catch (RemoteException ex) {
4940 }
4941 }
4942
4943 return list;
4944 }
4945
4946 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
4947 int flags) {
4948 synchronized (this) {
4949 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
4950 "getRecentTasks()");
4951
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004952 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07004953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004954 final int N = mRecentTasks.size();
4955 ArrayList<ActivityManager.RecentTaskInfo> res
4956 = new ArrayList<ActivityManager.RecentTaskInfo>(
4957 maxNum < N ? maxNum : N);
4958 for (int i=0; i<N && maxNum > 0; i++) {
4959 TaskRecord tr = mRecentTasks.get(i);
4960 if (((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
4961 || (tr.intent == null)
4962 || ((tr.intent.getFlags()
4963 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
4964 ActivityManager.RecentTaskInfo rti
4965 = new ActivityManager.RecentTaskInfo();
4966 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
4967 rti.baseIntent = new Intent(
4968 tr.intent != null ? tr.intent : tr.affinityIntent);
4969 rti.origActivity = tr.origActivity;
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07004970
4971 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
4972 // Check whether this activity is currently available.
4973 try {
4974 if (rti.origActivity != null) {
4975 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
4976 continue;
4977 }
4978 } else if (rti.baseIntent != null) {
4979 if (pm.queryIntentActivities(rti.baseIntent,
4980 null, 0) == null) {
4981 continue;
4982 }
4983 }
4984 } catch (RemoteException e) {
4985 // Will never happen.
4986 }
4987 }
4988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004989 res.add(rti);
4990 maxNum--;
4991 }
4992 }
4993 return res;
4994 }
4995 }
4996
4997 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
4998 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004999 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 TaskRecord jt = startTask;
5001
5002 // First look backwards
5003 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005004 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005005 if (r.task != jt) {
5006 jt = r.task;
5007 if (affinity.equals(jt.affinity)) {
5008 return j;
5009 }
5010 }
5011 }
5012
5013 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005014 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005015 jt = startTask;
5016 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005017 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005018 if (r.task != jt) {
5019 if (affinity.equals(jt.affinity)) {
5020 return j;
5021 }
5022 jt = r.task;
5023 }
5024 }
5025
5026 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005027 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005028 return N-1;
5029 }
5030
5031 return -1;
5032 }
5033
5034 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005035 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005036 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005037 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5039 "moveTaskToFront()");
5040
5041 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005042 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5043 Binder.getCallingUid(), "Task to front")) {
5044 return;
5045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005046 final long origId = Binder.clearCallingIdentity();
5047 try {
5048 int N = mRecentTasks.size();
5049 for (int i=0; i<N; i++) {
5050 TaskRecord tr = mRecentTasks.get(i);
5051 if (tr.taskId == task) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005052 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5053 // Caller wants the home activity moved with it. To accomplish this,
5054 // we'll just move the home task to the top first.
5055 mMainStack.moveHomeToFrontLocked();
5056 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005057 mMainStack.moveTaskToFrontLocked(tr, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005058 return;
5059 }
5060 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005061 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5062 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005063 if (hr.task.taskId == task) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005064 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5065 // Caller wants the home activity moved with it. To accomplish this,
5066 // we'll just move the home task to the top first.
5067 mMainStack.moveHomeToFrontLocked();
5068 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005069 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 return;
5071 }
5072 }
5073 } finally {
5074 Binder.restoreCallingIdentity(origId);
5075 }
5076 }
5077 }
5078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005079 public void moveTaskToBack(int task) {
5080 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5081 "moveTaskToBack()");
5082
5083 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005084 if (mMainStack.mResumedActivity != null
5085 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005086 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5087 Binder.getCallingUid(), "Task to back")) {
5088 return;
5089 }
5090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005092 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093 Binder.restoreCallingIdentity(origId);
5094 }
5095 }
5096
5097 /**
5098 * Moves an activity, and all of the other activities within the same task, to the bottom
5099 * of the history stack. The activity's order within the task is unchanged.
5100 *
5101 * @param token A reference to the activity we wish to move
5102 * @param nonRoot If false then this only works if the activity is the root
5103 * of a task; if true it will work for any activity in a task.
5104 * @return Returns true if the move completed, false if not.
5105 */
5106 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
5107 synchronized(this) {
5108 final long origId = Binder.clearCallingIdentity();
5109 int taskId = getTaskForActivityLocked(token, !nonRoot);
5110 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005111 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 }
5113 Binder.restoreCallingIdentity(origId);
5114 }
5115 return false;
5116 }
5117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118 public void moveTaskBackwards(int task) {
5119 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5120 "moveTaskBackwards()");
5121
5122 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005123 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5124 Binder.getCallingUid(), "Task backwards")) {
5125 return;
5126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005127 final long origId = Binder.clearCallingIdentity();
5128 moveTaskBackwardsLocked(task);
5129 Binder.restoreCallingIdentity(origId);
5130 }
5131 }
5132
5133 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005134 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005135 }
5136
5137 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5138 synchronized(this) {
5139 return getTaskForActivityLocked(token, onlyRoot);
5140 }
5141 }
5142
5143 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005144 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145 TaskRecord lastTask = null;
5146 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005147 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 if (r == token) {
5149 if (!onlyRoot || lastTask != r.task) {
5150 return r.task.taskId;
5151 }
5152 return -1;
5153 }
5154 lastTask = r.task;
5155 }
5156
5157 return -1;
5158 }
5159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005160 public void finishOtherInstances(IBinder token, ComponentName className) {
5161 synchronized(this) {
5162 final long origId = Binder.clearCallingIdentity();
5163
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005164 int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005165 TaskRecord lastTask = null;
5166 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005167 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005168 if (r.realActivity.equals(className)
5169 && r != token && lastTask != r.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005170 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005171 null, "others")) {
5172 i--;
5173 N--;
5174 }
5175 }
5176 lastTask = r.task;
5177 }
5178
5179 Binder.restoreCallingIdentity(origId);
5180 }
5181 }
5182
5183 // =========================================================
5184 // THUMBNAILS
5185 // =========================================================
5186
5187 public void reportThumbnail(IBinder token,
5188 Bitmap thumbnail, CharSequence description) {
5189 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5190 final long origId = Binder.clearCallingIdentity();
5191 sendPendingThumbnail(null, token, thumbnail, description, true);
5192 Binder.restoreCallingIdentity(origId);
5193 }
5194
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005195 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 Bitmap thumbnail, CharSequence description, boolean always) {
5197 TaskRecord task = null;
5198 ArrayList receivers = null;
5199
5200 //System.out.println("Send pending thumbnail: " + r);
5201
5202 synchronized(this) {
5203 if (r == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005204 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 if (index < 0) {
5206 return;
5207 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005208 r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 }
5210 if (thumbnail == null) {
5211 thumbnail = r.thumbnail;
5212 description = r.description;
5213 }
5214 if (thumbnail == null && !always) {
5215 // If there is no thumbnail, and this entry is not actually
5216 // going away, then abort for now and pick up the next
5217 // thumbnail we get.
5218 return;
5219 }
5220 task = r.task;
5221
5222 int N = mPendingThumbnails.size();
5223 int i=0;
5224 while (i<N) {
5225 PendingThumbnailsRecord pr =
5226 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5227 //System.out.println("Looking in " + pr.pendingRecords);
5228 if (pr.pendingRecords.remove(r)) {
5229 if (receivers == null) {
5230 receivers = new ArrayList();
5231 }
5232 receivers.add(pr);
5233 if (pr.pendingRecords.size() == 0) {
5234 pr.finished = true;
5235 mPendingThumbnails.remove(i);
5236 N--;
5237 continue;
5238 }
5239 }
5240 i++;
5241 }
5242 }
5243
5244 if (receivers != null) {
5245 final int N = receivers.size();
5246 for (int i=0; i<N; i++) {
5247 try {
5248 PendingThumbnailsRecord pr =
5249 (PendingThumbnailsRecord)receivers.get(i);
5250 pr.receiver.newThumbnail(
5251 task != null ? task.taskId : -1, thumbnail, description);
5252 if (pr.finished) {
5253 pr.receiver.finished();
5254 }
5255 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005256 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257 }
5258 }
5259 }
5260 }
5261
5262 // =========================================================
5263 // CONTENT PROVIDERS
5264 // =========================================================
5265
5266 private final List generateApplicationProvidersLocked(ProcessRecord app) {
5267 List providers = null;
5268 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005269 providers = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 queryContentProviders(app.processName, app.info.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005271 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005272 } catch (RemoteException ex) {
5273 }
5274 if (providers != null) {
5275 final int N = providers.size();
5276 for (int i=0; i<N; i++) {
5277 ProviderInfo cpi =
5278 (ProviderInfo)providers.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07005279 ContentProviderRecord cpr = mProvidersByClass.get(cpi.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005280 if (cpr == null) {
5281 cpr = new ContentProviderRecord(cpi, app.info);
5282 mProvidersByClass.put(cpi.name, cpr);
5283 }
5284 app.pubProviders.put(cpi.name, cpr);
5285 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005286 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 }
5288 }
5289 return providers;
5290 }
5291
5292 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005293 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
5295 final int callingUid = (r != null) ? r.info.uid : Binder.getCallingUid();
5296 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
5297 cpi.exported ? -1 : cpi.applicationInfo.uid)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005298 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005299 return null;
5300 }
5301 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
5302 cpi.exported ? -1 : cpi.applicationInfo.uid)
5303 == PackageManager.PERMISSION_GRANTED) {
5304 return null;
5305 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005306
5307 PathPermission[] pps = cpi.pathPermissions;
5308 if (pps != null) {
5309 int i = pps.length;
5310 while (i > 0) {
5311 i--;
5312 PathPermission pp = pps[i];
5313 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
5314 cpi.exported ? -1 : cpi.applicationInfo.uid)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005315 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005316 return null;
5317 }
5318 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
5319 cpi.exported ? -1 : cpi.applicationInfo.uid)
5320 == PackageManager.PERMISSION_GRANTED) {
5321 return null;
5322 }
5323 }
5324 }
5325
Dianne Hackbornb424b632010-08-18 15:59:05 -07005326 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5327 if (perms != null) {
5328 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5329 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5330 return null;
5331 }
5332 }
5333 }
5334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005335 String msg = "Permission Denial: opening provider " + cpi.name
5336 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5337 + ", uid=" + callingUid + ") requires "
5338 + cpi.readPermission + " or " + cpi.writePermission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005339 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005340 return msg;
5341 }
5342
5343 private final ContentProviderHolder getContentProviderImpl(
5344 IApplicationThread caller, String name) {
5345 ContentProviderRecord cpr;
5346 ProviderInfo cpi = null;
5347
5348 synchronized(this) {
5349 ProcessRecord r = null;
5350 if (caller != null) {
5351 r = getRecordForAppLocked(caller);
5352 if (r == null) {
5353 throw new SecurityException(
5354 "Unable to find app for caller " + caller
5355 + " (pid=" + Binder.getCallingPid()
5356 + ") when getting content provider " + name);
5357 }
5358 }
5359
5360 // First check if this content provider has been published...
Dianne Hackborn860755f2010-06-03 18:47:52 -07005361 cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 if (cpr != null) {
5363 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005364 String msg;
5365 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5366 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367 }
5368
5369 if (r != null && cpr.canRunHere(r)) {
5370 // This provider has been published or is in the process
5371 // of being published... but it is also allowed to run
5372 // in the caller's process, so don't make a connection
5373 // and just let the caller instantiate its own instance.
5374 if (cpr.provider != null) {
5375 // don't give caller the provider object, it needs
5376 // to make its own.
5377 cpr = new ContentProviderRecord(cpr);
5378 }
5379 return cpr;
5380 }
5381
5382 final long origId = Binder.clearCallingIdentity();
5383
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005384 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005385 // return it right away.
5386 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005387 if (DEBUG_PROVIDER) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005388 "Adding provider requested by "
5389 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005390 + cpr.info.processName);
5391 Integer cnt = r.conProviders.get(cpr);
5392 if (cnt == null) {
5393 r.conProviders.put(cpr, new Integer(1));
5394 } else {
5395 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 cpr.clients.add(r);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005398 if (cpr.app != null && r.setAdj <= PERCEPTIBLE_APP_ADJ) {
5399 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005400 // make sure to count it as being accessed and thus
5401 // back up on the LRU list. This is good because
5402 // content providers are often expensive to start.
5403 updateLruProcessLocked(cpr.app, false, true);
5404 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07005405 } else {
5406 cpr.externals++;
5407 }
5408
5409 if (cpr.app != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005410 updateOomAdjLocked(cpr.app);
5411 }
5412
5413 Binder.restoreCallingIdentity(origId);
5414
5415 } else {
5416 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005417 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07005418 resolveContentProvider(name,
5419 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 } catch (RemoteException ex) {
5421 }
5422 if (cpi == null) {
5423 return null;
5424 }
5425
Dianne Hackbornb424b632010-08-18 15:59:05 -07005426 String msg;
5427 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5428 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 }
5430
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07005431 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005432 && !cpi.processName.equals("system")) {
5433 // If this content provider does not run in the system
5434 // process, and the system is not yet ready to run other
5435 // processes, then fail fast instead of hanging.
5436 throw new IllegalArgumentException(
5437 "Attempt to launch content provider before system ready");
5438 }
5439
Dianne Hackborn860755f2010-06-03 18:47:52 -07005440 cpr = mProvidersByClass.get(cpi.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 final boolean firstClass = cpr == null;
5442 if (firstClass) {
5443 try {
5444 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005445 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 getApplicationInfo(
5447 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005448 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005449 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005450 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 + cpi.name);
5452 return null;
5453 }
5454 cpr = new ContentProviderRecord(cpi, ai);
5455 } catch (RemoteException ex) {
5456 // pm is in same process, this will never happen.
5457 }
5458 }
5459
5460 if (r != null && cpr.canRunHere(r)) {
5461 // If this is a multiprocess provider, then just return its
5462 // info and allow the caller to instantiate it. Only do
5463 // this if the provider is the same user as the caller's
5464 // process, or can run as root (so can be in any process).
5465 return cpr;
5466 }
5467
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005468 if (DEBUG_PROVIDER) {
5469 RuntimeException e = new RuntimeException("here");
Joe Onorato8a9b2202010-02-26 18:56:32 -08005470 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.info.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005471 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 }
5473
5474 // This is single process, and our app is now connecting to it.
5475 // See if we are already in the process of launching this
5476 // provider.
5477 final int N = mLaunchingProviders.size();
5478 int i;
5479 for (i=0; i<N; i++) {
5480 if (mLaunchingProviders.get(i) == cpr) {
5481 break;
5482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 }
5484
5485 // If the provider is not already being launched, then get it
5486 // started.
5487 if (i >= N) {
5488 final long origId = Binder.clearCallingIdentity();
5489 ProcessRecord proc = startProcessLocked(cpi.processName,
5490 cpr.appInfo, false, 0, "content provider",
5491 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005492 cpi.name), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005494 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 + cpi.applicationInfo.packageName + "/"
5496 + cpi.applicationInfo.uid + " for provider "
5497 + name + ": process is bad");
5498 return null;
5499 }
5500 cpr.launchingApp = proc;
5501 mLaunchingProviders.add(cpr);
5502 Binder.restoreCallingIdentity(origId);
5503 }
5504
5505 // Make sure the provider is published (the same provider class
5506 // may be published under multiple names).
5507 if (firstClass) {
5508 mProvidersByClass.put(cpi.name, cpr);
5509 }
5510 mProvidersByName.put(name, cpr);
5511
5512 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005513 if (DEBUG_PROVIDER) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005514 "Adding provider requested by "
5515 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005516 + cpr.info.processName);
5517 Integer cnt = r.conProviders.get(cpr);
5518 if (cnt == null) {
5519 r.conProviders.put(cpr, new Integer(1));
5520 } else {
5521 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 cpr.clients.add(r);
5524 } else {
5525 cpr.externals++;
5526 }
5527 }
5528 }
5529
5530 // Wait for the provider to be published...
5531 synchronized (cpr) {
5532 while (cpr.provider == null) {
5533 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005534 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 + cpi.applicationInfo.packageName + "/"
5536 + cpi.applicationInfo.uid + " for provider "
5537 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08005538 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 cpi.applicationInfo.packageName,
5540 cpi.applicationInfo.uid, name);
5541 return null;
5542 }
5543 try {
5544 cpr.wait();
5545 } catch (InterruptedException ex) {
5546 }
5547 }
5548 }
5549 return cpr;
5550 }
5551
5552 public final ContentProviderHolder getContentProvider(
5553 IApplicationThread caller, String name) {
5554 if (caller == null) {
5555 String msg = "null IApplicationThread when getting content provider "
5556 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005557 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 throw new SecurityException(msg);
5559 }
5560
5561 return getContentProviderImpl(caller, name);
5562 }
5563
5564 private ContentProviderHolder getContentProviderExternal(String name) {
5565 return getContentProviderImpl(null, name);
5566 }
5567
5568 /**
5569 * Drop a content provider from a ProcessRecord's bookkeeping
5570 * @param cpr
5571 */
5572 public void removeContentProvider(IApplicationThread caller, String name) {
5573 synchronized (this) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005574 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005576 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08005577 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005578 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 return;
5580 }
5581 final ProcessRecord r = getRecordForAppLocked(caller);
5582 if (r == null) {
5583 throw new SecurityException(
5584 "Unable to find app for caller " + caller +
5585 " when removing content provider " + name);
5586 }
5587 //update content provider record entry info
Dianne Hackborn860755f2010-06-03 18:47:52 -07005588 ContentProviderRecord localCpr = mProvidersByClass.get(cpr.info.name);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005589 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005590 + r.info.processName + " from process "
5591 + localCpr.appInfo.processName);
5592 if (localCpr.app == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005593 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08005594 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005595 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 return;
5597 } else {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005598 Integer cnt = r.conProviders.get(localCpr);
5599 if (cnt == null || cnt.intValue() <= 1) {
5600 localCpr.clients.remove(r);
5601 r.conProviders.remove(localCpr);
5602 } else {
5603 r.conProviders.put(localCpr, new Integer(cnt.intValue()-1));
5604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005605 }
5606 updateOomAdjLocked();
5607 }
5608 }
5609
5610 private void removeContentProviderExternal(String name) {
5611 synchronized (this) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005612 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 if(cpr == null) {
5614 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08005615 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 return;
5617 }
5618
5619 //update content provider record entry info
Dianne Hackborn860755f2010-06-03 18:47:52 -07005620 ContentProviderRecord localCpr = mProvidersByClass.get(cpr.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 localCpr.externals--;
5622 if (localCpr.externals < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005623 Slog.e(TAG, "Externals < 0 for content provider " + localCpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 }
5625 updateOomAdjLocked();
5626 }
5627 }
5628
5629 public final void publishContentProviders(IApplicationThread caller,
5630 List<ContentProviderHolder> providers) {
5631 if (providers == null) {
5632 return;
5633 }
5634
5635 synchronized(this) {
5636 final ProcessRecord r = getRecordForAppLocked(caller);
5637 if (r == null) {
5638 throw new SecurityException(
5639 "Unable to find app for caller " + caller
5640 + " (pid=" + Binder.getCallingPid()
5641 + ") when publishing content providers");
5642 }
5643
5644 final long origId = Binder.clearCallingIdentity();
5645
5646 final int N = providers.size();
5647 for (int i=0; i<N; i++) {
5648 ContentProviderHolder src = providers.get(i);
5649 if (src == null || src.info == null || src.provider == null) {
5650 continue;
5651 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005652 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 if (dst != null) {
5654 mProvidersByClass.put(dst.info.name, dst);
5655 String names[] = dst.info.authority.split(";");
5656 for (int j = 0; j < names.length; j++) {
5657 mProvidersByName.put(names[j], dst);
5658 }
5659
5660 int NL = mLaunchingProviders.size();
5661 int j;
5662 for (j=0; j<NL; j++) {
5663 if (mLaunchingProviders.get(j) == dst) {
5664 mLaunchingProviders.remove(j);
5665 j--;
5666 NL--;
5667 }
5668 }
5669 synchronized (dst) {
5670 dst.provider = src.provider;
5671 dst.app = r;
5672 dst.notifyAll();
5673 }
5674 updateOomAdjLocked(r);
5675 }
5676 }
5677
5678 Binder.restoreCallingIdentity(origId);
5679 }
5680 }
5681
5682 public static final void installSystemProviders() {
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08005683 List providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06005684 synchronized (mSelf) {
5685 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
5686 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08005687 if (providers != null) {
5688 for (int i=providers.size()-1; i>=0; i--) {
5689 ProviderInfo pi = (ProviderInfo)providers.get(i);
5690 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5691 Slog.w(TAG, "Not installing system proc provider " + pi.name
5692 + ": not system .apk");
5693 providers.remove(i);
5694 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005695 }
5696 }
5697 }
Josh Bartel2ecce342010-02-25 10:55:48 -06005698 if (providers != null) {
5699 mSystemThread.installSystemProviders(providers);
5700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 }
5702
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07005703 /**
5704 * Allows app to retrieve the MIME type of a URI without having permission
5705 * to access its content provider.
5706 *
5707 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
5708 *
5709 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
5710 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
5711 */
5712 public String getProviderMimeType(Uri uri) {
5713 final String name = uri.getAuthority();
5714 final long ident = Binder.clearCallingIdentity();
5715 ContentProviderHolder holder = null;
5716
5717 try {
5718 holder = getContentProviderExternal(name);
5719 if (holder != null) {
5720 return holder.provider.getType(uri);
5721 }
5722 } catch (RemoteException e) {
5723 Log.w(TAG, "Content provider dead retrieving " + uri, e);
5724 return null;
5725 } finally {
5726 if (holder != null) {
5727 removeContentProviderExternal(name);
5728 }
5729 Binder.restoreCallingIdentity(ident);
5730 }
5731
5732 return null;
5733 }
5734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005735 // =========================================================
5736 // GLOBAL MANAGEMENT
5737 // =========================================================
5738
5739 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
5740 ApplicationInfo info, String customProcess) {
5741 String proc = customProcess != null ? customProcess : info.processName;
5742 BatteryStatsImpl.Uid.Proc ps = null;
5743 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
5744 synchronized (stats) {
5745 ps = stats.getProcessStatsLocked(info.uid, proc);
5746 }
5747 return new ProcessRecord(ps, thread, info, proc);
5748 }
5749
5750 final ProcessRecord addAppLocked(ApplicationInfo info) {
5751 ProcessRecord app = getProcessRecordLocked(info.processName, info.uid);
5752
5753 if (app == null) {
5754 app = newProcessRecordLocked(null, info, null);
5755 mProcessNames.put(info.processName, info.uid, app);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08005756 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 }
5758
5759 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
5760 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
5761 app.persistent = true;
5762 app.maxAdj = CORE_SERVER_ADJ;
5763 }
5764 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
5765 mPersistentStartingProcesses.add(app);
5766 startProcessLocked(app, "added application", app.processName);
5767 }
5768
5769 return app;
5770 }
5771
5772 public void unhandledBack() {
5773 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
5774 "unhandledBack()");
5775
5776 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005777 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08005778 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 TAG, "Performing unhandledBack(): stack size = " + count);
5780 if (count > 1) {
5781 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005782 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
5784 Binder.restoreCallingIdentity(origId);
5785 }
5786 }
5787 }
5788
5789 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
5790 String name = uri.getAuthority();
5791 ContentProviderHolder cph = getContentProviderExternal(name);
5792 ParcelFileDescriptor pfd = null;
5793 if (cph != null) {
5794 // We record the binder invoker's uid in thread-local storage before
5795 // going to the content provider to open the file. Later, in the code
5796 // that handles all permissions checks, we look for this uid and use
5797 // that rather than the Activity Manager's own uid. The effect is that
5798 // we do the check against the caller's permissions even though it looks
5799 // to the content provider like the Activity Manager itself is making
5800 // the request.
5801 sCallerIdentity.set(new Identity(
5802 Binder.getCallingPid(), Binder.getCallingUid()));
5803 try {
5804 pfd = cph.provider.openFile(uri, "r");
5805 } catch (FileNotFoundException e) {
5806 // do nothing; pfd will be returned null
5807 } finally {
5808 // Ensure that whatever happens, we clean up the identity state
5809 sCallerIdentity.remove();
5810 }
5811
5812 // We've got the fd now, so we're done with the provider.
5813 removeContentProviderExternal(name);
5814 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005815 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 }
5817 return pfd;
5818 }
5819
5820 public void goingToSleep() {
5821 synchronized(this) {
5822 mSleeping = true;
5823 mWindowManager.setEventDispatching(false);
5824
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005825 if (mMainStack.mResumedActivity != null) {
5826 mMainStack.pauseIfSleepingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005827 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005828 Slog.w(TAG, "goingToSleep with no resumed activity!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005830
5831 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07005832 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005833 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
5834 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07005835 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 }
5837 }
5838
Dianne Hackborn55280a92009-05-07 15:53:46 -07005839 public boolean shutdown(int timeout) {
5840 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
5841 != PackageManager.PERMISSION_GRANTED) {
5842 throw new SecurityException("Requires permission "
5843 + android.Manifest.permission.SHUTDOWN);
5844 }
5845
5846 boolean timedout = false;
5847
5848 synchronized(this) {
5849 mShuttingDown = true;
5850 mWindowManager.setEventDispatching(false);
5851
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005852 if (mMainStack.mResumedActivity != null) {
5853 mMainStack.pauseIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07005854 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005855 while (mMainStack.mResumedActivity != null
5856 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07005857 long delay = endTime - System.currentTimeMillis();
5858 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005859 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07005860 timedout = true;
5861 break;
5862 }
5863 try {
5864 this.wait();
5865 } catch (InterruptedException e) {
5866 }
5867 }
5868 }
5869 }
5870
5871 mUsageStatsService.shutdown();
5872 mBatteryStatsService.shutdown();
5873
5874 return timedout;
5875 }
5876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 public void wakingUp() {
5878 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005879 if (mMainStack.mGoingToSleep.isHeld()) {
5880 mMainStack.mGoingToSleep.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 }
5882 mWindowManager.setEventDispatching(true);
5883 mSleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005884 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 }
5886 }
5887
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005888 public void stopAppSwitches() {
5889 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
5890 != PackageManager.PERMISSION_GRANTED) {
5891 throw new SecurityException("Requires permission "
5892 + android.Manifest.permission.STOP_APP_SWITCHES);
5893 }
5894
5895 synchronized(this) {
5896 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
5897 + APP_SWITCH_DELAY_TIME;
5898 mDidAppSwitch = false;
5899 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
5900 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
5901 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
5902 }
5903 }
5904
5905 public void resumeAppSwitches() {
5906 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
5907 != PackageManager.PERMISSION_GRANTED) {
5908 throw new SecurityException("Requires permission "
5909 + android.Manifest.permission.STOP_APP_SWITCHES);
5910 }
5911
5912 synchronized(this) {
5913 // Note that we don't execute any pending app switches... we will
5914 // let those wait until either the timeout, or the next start
5915 // activity request.
5916 mAppSwitchesAllowedTime = 0;
5917 }
5918 }
5919
5920 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
5921 String name) {
5922 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
5923 return true;
5924 }
5925
5926 final int perm = checkComponentPermission(
5927 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
5928 callingUid, -1);
5929 if (perm == PackageManager.PERMISSION_GRANTED) {
5930 return true;
5931 }
5932
Joe Onorato8a9b2202010-02-26 18:56:32 -08005933 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005934 return false;
5935 }
5936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005937 public void setDebugApp(String packageName, boolean waitForDebugger,
5938 boolean persistent) {
5939 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
5940 "setDebugApp()");
5941
5942 // Note that this is not really thread safe if there are multiple
5943 // callers into it at the same time, but that's not a situation we
5944 // care about.
5945 if (persistent) {
5946 final ContentResolver resolver = mContext.getContentResolver();
5947 Settings.System.putString(
5948 resolver, Settings.System.DEBUG_APP,
5949 packageName);
5950 Settings.System.putInt(
5951 resolver, Settings.System.WAIT_FOR_DEBUGGER,
5952 waitForDebugger ? 1 : 0);
5953 }
5954
5955 synchronized (this) {
5956 if (!persistent) {
5957 mOrigDebugApp = mDebugApp;
5958 mOrigWaitForDebugger = mWaitForDebugger;
5959 }
5960 mDebugApp = packageName;
5961 mWaitForDebugger = waitForDebugger;
5962 mDebugTransient = !persistent;
5963 if (packageName != null) {
5964 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005965 forceStopPackageLocked(packageName, -1, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 Binder.restoreCallingIdentity(origId);
5967 }
5968 }
5969 }
5970
5971 public void setAlwaysFinish(boolean enabled) {
5972 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
5973 "setAlwaysFinish()");
5974
5975 Settings.System.putInt(
5976 mContext.getContentResolver(),
5977 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
5978
5979 synchronized (this) {
5980 mAlwaysFinishActivities = enabled;
5981 }
5982 }
5983
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005984 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005986 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005988 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005989 }
5990 }
5991
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08005992 public boolean isUserAMonkey() {
5993 // For now the fact that there is a controller implies
5994 // we have a monkey.
5995 synchronized (this) {
5996 return mController != null;
5997 }
5998 }
5999
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006000 public void registerActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06006001 synchronized (this) {
6002 mWatchers.register(watcher);
6003 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006004 }
6005
6006 public void unregisterActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06006007 synchronized (this) {
6008 mWatchers.unregister(watcher);
6009 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006010 }
6011
Daniel Sandler69a48172010-06-23 16:29:36 -04006012 public void setImmersive(IBinder token, boolean immersive) {
6013 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006014 int index = (token != null) ? mMainStack.indexOfTokenLocked(token) : -1;
Daniel Sandler69a48172010-06-23 16:29:36 -04006015 if (index < 0) {
6016 throw new IllegalArgumentException();
6017 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006018 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
Daniel Sandler69a48172010-06-23 16:29:36 -04006019 r.immersive = immersive;
6020 }
6021 }
6022
6023 public boolean isImmersive(IBinder token) {
6024 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006025 int index = (token != null) ? mMainStack.indexOfTokenLocked(token) : -1;
Daniel Sandler69a48172010-06-23 16:29:36 -04006026 if (index < 0) {
6027 throw new IllegalArgumentException();
6028 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006029 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
Daniel Sandler69a48172010-06-23 16:29:36 -04006030 return r.immersive;
6031 }
6032 }
6033
6034 public boolean isTopActivityImmersive() {
6035 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006036 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006037 return (r != null) ? r.immersive : false;
6038 }
6039 }
6040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 public final void enterSafeMode() {
6042 synchronized(this) {
6043 // It only makes sense to do this before the system is ready
6044 // and started launching other packages.
6045 if (!mSystemReady) {
6046 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006047 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 } catch (RemoteException e) {
6049 }
6050
6051 View v = LayoutInflater.from(mContext).inflate(
6052 com.android.internal.R.layout.safe_mode, null);
6053 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Jeff Brown3b2b3542010-10-15 00:54:27 -07006054 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6056 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6057 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6058 lp.format = v.getBackground().getOpacity();
6059 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6060 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6061 ((WindowManager)mContext.getSystemService(
6062 Context.WINDOW_SERVICE)).addView(v, lp);
6063 }
6064 }
6065 }
6066
6067 public void noteWakeupAlarm(IIntentSender sender) {
6068 if (!(sender instanceof PendingIntentRecord)) {
6069 return;
6070 }
6071 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6072 synchronized (stats) {
6073 if (mBatteryStatsService.isOnBattery()) {
6074 mBatteryStatsService.enforceCallingPermission();
6075 PendingIntentRecord rec = (PendingIntentRecord)sender;
6076 int MY_UID = Binder.getCallingUid();
6077 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6078 BatteryStatsImpl.Uid.Pkg pkg =
6079 stats.getPackageStatsLocked(uid, rec.key.packageName);
6080 pkg.incWakeupsLocked();
6081 }
6082 }
6083 }
6084
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006085 public boolean killPids(int[] pids, String pReason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006087 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006089 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006090 // XXX Note: don't acquire main activity lock here, because the window
6091 // manager calls in with its locks held.
6092
6093 boolean killed = false;
6094 synchronized (mPidsSelfLocked) {
6095 int[] types = new int[pids.length];
6096 int worstType = 0;
6097 for (int i=0; i<pids.length; i++) {
6098 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6099 if (proc != null) {
6100 int type = proc.setAdj;
6101 types[i] = type;
6102 if (type > worstType) {
6103 worstType = type;
6104 }
6105 }
6106 }
6107
6108 // If the worse oom_adj is somewhere in the hidden proc LRU range,
6109 // then constrain it so we will kill all hidden procs.
6110 if (worstType < EMPTY_APP_ADJ && worstType > HIDDEN_APP_MIN_ADJ) {
6111 worstType = HIDDEN_APP_MIN_ADJ;
6112 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006113 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 for (int i=0; i<pids.length; i++) {
6115 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6116 if (proc == null) {
6117 continue;
6118 }
6119 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006120 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006121 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006122 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6123 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006125 proc.killedBackground = true;
6126 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 }
6128 }
6129 }
6130 return killed;
6131 }
6132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 public final void startRunning(String pkg, String cls, String action,
6134 String data) {
6135 synchronized(this) {
6136 if (mStartRunning) {
6137 return;
6138 }
6139 mStartRunning = true;
6140 mTopComponent = pkg != null && cls != null
6141 ? new ComponentName(pkg, cls) : null;
6142 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6143 mTopData = data;
6144 if (!mSystemReady) {
6145 return;
6146 }
6147 }
6148
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006149 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 }
6151
6152 private void retrieveSettings() {
6153 final ContentResolver resolver = mContext.getContentResolver();
6154 String debugApp = Settings.System.getString(
6155 resolver, Settings.System.DEBUG_APP);
6156 boolean waitForDebugger = Settings.System.getInt(
6157 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6158 boolean alwaysFinishActivities = Settings.System.getInt(
6159 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6160
6161 Configuration configuration = new Configuration();
6162 Settings.System.getConfiguration(resolver, configuration);
6163
6164 synchronized (this) {
6165 mDebugApp = mOrigDebugApp = debugApp;
6166 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6167 mAlwaysFinishActivities = alwaysFinishActivities;
6168 // This happens before any activities are started, so we can
6169 // change mConfiguration in-place.
6170 mConfiguration.updateFrom(configuration);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006171 mConfigurationSeq = mConfiguration.seq = 1;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006172 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 }
6174 }
6175
6176 public boolean testIsSystemReady() {
6177 // no need to synchronize(this) just to read & return the value
6178 return mSystemReady;
6179 }
6180
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006181 private static File getCalledPreBootReceiversFile() {
6182 File dataDir = Environment.getDataDirectory();
6183 File systemDir = new File(dataDir, "system");
6184 File fname = new File(systemDir, "called_pre_boots.dat");
6185 return fname;
6186 }
6187
6188 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6189 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6190 File file = getCalledPreBootReceiversFile();
6191 FileInputStream fis = null;
6192 try {
6193 fis = new FileInputStream(file);
6194 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
6195 int vers = dis.readInt();
6196 String codename = dis.readUTF();
6197 if (vers == android.os.Build.VERSION.SDK_INT
6198 && codename.equals(android.os.Build.VERSION.CODENAME)) {
6199 int num = dis.readInt();
6200 while (num > 0) {
6201 num--;
6202 String pkg = dis.readUTF();
6203 String cls = dis.readUTF();
6204 lastDoneReceivers.add(new ComponentName(pkg, cls));
6205 }
6206 }
6207 } catch (FileNotFoundException e) {
6208 } catch (IOException e) {
6209 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6210 } finally {
6211 if (fis != null) {
6212 try {
6213 fis.close();
6214 } catch (IOException e) {
6215 }
6216 }
6217 }
6218 return lastDoneReceivers;
6219 }
6220
6221 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
6222 File file = getCalledPreBootReceiversFile();
6223 FileOutputStream fos = null;
6224 DataOutputStream dos = null;
6225 try {
6226 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
6227 fos = new FileOutputStream(file);
6228 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
6229 dos.writeInt(android.os.Build.VERSION.SDK_INT);
6230 dos.writeUTF(android.os.Build.VERSION.CODENAME);
6231 dos.writeInt(list.size());
6232 for (int i=0; i<list.size(); i++) {
6233 dos.writeUTF(list.get(i).getPackageName());
6234 dos.writeUTF(list.get(i).getClassName());
6235 }
6236 } catch (IOException e) {
6237 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
6238 file.delete();
6239 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006240 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006241 if (dos != null) {
6242 try {
6243 dos.close();
6244 } catch (IOException e) {
6245 // TODO Auto-generated catch block
6246 e.printStackTrace();
6247 }
6248 }
6249 }
6250 }
6251
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006252 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 // In the simulator, startRunning will never have been called, which
6254 // normally sets a few crucial variables. Do it here instead.
6255 if (!Process.supportsProcesses()) {
6256 mStartRunning = true;
6257 mTopAction = Intent.ACTION_MAIN;
6258 }
6259
6260 synchronized(this) {
6261 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006262 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 return;
6264 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006265
6266 // Check to see if there are any update receivers to run.
6267 if (!mDidUpdate) {
6268 if (mWaitingUpdate) {
6269 return;
6270 }
6271 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6272 List<ResolveInfo> ris = null;
6273 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006274 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006275 intent, null, 0);
6276 } catch (RemoteException e) {
6277 }
6278 if (ris != null) {
6279 for (int i=ris.size()-1; i>=0; i--) {
6280 if ((ris.get(i).activityInfo.applicationInfo.flags
6281 &ApplicationInfo.FLAG_SYSTEM) == 0) {
6282 ris.remove(i);
6283 }
6284 }
6285 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006286
6287 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
6288
6289 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006290 for (int i=0; i<ris.size(); i++) {
6291 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006292 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6293 if (lastDoneReceivers.contains(comp)) {
6294 ris.remove(i);
6295 i--;
6296 }
6297 }
6298
6299 for (int i=0; i<ris.size(); i++) {
6300 ActivityInfo ai = ris.get(i).activityInfo;
6301 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6302 doneReceivers.add(comp);
6303 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006304 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08006305 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006306 finisher = new IIntentReceiver.Stub() {
6307 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07006308 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006309 boolean sticky) {
6310 // The raw IIntentReceiver interface is called
6311 // with the AM lock held, so redispatch to
6312 // execute our code without the lock.
6313 mHandler.post(new Runnable() {
6314 public void run() {
6315 synchronized (ActivityManagerService.this) {
6316 mDidUpdate = true;
6317 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006318 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006319 systemReady(goingCallback);
6320 }
6321 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006322 }
6323 };
6324 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006325 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006326 broadcastIntentLocked(null, null, intent, null, finisher,
6327 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackbornd6847842010-01-12 18:14:19 -08006328 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006329 mWaitingUpdate = true;
6330 }
6331 }
6332 }
6333 if (mWaitingUpdate) {
6334 return;
6335 }
6336 mDidUpdate = true;
6337 }
6338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 mSystemReady = true;
6340 if (!mStartRunning) {
6341 return;
6342 }
6343 }
6344
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006345 ArrayList<ProcessRecord> procsToKill = null;
6346 synchronized(mPidsSelfLocked) {
6347 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
6348 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
6349 if (!isAllowedWhileBooting(proc.info)){
6350 if (procsToKill == null) {
6351 procsToKill = new ArrayList<ProcessRecord>();
6352 }
6353 procsToKill.add(proc);
6354 }
6355 }
6356 }
6357
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006358 synchronized(this) {
6359 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006360 for (int i=procsToKill.size()-1; i>=0; i--) {
6361 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006362 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006363 removeProcessLocked(proc, true);
6364 }
6365 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006366
6367 // Now that we have cleaned up any update processes, we
6368 // are ready to start launching real processes and know that
6369 // we won't trample on them any more.
6370 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006371 }
6372
Joe Onorato8a9b2202010-02-26 18:56:32 -08006373 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006374 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 SystemClock.uptimeMillis());
6376
6377 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006378 // Make sure we have no pre-ready processes sitting around.
6379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
6381 ResolveInfo ri = mContext.getPackageManager()
6382 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07006383 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 CharSequence errorMsg = null;
6385 if (ri != null) {
6386 ActivityInfo ai = ri.activityInfo;
6387 ApplicationInfo app = ai.applicationInfo;
6388 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6389 mTopAction = Intent.ACTION_FACTORY_TEST;
6390 mTopData = null;
6391 mTopComponent = new ComponentName(app.packageName,
6392 ai.name);
6393 } else {
6394 errorMsg = mContext.getResources().getText(
6395 com.android.internal.R.string.factorytest_not_system);
6396 }
6397 } else {
6398 errorMsg = mContext.getResources().getText(
6399 com.android.internal.R.string.factorytest_no_action);
6400 }
6401 if (errorMsg != null) {
6402 mTopAction = null;
6403 mTopData = null;
6404 mTopComponent = null;
6405 Message msg = Message.obtain();
6406 msg.what = SHOW_FACTORY_ERROR_MSG;
6407 msg.getData().putCharSequence("msg", errorMsg);
6408 mHandler.sendMessage(msg);
6409 }
6410 }
6411 }
6412
6413 retrieveSettings();
6414
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006415 if (goingCallback != null) goingCallback.run();
6416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 synchronized (this) {
6418 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
6419 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006420 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006421 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 if (apps != null) {
6423 int N = apps.size();
6424 int i;
6425 for (i=0; i<N; i++) {
6426 ApplicationInfo info
6427 = (ApplicationInfo)apps.get(i);
6428 if (info != null &&
6429 !info.packageName.equals("android")) {
6430 addAppLocked(info);
6431 }
6432 }
6433 }
6434 } catch (RemoteException ex) {
6435 // pm is in same process, this will never happen.
6436 }
6437 }
6438
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006439 // Start up initial activity.
6440 mBooting = true;
6441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006443 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 Message msg = Message.obtain();
6445 msg.what = SHOW_UID_ERROR_MSG;
6446 mHandler.sendMessage(msg);
6447 }
6448 } catch (RemoteException e) {
6449 }
6450
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006451 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 }
6453 }
6454
Dan Egnorb7f03672009-12-09 16:22:32 -08006455 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006456 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08006458 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08006459 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006460 startAppProblemLocked(app);
6461 app.stopFreezingAllLocked();
6462 return handleAppCrashLocked(app);
6463 }
6464
Dan Egnorb7f03672009-12-09 16:22:32 -08006465 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006466 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08006468 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08006469 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
6470 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 startAppProblemLocked(app);
6472 app.stopFreezingAllLocked();
6473 }
6474
6475 /**
6476 * Generate a process error record, suitable for attachment to a ProcessRecord.
6477 *
6478 * @param app The ProcessRecord in which the error occurred.
6479 * @param condition Crashing, Application Not Responding, etc. Values are defined in
6480 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08006481 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 * @param shortMsg Short message describing the crash.
6483 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08006484 * @param stackTrace Full crash stack trace, may be null.
6485 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 * @return Returns a fully-formed AppErrorStateInfo record.
6487 */
6488 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08006489 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08006491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 report.condition = condition;
6493 report.processName = app.processName;
6494 report.pid = app.pid;
6495 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08006496 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 report.shortMsg = shortMsg;
6498 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08006499 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006500
6501 return report;
6502 }
6503
Dan Egnor42471dd2010-01-07 17:25:22 -08006504 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 synchronized (this) {
6506 app.crashing = false;
6507 app.crashingReport = null;
6508 app.notResponding = false;
6509 app.notRespondingReport = null;
6510 if (app.anrDialog == fromDialog) {
6511 app.anrDialog = null;
6512 }
6513 if (app.waitDialog == fromDialog) {
6514 app.waitDialog = null;
6515 }
6516 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08006517 handleAppCrashLocked(app);
Dianne Hackborn8633e682010-04-22 16:03:41 -07006518 Slog.i(ActivityManagerService.TAG, "Killing "
6519 + app.processName + " (pid=" + app.pid + "): user's request");
6520 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
6521 app.processName, app.setAdj, "user's request after error");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 Process.killProcess(app.pid);
6523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 }
6525 }
Dan Egnor42471dd2010-01-07 17:25:22 -08006526
Dan Egnorb7f03672009-12-09 16:22:32 -08006527 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 long now = SystemClock.uptimeMillis();
6529
6530 Long crashTime = mProcessCrashTimes.get(app.info.processName,
6531 app.info.uid);
6532 if (crashTime != null && now < crashTime+MIN_CRASH_INTERVAL) {
6533 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08006534 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006536 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 app.info.processName, app.info.uid);
6538 killServicesLocked(app, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006539 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6540 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006542 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006544 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006545 }
6546 }
6547 if (!app.persistent) {
6548 // We don't want to start this process again until the user
6549 // explicitly does so... but for persistent process, we really
6550 // need to keep it running. If a persistent process is actually
6551 // repeatedly crashing, then badness for everyone.
Doug Zongker2bec3d42009-12-04 12:52:44 -08006552 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006553 app.info.processName);
6554 mBadProcesses.put(app.info.processName, app.info.uid, now);
6555 app.bad = true;
6556 mProcessCrashTimes.remove(app.info.processName, app.info.uid);
6557 app.removed = true;
6558 removeProcessLocked(app, false);
6559 return false;
6560 }
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006561 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006562 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006563 if (r.app == app) {
6564 // If the top running activity is from this crashing
6565 // process, then terminate it to avoid getting in a loop.
6566 Slog.w(TAG, " Force finishing activity "
6567 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006568 int index = mMainStack.indexOfTokenLocked(r);
6569 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006570 Activity.RESULT_CANCELED, null, "crashed");
6571 // Also terminate an activities below it that aren't yet
6572 // stopped, to avoid a situation where one will get
6573 // re-start our crashing activity once it gets resumed again.
6574 index--;
6575 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006576 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006577 if (r.state == ActivityState.RESUMED
6578 || r.state == ActivityState.PAUSING
6579 || r.state == ActivityState.PAUSED) {
6580 if (!r.isHomeActivity) {
6581 Slog.w(TAG, " Force finishing activity "
6582 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006583 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006584 Activity.RESULT_CANCELED, null, "crashed");
6585 }
6586 }
6587 }
6588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 }
6590
6591 // Bump up the crash count of any services currently running in the proc.
6592 if (app.services.size() != 0) {
6593 // Any services running in the application need to be placed
6594 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07006595 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07006597 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 sr.crashCount++;
6599 }
6600 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02006601
6602 // If the crashing process is what we consider to be the "home process" and it has been
6603 // replaced by a third-party app, clear the package preferred activities from packages
6604 // with a home activity running in the process to prevent a repeatedly crashing app
6605 // from blocking the user to manually clear the list.
6606 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
6607 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
6608 Iterator it = mHomeProcess.activities.iterator();
6609 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07006610 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02006611 if (r.isHomeActivity) {
6612 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
6613 try {
6614 ActivityThread.getPackageManager()
6615 .clearPackagePreferredActivities(r.packageName);
6616 } catch (RemoteException c) {
6617 // pm is in same process, this will never happen.
6618 }
6619 }
6620 }
6621 }
6622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006623 mProcessCrashTimes.put(app.info.processName, app.info.uid, now);
6624 return true;
6625 }
6626
6627 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006628 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
6629 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 skipCurrentReceiverLocked(app);
6631 }
6632
6633 void skipCurrentReceiverLocked(ProcessRecord app) {
6634 boolean reschedule = false;
6635 BroadcastRecord r = app.curReceiver;
6636 if (r != null) {
6637 // The current broadcast is waiting for this app's receiver
6638 // to be finished. Looks like that's not going to happen, so
6639 // let the broadcast continue.
Jeff Brown4d94a762010-09-23 11:33:28 -07006640 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
6642 r.resultExtras, r.resultAbort, true);
6643 reschedule = true;
6644 }
6645 r = mPendingBroadcast;
6646 if (r != null && r.curApp == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006647 if (DEBUG_BROADCAST) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 "skip & discard pending app " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -07006649 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
6651 r.resultExtras, r.resultAbort, true);
6652 reschedule = true;
6653 }
6654 if (reschedule) {
6655 scheduleBroadcastsLocked();
6656 }
6657 }
6658
Dan Egnor60d87622009-12-16 16:32:58 -08006659 /**
6660 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
6661 * The application process will exit immediately after this call returns.
6662 * @param app object of the crashing app, null for the system server
6663 * @param crashInfo describing the exception
6664 */
6665 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
6666 ProcessRecord r = findAppProcess(app);
6667
6668 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
6669 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08006670 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08006671 crashInfo.exceptionClassName,
6672 crashInfo.exceptionMessage,
6673 crashInfo.throwFileName,
6674 crashInfo.throwLineNumber);
6675
Dan Egnor42471dd2010-01-07 17:25:22 -08006676 addErrorToDropBox("crash", r, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08006677
6678 crashApplication(r, crashInfo);
6679 }
6680
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006681 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006682 IBinder app,
6683 int violationMask,
6684 StrictMode.ViolationInfo info) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006685 ProcessRecord r = findAppProcess(app);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006686
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006687 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08006688 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006689 boolean logIt = true;
6690 synchronized (mAlreadyLoggedViolatedStacks) {
6691 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
6692 logIt = false;
6693 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006694 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006695 // the relative pain numbers, without logging all
6696 // the stack traces repeatedly. We'd want to do
6697 // likewise in the client code, which also does
6698 // dup suppression, before the Binder call.
6699 } else {
6700 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
6701 mAlreadyLoggedViolatedStacks.clear();
6702 }
6703 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
6704 }
6705 }
6706 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006707 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006708 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006709 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006710
6711 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
6712 AppErrorResult result = new AppErrorResult();
6713 synchronized (this) {
6714 final long origId = Binder.clearCallingIdentity();
6715
6716 Message msg = Message.obtain();
6717 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
6718 HashMap<String, Object> data = new HashMap<String, Object>();
6719 data.put("result", result);
6720 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006721 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006722 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006723 msg.obj = data;
6724 mHandler.sendMessage(msg);
6725
6726 Binder.restoreCallingIdentity(origId);
6727 }
6728 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07006729 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006730 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006731 }
6732
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006733 // Depending on the policy in effect, there could be a bunch of
6734 // these in quick succession so we try to batch these together to
6735 // minimize disk writes, number of dropbox entries, and maximize
6736 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006737 private void logStrictModeViolationToDropBox(
6738 ProcessRecord process,
6739 StrictMode.ViolationInfo info) {
6740 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006741 return;
6742 }
6743 final boolean isSystemApp = process == null ||
6744 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
6745 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
6746 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
6747 final DropBoxManager dbox = (DropBoxManager)
6748 mContext.getSystemService(Context.DROPBOX_SERVICE);
6749
6750 // Exit early if the dropbox isn't configured to accept this report type.
6751 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
6752
6753 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006754 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006755 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
6756 synchronized (sb) {
6757 bufferWasEmpty = sb.length() == 0;
6758 appendDropBoxProcessHeaders(process, sb);
6759 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
6760 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006761 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
6762 if (info.violationNumThisLoop != 0) {
6763 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
6764 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07006765 if (info.numAnimationsRunning != 0) {
6766 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
6767 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07006768 if (info.broadcastIntentAction != null) {
6769 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
6770 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08006771 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006772 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006773 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08006774 if (info.tags != null) {
6775 for (String tag : info.tags) {
6776 sb.append("Span-Tag: ").append(tag).append("\n");
6777 }
6778 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006779 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07006780 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
6781 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006782 }
6783 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006784
6785 // Only buffer up to ~64k. Various logging bits truncate
6786 // things at 128k.
6787 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006788 }
6789
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006790 // Flush immediately if the buffer's grown too large, or this
6791 // is a non-system app. Non-system apps are isolated with a
6792 // different tag & policy and not batched.
6793 //
6794 // Batching is useful during internal testing with
6795 // StrictMode settings turned up high. Without batching,
6796 // thousands of separate files could be created on boot.
6797 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006798 new Thread("Error dump: " + dropboxTag) {
6799 @Override
6800 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006801 String report;
6802 synchronized (sb) {
6803 report = sb.toString();
6804 sb.delete(0, sb.length());
6805 sb.trimToSize();
6806 }
6807 if (report.length() != 0) {
6808 dbox.addText(dropboxTag, report);
6809 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006810 }
6811 }.start();
6812 return;
6813 }
6814
6815 // System app batching:
6816 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006817 // An existing dropbox-writing thread is outstanding, so
6818 // we don't need to start it up. The existing thread will
6819 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006820 return;
6821 }
6822
6823 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
6824 // (After this point, we shouldn't access AMS internal data structures.)
6825 new Thread("Error dump: " + dropboxTag) {
6826 @Override
6827 public void run() {
6828 // 5 second sleep to let stacks arrive and be batched together
6829 try {
6830 Thread.sleep(5000); // 5 seconds
6831 } catch (InterruptedException e) {}
6832
6833 String errorReport;
6834 synchronized (mStrictModeBuffer) {
6835 errorReport = mStrictModeBuffer.toString();
6836 if (errorReport.length() == 0) {
6837 return;
6838 }
6839 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
6840 mStrictModeBuffer.trimToSize();
6841 }
6842 dbox.addText(dropboxTag, errorReport);
6843 }
6844 }.start();
6845 }
6846
Dan Egnor60d87622009-12-16 16:32:58 -08006847 /**
6848 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
6849 * @param app object of the crashing app, null for the system server
6850 * @param tag reported by the caller
6851 * @param crashInfo describing the context of the error
6852 * @return true if the process should exit immediately (WTF is fatal)
6853 */
6854 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08006855 ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnor60d87622009-12-16 16:32:58 -08006856 ProcessRecord r = findAppProcess(app);
6857
6858 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
6859 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08006860 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08006861 tag, crashInfo.exceptionMessage);
6862
Dan Egnor42471dd2010-01-07 17:25:22 -08006863 addErrorToDropBox("wtf", r, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08006864
Doug Zongker43866e02010-01-07 12:09:54 -08006865 if (Settings.Secure.getInt(mContext.getContentResolver(),
6866 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08006867 crashApplication(r, crashInfo);
6868 return true;
6869 } else {
6870 return false;
6871 }
6872 }
6873
6874 /**
6875 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
6876 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
6877 */
6878 private ProcessRecord findAppProcess(IBinder app) {
6879 if (app == null) {
6880 return null;
6881 }
6882
6883 synchronized (this) {
6884 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
6885 final int NA = apps.size();
6886 for (int ia=0; ia<NA; ia++) {
6887 ProcessRecord p = apps.valueAt(ia);
6888 if (p.thread != null && p.thread.asBinder() == app) {
6889 return p;
6890 }
6891 }
6892 }
6893
Joe Onorato8a9b2202010-02-26 18:56:32 -08006894 Slog.w(TAG, "Can't find mystery application: " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08006895 return null;
6896 }
6897 }
6898
6899 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006900 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
6901 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08006902 */
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07006903 private void appendDropBoxProcessHeaders(ProcessRecord process, StringBuilder sb) {
6904 // Note: ProcessRecord 'process' is guarded by the service
6905 // instance. (notably process.pkgList, which could otherwise change
6906 // concurrently during execution of this method)
6907 synchronized (this) {
6908 if (process == null || process.pid == MY_PID) {
6909 sb.append("Process: system_server\n");
6910 } else {
6911 sb.append("Process: ").append(process.processName).append("\n");
6912 }
6913 if (process == null) {
6914 return;
6915 }
Dan Egnora455d192010-03-12 08:52:28 -08006916 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006917 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08006918 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
6919 for (String pkg : process.pkgList) {
6920 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08006921 try {
Dan Egnora455d192010-03-12 08:52:28 -08006922 PackageInfo pi = pm.getPackageInfo(pkg, 0);
6923 if (pi != null) {
6924 sb.append(" v").append(pi.versionCode);
6925 if (pi.versionName != null) {
6926 sb.append(" (").append(pi.versionName).append(")");
6927 }
6928 }
6929 } catch (RemoteException e) {
6930 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08006931 }
Dan Egnora455d192010-03-12 08:52:28 -08006932 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08006933 }
Dan Egnora455d192010-03-12 08:52:28 -08006934 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006935 }
6936
6937 private static String processClass(ProcessRecord process) {
6938 if (process == null || process.pid == MY_PID) {
6939 return "system_server";
6940 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6941 return "system_app";
6942 } else {
6943 return "data_app";
6944 }
6945 }
6946
6947 /**
6948 * Write a description of an error (crash, WTF, ANR) to the drop box.
6949 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
6950 * @param process which caused the error, null means the system server
6951 * @param activity which triggered the error, null if unknown
6952 * @param parent activity related to the error, null if unknown
6953 * @param subject line related to the error, null if absent
6954 * @param report in long form describing the error, null if absent
6955 * @param logFile to include in the report, null if none
6956 * @param crashInfo giving an application stack trace, null if absent
6957 */
6958 public void addErrorToDropBox(String eventType,
6959 ProcessRecord process, ActivityRecord activity, ActivityRecord parent, String subject,
6960 final String report, final File logFile,
6961 final ApplicationErrorReport.CrashInfo crashInfo) {
6962 // NOTE -- this must never acquire the ActivityManagerService lock,
6963 // otherwise the watchdog may be prevented from resetting the system.
6964
6965 final String dropboxTag = processClass(process) + "_" + eventType;
6966 final DropBoxManager dbox = (DropBoxManager)
6967 mContext.getSystemService(Context.DROPBOX_SERVICE);
6968
6969 // Exit early if the dropbox isn't configured to accept this report type.
6970 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
6971
6972 final StringBuilder sb = new StringBuilder(1024);
6973 appendDropBoxProcessHeaders(process, sb);
Dan Egnora455d192010-03-12 08:52:28 -08006974 if (activity != null) {
6975 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
6976 }
6977 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
6978 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
6979 }
6980 if (parent != null && parent != activity) {
6981 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
6982 }
6983 if (subject != null) {
6984 sb.append("Subject: ").append(subject).append("\n");
6985 }
6986 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02006987 if (Debug.isDebuggerConnected()) {
6988 sb.append("Debugger: Connected\n");
6989 }
Dan Egnora455d192010-03-12 08:52:28 -08006990 sb.append("\n");
6991
6992 // Do the rest in a worker thread to avoid blocking the caller on I/O
6993 // (After this point, we shouldn't access AMS internal data structures.)
6994 Thread worker = new Thread("Error dump: " + dropboxTag) {
6995 @Override
6996 public void run() {
6997 if (report != null) {
6998 sb.append(report);
6999 }
7000 if (logFile != null) {
7001 try {
7002 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7003 } catch (IOException e) {
7004 Slog.e(TAG, "Error reading " + logFile, e);
7005 }
7006 }
7007 if (crashInfo != null && crashInfo.stackTrace != null) {
7008 sb.append(crashInfo.stackTrace);
7009 }
7010
7011 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7012 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7013 if (lines > 0) {
7014 sb.append("\n");
7015
7016 // Merge several logcat streams, and take the last N lines
7017 InputStreamReader input = null;
7018 try {
7019 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7020 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7021 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7022
7023 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7024 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7025 input = new InputStreamReader(logcat.getInputStream());
7026
7027 int num;
7028 char[] buf = new char[8192];
7029 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7030 } catch (IOException e) {
7031 Slog.e(TAG, "Error running logcat", e);
7032 } finally {
7033 if (input != null) try { input.close(); } catch (IOException e) {}
7034 }
7035 }
7036
7037 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007038 }
Dan Egnora455d192010-03-12 08:52:28 -08007039 };
7040
7041 if (process == null || process.pid == MY_PID) {
7042 worker.run(); // We may be about to die -- need to run this synchronously
7043 } else {
7044 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007045 }
7046 }
7047
7048 /**
7049 * Bring up the "unexpected error" dialog box for a crashing app.
7050 * Deal with edge cases (intercepts from instrumented applications,
7051 * ActivityController, error intent receivers, that sort of thing).
7052 * @param r the application crashing
7053 * @param crashInfo describing the failure
7054 */
7055 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007056 long timeMillis = System.currentTimeMillis();
7057 String shortMsg = crashInfo.exceptionClassName;
7058 String longMsg = crashInfo.exceptionMessage;
7059 String stackTrace = crashInfo.stackTrace;
7060 if (shortMsg != null && longMsg != null) {
7061 longMsg = shortMsg + ": " + longMsg;
7062 } else if (shortMsg != null) {
7063 longMsg = shortMsg;
7064 }
7065
Dan Egnor60d87622009-12-16 16:32:58 -08007066 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007067 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007068 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007069 try {
7070 String name = r != null ? r.processName : null;
7071 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007072 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007073 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007074 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007075 + " at watcher's request");
7076 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007077 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007078 }
7079 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007080 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 }
7082 }
7083
7084 final long origId = Binder.clearCallingIdentity();
7085
7086 // If this process is running instrumentation, finish it.
7087 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007088 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007089 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007090 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7091 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 Bundle info = new Bundle();
7093 info.putString("shortMsg", shortMsg);
7094 info.putString("longMsg", longMsg);
7095 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7096 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007097 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007098 }
7099
Dan Egnor60d87622009-12-16 16:32:58 -08007100 // If we can't identify the process or it's already exceeded its crash quota,
7101 // quit right away without showing a crash dialog.
7102 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007104 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007105 }
7106
7107 Message msg = Message.obtain();
7108 msg.what = SHOW_ERROR_MSG;
7109 HashMap data = new HashMap();
7110 data.put("result", result);
7111 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007112 msg.obj = data;
7113 mHandler.sendMessage(msg);
7114
7115 Binder.restoreCallingIdentity(origId);
7116 }
7117
7118 int res = result.get();
7119
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007120 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007121 synchronized (this) {
7122 if (r != null) {
7123 mProcessCrashTimes.put(r.info.processName, r.info.uid,
7124 SystemClock.uptimeMillis());
7125 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007126 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007127 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007128 }
7129 }
7130
7131 if (appErrorIntent != null) {
7132 try {
7133 mContext.startActivity(appErrorIntent);
7134 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007135 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007138 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007139
7140 Intent createAppErrorIntentLocked(ProcessRecord r,
7141 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7142 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007143 if (report == null) {
7144 return null;
7145 }
7146 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7147 result.setComponent(r.errorReportReceiver);
7148 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7149 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7150 return result;
7151 }
7152
Dan Egnorb7f03672009-12-09 16:22:32 -08007153 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7154 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007155 if (r.errorReportReceiver == null) {
7156 return null;
7157 }
7158
7159 if (!r.crashing && !r.notResponding) {
7160 return null;
7161 }
7162
Dan Egnorb7f03672009-12-09 16:22:32 -08007163 ApplicationErrorReport report = new ApplicationErrorReport();
7164 report.packageName = r.info.packageName;
7165 report.installerPackageName = r.errorReportReceiver.getPackageName();
7166 report.processName = r.processName;
7167 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007168 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007169
Dan Egnorb7f03672009-12-09 16:22:32 -08007170 if (r.crashing) {
7171 report.type = ApplicationErrorReport.TYPE_CRASH;
7172 report.crashInfo = crashInfo;
7173 } else if (r.notResponding) {
7174 report.type = ApplicationErrorReport.TYPE_ANR;
7175 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007176
Dan Egnorb7f03672009-12-09 16:22:32 -08007177 report.anrInfo.activity = r.notRespondingReport.tag;
7178 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7179 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007180 }
7181
Dan Egnorb7f03672009-12-09 16:22:32 -08007182 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007183 }
7184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007185 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
7186 // assume our apps are happy - lazy create the list
7187 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7188
7189 synchronized (this) {
7190
7191 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007192 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7193 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007194 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7195 // This one's in trouble, so we'll generate a report for it
7196 // crashes are higher priority (in case there's a crash *and* an anr)
7197 ActivityManager.ProcessErrorStateInfo report = null;
7198 if (app.crashing) {
7199 report = app.crashingReport;
7200 } else if (app.notResponding) {
7201 report = app.notRespondingReport;
7202 }
7203
7204 if (report != null) {
7205 if (errList == null) {
7206 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
7207 }
7208 errList.add(report);
7209 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007210 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 " crashing = " + app.crashing +
7212 " notResponding = " + app.notResponding);
7213 }
7214 }
7215 }
7216 }
7217
7218 return errList;
7219 }
7220
7221 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
7222 // Lazy instantiation of list
7223 List<ActivityManager.RunningAppProcessInfo> runList = null;
7224 synchronized (this) {
7225 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007226 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7227 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007228 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
7229 // Generate process state info for running application
7230 ActivityManager.RunningAppProcessInfo currApp =
7231 new ActivityManager.RunningAppProcessInfo(app.processName,
7232 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07007233 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007234 if (mHeavyWeightProcess == app) {
Dianne Hackborn482566e2010-09-03 12:51:28 -07007235 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007236 }
Dianne Hackborn42499172010-10-15 18:45:07 -07007237 if (app.persistent) {
7238 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
7239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007240 int adj = app.curAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007241 if (adj >= EMPTY_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007242 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY;
7243 } else if (adj >= HIDDEN_APP_MIN_ADJ) {
7244 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
The Android Open Source Project4df24232009-03-05 14:34:35 -08007245 currApp.lru = adj - HIDDEN_APP_MIN_ADJ + 1;
7246 } else if (adj >= HOME_APP_ADJ) {
7247 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
7248 currApp.lru = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007249 } else if (adj >= SECONDARY_SERVER_ADJ) {
7250 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07007251 } else if (adj >= HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackborn5383f502010-10-22 12:59:20 -07007252 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07007253 } else if (adj >= PERCEPTIBLE_APP_ADJ) {
7254 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 } else if (adj >= VISIBLE_APP_ADJ) {
7256 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
7257 } else {
7258 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
7259 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007260 currApp.importanceReasonCode = app.adjTypeCode;
7261 if (app.adjSource instanceof ProcessRecord) {
7262 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007263 } else if (app.adjSource instanceof ActivityRecord) {
7264 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007265 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
7266 }
7267 if (app.adjTarget instanceof ComponentName) {
7268 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
7269 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007270 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007271 // + " lru=" + currApp.lru);
7272 if (runList == null) {
7273 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
7274 }
7275 runList.add(currApp);
7276 }
7277 }
7278 }
7279 return runList;
7280 }
7281
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007282 public List<ApplicationInfo> getRunningExternalApplications() {
7283 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
7284 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
7285 if (runningApps != null && runningApps.size() > 0) {
7286 Set<String> extList = new HashSet<String>();
7287 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
7288 if (app.pkgList != null) {
7289 for (String pkg : app.pkgList) {
7290 extList.add(pkg);
7291 }
7292 }
7293 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007294 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007295 for (String pkg : extList) {
7296 try {
7297 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
7298 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
7299 retList.add(info);
7300 }
7301 } catch (RemoteException e) {
7302 }
7303 }
7304 }
7305 return retList;
7306 }
7307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007308 @Override
7309 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007310 if (checkCallingPermission(android.Manifest.permission.DUMP)
7311 != PackageManager.PERMISSION_GRANTED) {
7312 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7313 + Binder.getCallingPid()
7314 + ", uid=" + Binder.getCallingUid()
7315 + " without permission "
7316 + android.Manifest.permission.DUMP);
7317 return;
7318 }
7319
7320 boolean dumpAll = false;
7321
7322 int opti = 0;
7323 while (opti < args.length) {
7324 String opt = args[opti];
7325 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7326 break;
7327 }
7328 opti++;
7329 if ("-a".equals(opt)) {
7330 dumpAll = true;
7331 } else if ("-h".equals(opt)) {
7332 pw.println("Activity manager dump options:");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007333 pw.println(" [-a] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007334 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07007335 pw.println(" a[ctivities]: activity stack state");
7336 pw.println(" b[roadcasts]: broadcast state");
7337 pw.println(" i[ntents]: pending intent state");
7338 pw.println(" p[rocesses]: process state");
7339 pw.println(" o[om]: out of memory management");
7340 pw.println(" prov[iders]: content provider state");
7341 pw.println(" s[ervices]: service state");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007342 pw.println(" service [name]: service client-side state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007343 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007344 } else {
7345 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007346 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007347 }
7348
7349 // Is the caller requesting to dump a particular piece of data?
7350 if (opti < args.length) {
7351 String cmd = args[opti];
7352 opti++;
7353 if ("activities".equals(cmd) || "a".equals(cmd)) {
7354 synchronized (this) {
7355 dumpActivitiesLocked(fd, pw, args, opti, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007356 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007357 return;
7358 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
7359 synchronized (this) {
7360 dumpBroadcastsLocked(fd, pw, args, opti, true);
7361 }
7362 return;
7363 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
7364 synchronized (this) {
7365 dumpPendingIntentsLocked(fd, pw, args, opti, true);
7366 }
7367 return;
7368 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
7369 synchronized (this) {
7370 dumpProcessesLocked(fd, pw, args, opti, true);
7371 }
7372 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07007373 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
7374 synchronized (this) {
7375 dumpOomLocked(fd, pw, args, opti, true);
7376 }
7377 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007378 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
7379 synchronized (this) {
7380 dumpProvidersLocked(fd, pw, args, opti, true);
7381 }
7382 return;
7383 } else if ("service".equals(cmd)) {
Joe Onoratoeb95b082010-10-21 14:54:19 -04007384 dumpService(fd, pw, args, opti);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007385 return;
7386 } else if ("services".equals(cmd) || "s".equals(cmd)) {
7387 synchronized (this) {
7388 dumpServicesLocked(fd, pw, args, opti, true);
7389 }
7390 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07007391 } else {
7392 // Dumping a single activity?
7393 if (dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
7394 return;
7395 }
7396 pw.println("Bad activity command: " + cmd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007398 }
7399
7400 // No piece of data specified, dump everything.
7401 synchronized (this) {
7402 boolean needSep;
7403 if (dumpAll) {
7404 pw.println("Providers in Current Activity Manager State:");
7405 }
7406 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll);
7407 if (needSep) {
7408 pw.println(" ");
7409 }
7410 if (dumpAll) {
7411 pw.println("-------------------------------------------------------------------------------");
7412 pw.println("Broadcasts in Current Activity Manager State:");
7413 }
7414 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll);
7415 if (needSep) {
7416 pw.println(" ");
7417 }
7418 if (dumpAll) {
7419 pw.println("-------------------------------------------------------------------------------");
7420 pw.println("Services in Current Activity Manager State:");
7421 }
7422 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll);
7423 if (needSep) {
7424 pw.println(" ");
7425 }
7426 if (dumpAll) {
7427 pw.println("-------------------------------------------------------------------------------");
7428 pw.println("PendingIntents in Current Activity Manager State:");
7429 }
7430 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll);
7431 if (needSep) {
7432 pw.println(" ");
7433 }
7434 if (dumpAll) {
7435 pw.println("-------------------------------------------------------------------------------");
7436 pw.println("Activities in Current Activity Manager State:");
7437 }
7438 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, !dumpAll);
7439 if (needSep) {
7440 pw.println(" ");
7441 }
7442 if (dumpAll) {
7443 pw.println("-------------------------------------------------------------------------------");
7444 pw.println("Processes in Current Activity Manager State:");
7445 }
7446 dumpProcessesLocked(fd, pw, args, opti, dumpAll);
7447 }
7448 }
7449
7450 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7451 int opti, boolean dumpAll, boolean needHeader) {
7452 if (needHeader) {
7453 pw.println(" Activity stack:");
7454 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007455 dumpHistoryList(pw, mMainStack.mHistory, " ", "Hist", true);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007456 pw.println(" ");
7457 pw.println(" Running activities (most recent first):");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007458 dumpHistoryList(pw, mMainStack.mLRUActivities, " ", "Run", false);
7459 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007460 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007461 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007462 dumpHistoryList(pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007463 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007464 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007465 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007466 pw.println(" Activities waiting to stop:");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007467 dumpHistoryList(pw, mMainStack.mStoppingActivities, " ", "Stop", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007468 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007469 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007470 pw.println(" ");
7471 pw.println(" Activities waiting to finish:");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007472 dumpHistoryList(pw, mMainStack.mFinishingActivities, " ", "Fin", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007475 pw.println(" ");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007476 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
7477 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007478 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007479 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007481 if (dumpAll && mRecentTasks.size() > 0) {
7482 pw.println(" ");
7483 pw.println("Recent tasks in Current Activity Manager State:");
7484
7485 final int N = mRecentTasks.size();
7486 for (int i=0; i<N; i++) {
7487 TaskRecord tr = mRecentTasks.get(i);
7488 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
7489 pw.println(tr);
7490 mRecentTasks.get(i).dump(pw, " ");
7491 }
7492 }
7493
7494 pw.println(" ");
7495 pw.println(" mCurTask: " + mCurTask);
7496
7497 return true;
7498 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07007499
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007500 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7501 int opti, boolean dumpAll) {
7502 boolean needSep = false;
7503 int numPers = 0;
7504
7505 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
7507 final int NA = procs.size();
7508 for (int ia=0; ia<NA; ia++) {
7509 if (!needSep) {
7510 pw.println(" All known processes:");
7511 needSep = true;
7512 }
7513 ProcessRecord r = procs.valueAt(ia);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007514 pw.print(r.persistent ? " *PERS*" : " *APP*");
7515 pw.print(" UID "); pw.print(procs.keyAt(ia));
7516 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007517 r.dump(pw, " ");
7518 if (r.persistent) {
7519 numPers++;
7520 }
7521 }
7522 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007523 }
7524
7525 if (mLruProcesses.size() > 0) {
7526 if (needSep) pw.println(" ");
7527 needSep = true;
7528 pw.println(" Running processes (most recent first):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07007529 dumpProcessOomList(pw, this, mLruProcesses, " ",
7530 "Proc", "PERS", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007531 needSep = true;
7532 }
7533
7534 synchronized (mPidsSelfLocked) {
7535 if (mPidsSelfLocked.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 if (needSep) pw.println(" ");
7537 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007538 pw.println(" PID mappings:");
7539 for (int i=0; i<mPidsSelfLocked.size(); i++) {
7540 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
7541 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 }
7543 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007544 }
7545
7546 if (mForegroundProcesses.size() > 0) {
7547 if (needSep) pw.println(" ");
7548 needSep = true;
7549 pw.println(" Foreground Processes:");
7550 for (int i=0; i<mForegroundProcesses.size(); i++) {
7551 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
7552 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007553 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007554 }
7555
7556 if (mPersistentStartingProcesses.size() > 0) {
7557 if (needSep) pw.println(" ");
7558 needSep = true;
7559 pw.println(" Persisent processes that are starting:");
7560 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007561 "Starting Norm", "Restarting PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007563
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007564 if (mStartingProcesses.size() > 0) {
7565 if (needSep) pw.println(" ");
7566 needSep = true;
7567 pw.println(" Processes that are starting:");
7568 dumpProcessList(pw, this, mStartingProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007569 "Starting Norm", "Starting PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007571
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007572 if (mRemovedProcesses.size() > 0) {
7573 if (needSep) pw.println(" ");
7574 needSep = true;
7575 pw.println(" Processes that are being removed:");
7576 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007577 "Removed Norm", "Removed PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007578 }
7579
7580 if (mProcessesOnHold.size() > 0) {
7581 if (needSep) pw.println(" ");
7582 needSep = true;
7583 pw.println(" Processes that are on old until the system is ready:");
7584 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackborn287952c2010-09-22 22:34:31 -07007585 "OnHold Norm", "OnHold PERS");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587
Dianne Hackborn287952c2010-09-22 22:34:31 -07007588 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007589
7590 if (mProcessCrashTimes.getMap().size() > 0) {
7591 if (needSep) pw.println(" ");
7592 needSep = true;
7593 pw.println(" Time since processes crashed:");
7594 long now = SystemClock.uptimeMillis();
7595 for (Map.Entry<String, SparseArray<Long>> procs
7596 : mProcessCrashTimes.getMap().entrySet()) {
7597 SparseArray<Long> uids = procs.getValue();
7598 final int N = uids.size();
7599 for (int i=0; i<N; i++) {
7600 pw.print(" Process "); pw.print(procs.getKey());
7601 pw.print(" uid "); pw.print(uids.keyAt(i));
7602 pw.print(": last crashed ");
7603 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07007604 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07007605 }
7606 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007609 if (mBadProcesses.getMap().size() > 0) {
7610 if (needSep) pw.println(" ");
7611 needSep = true;
7612 pw.println(" Bad processes:");
7613 for (Map.Entry<String, SparseArray<Long>> procs
7614 : mBadProcesses.getMap().entrySet()) {
7615 SparseArray<Long> uids = procs.getValue();
7616 final int N = uids.size();
7617 for (int i=0; i<N; i++) {
7618 pw.print(" Bad process "); pw.print(procs.getKey());
7619 pw.print(" uid "); pw.print(uids.keyAt(i));
7620 pw.print(": crashed at time ");
7621 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007622 }
7623 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007625
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007626 pw.println(" ");
7627 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackborn860755f2010-06-03 18:47:52 -07007628 if (mHeavyWeightProcess != null) {
7629 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7630 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007631 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007632 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007633 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
7634 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
7635 || mOrigWaitForDebugger) {
7636 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
7637 + " mDebugTransient=" + mDebugTransient
7638 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
7639 }
7640 if (mAlwaysFinishActivities || mController != null) {
7641 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
7642 + " mController=" + mController);
7643 }
7644 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007646 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07007647 + " mProcessesReady=" + mProcessesReady
7648 + " mSystemReady=" + mSystemReady);
7649 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007650 + " mBooted=" + mBooted
7651 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07007652 pw.print(" mLastPowerCheckRealtime=");
7653 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
7654 pw.println("");
7655 pw.print(" mLastPowerCheckUptime=");
7656 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
7657 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007658 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
7659 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07007660 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007661 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007662
7663 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007664 }
7665
Dianne Hackborn287952c2010-09-22 22:34:31 -07007666 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
7667 int opti, boolean needSep, boolean dumpAll) {
7668 if (mProcessesToGc.size() > 0) {
7669 if (needSep) pw.println(" ");
7670 needSep = true;
7671 pw.println(" Processes that are waiting to GC:");
7672 long now = SystemClock.uptimeMillis();
7673 for (int i=0; i<mProcessesToGc.size(); i++) {
7674 ProcessRecord proc = mProcessesToGc.get(i);
7675 pw.print(" Process "); pw.println(proc);
7676 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
7677 pw.print(", last gced=");
7678 pw.print(now-proc.lastRequestedGc);
7679 pw.print(" ms ago, last lowMem=");
7680 pw.print(now-proc.lastLowMemory);
7681 pw.println(" ms ago");
7682
7683 }
7684 }
7685 return needSep;
7686 }
7687
7688 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7689 int opti, boolean dumpAll) {
7690 boolean needSep = false;
7691
7692 if (mLruProcesses.size() > 0) {
7693 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(mLruProcesses);
7694
7695 Comparator<ProcessRecord> comparator = new Comparator<ProcessRecord>() {
7696 @Override
7697 public int compare(ProcessRecord object1, ProcessRecord object2) {
7698 if (object1.setAdj != object2.setAdj) {
7699 return object1.setAdj > object2.setAdj ? -1 : 1;
7700 }
7701 if (object1.setSchedGroup != object2.setSchedGroup) {
7702 return object1.setSchedGroup > object2.setSchedGroup ? -1 : 1;
7703 }
7704 if (object1.keeping != object2.keeping) {
7705 return object1.keeping ? -1 : 1;
7706 }
7707 if (object1.pid != object2.pid) {
7708 return object1.pid > object2.pid ? -1 : 1;
7709 }
7710 return 0;
7711 }
7712 };
7713
7714 Collections.sort(procs, comparator);
7715
7716 if (needSep) pw.println(" ");
7717 needSep = true;
7718 pw.println(" Process OOM control:");
7719 dumpProcessOomList(pw, this, procs, " ",
7720 "Proc", "PERS", true);
7721 needSep = true;
7722 }
7723
7724 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll);
7725
7726 pw.println(" ");
7727 pw.println(" mHomeProcess: " + mHomeProcess);
7728 if (mHeavyWeightProcess != null) {
7729 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7730 }
7731
7732 return true;
7733 }
7734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 /**
7736 * There are three ways to call this:
7737 * - no service specified: dump all the services
7738 * - a flattened component name that matched an existing service was specified as the
7739 * first arg: dump that one service
7740 * - the first arg isn't the flattened component name of an existing service:
7741 * dump all services whose component contains the first arg as a substring
7742 */
Joe Onoratoeb95b082010-10-21 14:54:19 -04007743 protected void dumpService(FileDescriptor fd, PrintWriter pw, String[] args, int opti) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007744 String[] newArgs;
7745 String componentNameString;
7746 ServiceRecord r;
Kenny Root3619b9ab2010-02-13 10:05:42 -08007747 if (opti >= args.length) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 componentNameString = null;
7749 newArgs = EMPTY_STRING_ARRAY;
7750 r = null;
7751 } else {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007752 componentNameString = args[opti];
7753 opti++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007754 ComponentName componentName = ComponentName.unflattenFromString(componentNameString);
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007755 synchronized (this) {
7756 r = componentName != null ? mServices.get(componentName) : null;
7757 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007758 newArgs = new String[args.length - opti];
7759 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007760 }
7761
7762 if (r != null) {
Joe Onoratoeb95b082010-10-21 14:54:19 -04007763 dumpService(fd, pw, r, newArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 } else {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007765 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
7766 synchronized (this) {
7767 for (ServiceRecord r1 : mServices.values()) {
7768 if (componentNameString == null
7769 || r1.name.flattenToString().contains(componentNameString)) {
7770 services.add(r1);
7771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772 }
7773 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007774 for (int i=0; i<services.size(); i++) {
Joe Onoratoeb95b082010-10-21 14:54:19 -04007775 dumpService(fd, pw, services.get(i), newArgs);
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007777 }
7778 }
7779
7780 /**
7781 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
7782 * there is a thread associated with the service.
7783 */
Joe Onoratoeb95b082010-10-21 14:54:19 -04007784 private void dumpService(FileDescriptor fd, PrintWriter pw, ServiceRecord r, String[] args) {
7785 pw.println("------------------------------------------------------------"
7786 + "-------------------");
7787 pw.println("APP SERVICE: " + r.name.flattenToString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 if (r.app != null && r.app.thread != null) {
7789 try {
7790 // flush anything that is already in the PrintWriter since the thread is going
7791 // to write to the file descriptor directly
7792 pw.flush();
7793 r.app.thread.dumpService(fd, r, args);
7794 pw.print("\n");
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007795 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007796 } catch (RemoteException e) {
7797 pw.println("got a RemoteException while dumping the service");
7798 }
7799 }
7800 }
7801
Dianne Hackborn625ac272010-09-17 18:29:22 -07007802 /**
7803 * There are three things that cmd can be:
7804 * - a flattened component name that matched an existing activity
7805 * - the cmd arg isn't the flattened component name of an existing activity:
7806 * dump all activity whose component contains the cmd as a substring
7807 * - A hex number of the ActivityRecord object instance.
7808 */
7809 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
7810 int opti, boolean dumpAll) {
7811 String[] newArgs;
7812 ComponentName componentName = ComponentName.unflattenFromString(name);
7813 int objectId = 0;
7814 try {
7815 objectId = Integer.parseInt(name, 16);
7816 name = null;
7817 componentName = null;
7818 } catch (RuntimeException e) {
7819 }
7820 newArgs = new String[args.length - opti];
7821 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
7822
7823 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
7824 synchronized (this) {
7825 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
7826 if (componentName != null) {
7827 if (r1.intent.getComponent().equals(componentName)) {
7828 activities.add(r1);
7829 }
7830 } else if (name != null) {
7831 if (r1.intent.getComponent().flattenToString().contains(name)) {
7832 activities.add(r1);
7833 }
7834 } else if (System.identityHashCode(this) == objectId) {
7835 activities.add(r1);
7836 }
7837 }
7838 }
7839
7840 if (activities.size() <= 0) {
7841 return false;
7842 }
7843
7844 for (int i=0; i<activities.size(); i++) {
7845 dumpActivity(fd, pw, activities.get(i), newArgs, dumpAll);
7846 }
7847 return true;
7848 }
7849
7850 /**
7851 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
7852 * there is a thread associated with the activity.
7853 */
7854 private void dumpActivity(FileDescriptor fd, PrintWriter pw, ActivityRecord r, String[] args,
7855 boolean dumpAll) {
7856 pw.println(" Activity " + r.intent.getComponent().flattenToString());
7857 if (dumpAll) {
7858 synchronized (this) {
7859 pw.print(" * "); pw.println(r);
7860 r.dump(pw, " ");
7861 }
7862 pw.println("");
7863 }
7864 if (r.app != null && r.app.thread != null) {
7865 try {
7866 // flush anything that is already in the PrintWriter since the thread is going
7867 // to write to the file descriptor directly
7868 pw.flush();
7869 r.app.thread.dumpActivity(fd, r, args);
7870 pw.print("\n");
7871 pw.flush();
7872 } catch (RemoteException e) {
7873 pw.println("got a RemoteException while dumping the activity");
7874 }
7875 }
7876 }
7877
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007878 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7879 int opti, boolean dumpAll) {
7880 boolean needSep = false;
7881
7882 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 if (mRegisteredReceivers.size() > 0) {
7884 pw.println(" ");
7885 pw.println(" Registered Receivers:");
7886 Iterator it = mRegisteredReceivers.values().iterator();
7887 while (it.hasNext()) {
7888 ReceiverList r = (ReceiverList)it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007889 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007890 r.dump(pw, " ");
7891 }
7892 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007894 pw.println(" ");
7895 pw.println("Receiver Resolver Table:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007896 mReceiverResolver.dump(pw, null, " ", null, false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007897 needSep = true;
7898 }
7899
7900 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
7901 || mPendingBroadcast != null) {
7902 if (mParallelBroadcasts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007904 pw.println(" Active broadcasts:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007906 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
7907 pw.println(" Broadcast #" + i + ":");
7908 mParallelBroadcasts.get(i).dump(pw, " ");
7909 }
7910 if (mOrderedBroadcasts.size() > 0) {
7911 pw.println(" ");
Dianne Hackborn399cccb2010-04-13 22:57:49 -07007912 pw.println(" Active ordered broadcasts:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007913 }
7914 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
7915 pw.println(" Serialized Broadcast #" + i + ":");
7916 mOrderedBroadcasts.get(i).dump(pw, " ");
7917 }
7918 pw.println(" ");
7919 pw.println(" Pending broadcast:");
7920 if (mPendingBroadcast != null) {
7921 mPendingBroadcast.dump(pw, " ");
7922 } else {
7923 pw.println(" (null)");
7924 }
7925 needSep = true;
7926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007928 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007929 pw.println(" ");
Dianne Hackborn12527f92009-11-11 17:39:50 -08007930 pw.println(" Historical broadcasts:");
7931 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
7932 BroadcastRecord r = mBroadcastHistory[i];
7933 if (r == null) {
7934 break;
7935 }
7936 pw.println(" Historical Broadcast #" + i + ":");
7937 r.dump(pw, " ");
7938 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007939 needSep = true;
7940 }
7941
7942 if (mStickyBroadcasts != null) {
Dianne Hackborn12527f92009-11-11 17:39:50 -08007943 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007944 pw.println(" Sticky broadcasts:");
7945 StringBuilder sb = new StringBuilder(128);
7946 for (Map.Entry<String, ArrayList<Intent>> ent
7947 : mStickyBroadcasts.entrySet()) {
7948 pw.print(" * Sticky action "); pw.print(ent.getKey());
7949 pw.println(":");
7950 ArrayList<Intent> intents = ent.getValue();
7951 final int N = intents.size();
7952 for (int i=0; i<N; i++) {
7953 sb.setLength(0);
7954 sb.append(" Intent: ");
7955 intents.get(i).toShortString(sb, true, false);
7956 pw.println(sb.toString());
7957 Bundle bundle = intents.get(i).getExtras();
7958 if (bundle != null) {
7959 pw.print(" ");
7960 pw.println(bundle.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007961 }
7962 }
7963 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007964 needSep = true;
7965 }
7966
7967 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007969 pw.println(" mBroadcastsScheduled=" + mBroadcastsScheduled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970 pw.println(" mHandler:");
7971 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007972 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007974
7975 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007976 }
7977
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007978 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7979 int opti, boolean dumpAll) {
7980 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007982 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 if (mServices.size() > 0) {
7984 pw.println(" Active services:");
7985 Iterator<ServiceRecord> it = mServices.values().iterator();
7986 while (it.hasNext()) {
7987 ServiceRecord r = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007988 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007989 r.dump(pw, " ");
7990 }
7991 needSep = true;
7992 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007994
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007995 if (mPendingServices.size() > 0) {
7996 if (needSep) pw.println(" ");
7997 pw.println(" Pending services:");
7998 for (int i=0; i<mPendingServices.size(); i++) {
7999 ServiceRecord r = mPendingServices.get(i);
8000 pw.print(" * Pending "); pw.println(r);
8001 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008002 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008003 needSep = true;
8004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008006 if (mRestartingServices.size() > 0) {
8007 if (needSep) pw.println(" ");
8008 pw.println(" Restarting services:");
8009 for (int i=0; i<mRestartingServices.size(); i++) {
8010 ServiceRecord r = mRestartingServices.get(i);
8011 pw.print(" * Restarting "); pw.println(r);
8012 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008013 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008014 needSep = true;
8015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008016
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008017 if (mStoppingServices.size() > 0) {
8018 if (needSep) pw.println(" ");
8019 pw.println(" Stopping services:");
8020 for (int i=0; i<mStoppingServices.size(); i++) {
8021 ServiceRecord r = mStoppingServices.get(i);
8022 pw.print(" * Stopping "); pw.println(r);
8023 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008025 needSep = true;
8026 }
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 (mServiceConnections.size() > 0) {
8030 if (needSep) pw.println(" ");
8031 pw.println(" Connection bindings to services:");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008032 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 = mServiceConnections.values().iterator();
8034 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008035 ArrayList<ConnectionRecord> r = it.next();
8036 for (int i=0; i<r.size(); i++) {
8037 pw.print(" * "); pw.println(r.get(i));
8038 r.get(i).dump(pw, " ");
8039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008041 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008042 }
8043 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008044
8045 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008046 }
8047
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008048 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8049 int opti, boolean dumpAll) {
8050 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008052 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008053 if (mProvidersByClass.size() > 0) {
8054 if (needSep) pw.println(" ");
8055 pw.println(" Published content providers (by class):");
Dianne Hackborn860755f2010-06-03 18:47:52 -07008056 Iterator<Map.Entry<String, ContentProviderRecord>> it
8057 = mProvidersByClass.entrySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008058 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008059 Map.Entry<String, ContentProviderRecord> e = it.next();
8060 ContentProviderRecord r = e.getValue();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008061 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008062 r.dump(pw, " ");
8063 }
8064 needSep = true;
8065 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008066
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008067 if (mProvidersByName.size() > 0) {
8068 pw.println(" ");
8069 pw.println(" Authority to provider mappings:");
Dianne Hackborn860755f2010-06-03 18:47:52 -07008070 Iterator<Map.Entry<String, ContentProviderRecord>> it
8071 = mProvidersByName.entrySet().iterator();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008072 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008073 Map.Entry<String, ContentProviderRecord> e = it.next();
8074 ContentProviderRecord r = e.getValue();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008075 pw.print(" "); pw.print(e.getKey()); pw.print(": ");
8076 pw.println(r);
8077 }
8078 needSep = true;
8079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008080 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008081
8082 if (mLaunchingProviders.size() > 0) {
8083 if (needSep) pw.println(" ");
8084 pw.println(" Launching content providers:");
8085 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
8086 pw.print(" Launching #"); pw.print(i); pw.print(": ");
8087 pw.println(mLaunchingProviders.get(i));
8088 }
8089 needSep = true;
8090 }
8091
8092 if (mGrantedUriPermissions.size() > 0) {
8093 pw.println();
8094 pw.println("Granted Uri Permissions:");
8095 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
8096 int uid = mGrantedUriPermissions.keyAt(i);
8097 HashMap<Uri, UriPermission> perms
8098 = mGrantedUriPermissions.valueAt(i);
8099 pw.print(" * UID "); pw.print(uid);
8100 pw.println(" holds:");
8101 for (UriPermission perm : perms.values()) {
8102 pw.print(" "); pw.println(perm);
8103 perm.dump(pw, " ");
8104 }
8105 }
8106 needSep = true;
8107 }
8108
8109 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 }
8111
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008112 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8113 int opti, boolean dumpAll) {
8114 boolean needSep = false;
8115
8116 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 if (this.mIntentSenderRecords.size() > 0) {
8118 Iterator<WeakReference<PendingIntentRecord>> it
8119 = mIntentSenderRecords.values().iterator();
8120 while (it.hasNext()) {
8121 WeakReference<PendingIntentRecord> ref = it.next();
8122 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008123 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008124 if (rec != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008125 pw.print(" * "); pw.println(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008126 rec.dump(pw, " ");
8127 } else {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008128 pw.print(" * "); pw.print(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008129 }
8130 }
8131 }
8132 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008133
8134 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 }
8136
8137 private static final void dumpHistoryList(PrintWriter pw, List list,
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008138 String prefix, String label, boolean complete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008139 TaskRecord lastTask = null;
8140 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008141 ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008142 final boolean full = complete || !r.inHistory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008143 if (lastTask != r.task) {
8144 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008145 pw.print(prefix);
8146 pw.print(full ? "* " : " ");
8147 pw.println(lastTask);
8148 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008149 lastTask.dump(pw, prefix + " ");
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008152 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
8153 pw.print(" #"); pw.print(i); pw.print(": ");
8154 pw.println(r);
8155 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008156 r.dump(pw, prefix + " ");
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 }
8159 }
8160
Dianne Hackborn09c916b2009-12-08 14:50:51 -08008161 private static String buildOomTag(String prefix, String space, int val, int base) {
8162 if (val == base) {
8163 if (space == null) return prefix;
8164 return prefix + " ";
8165 }
8166 return prefix + "+" + Integer.toString(val-base);
8167 }
8168
8169 private static final int dumpProcessList(PrintWriter pw,
8170 ActivityManagerService service, List list,
Dianne Hackborn287952c2010-09-22 22:34:31 -07008171 String prefix, String normalLabel, String persistentLabel) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008172 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07008173 final int N = list.size()-1;
8174 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008176 pw.println(String.format("%s%s #%2d: %s",
8177 prefix, (r.persistent ? persistentLabel : normalLabel),
8178 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008179 if (r.persistent) {
8180 numPers++;
8181 }
8182 }
8183 return numPers;
8184 }
8185
Dianne Hackborn287952c2010-09-22 22:34:31 -07008186 private static final void dumpProcessOomList(PrintWriter pw,
8187 ActivityManagerService service, List<ProcessRecord> list,
8188 String prefix, String normalLabel, String persistentLabel,
8189 boolean inclDetails) {
8190
8191 final long curRealtime = SystemClock.elapsedRealtime();
8192 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
8193 final long curUptime = SystemClock.uptimeMillis();
8194 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
8195
8196 final int N = list.size()-1;
8197 for (int i=N; i>=0; i--) {
8198 ProcessRecord r = list.get(i);
8199 String oomAdj;
8200 if (r.setAdj >= EMPTY_APP_ADJ) {
8201 oomAdj = buildOomTag("empty", null, r.setAdj, EMPTY_APP_ADJ);
8202 } else if (r.setAdj >= HIDDEN_APP_MIN_ADJ) {
8203 oomAdj = buildOomTag("bak", " ", r.setAdj, HIDDEN_APP_MIN_ADJ);
8204 } else if (r.setAdj >= HOME_APP_ADJ) {
8205 oomAdj = buildOomTag("home ", null, r.setAdj, HOME_APP_ADJ);
8206 } else if (r.setAdj >= SECONDARY_SERVER_ADJ) {
8207 oomAdj = buildOomTag("svc", " ", r.setAdj, SECONDARY_SERVER_ADJ);
8208 } else if (r.setAdj >= BACKUP_APP_ADJ) {
8209 oomAdj = buildOomTag("bckup", null, r.setAdj, BACKUP_APP_ADJ);
8210 } else if (r.setAdj >= HEAVY_WEIGHT_APP_ADJ) {
8211 oomAdj = buildOomTag("hvy ", null, r.setAdj, HEAVY_WEIGHT_APP_ADJ);
8212 } else if (r.setAdj >= PERCEPTIBLE_APP_ADJ) {
8213 oomAdj = buildOomTag("prcp ", null, r.setAdj, PERCEPTIBLE_APP_ADJ);
8214 } else if (r.setAdj >= VISIBLE_APP_ADJ) {
8215 oomAdj = buildOomTag("vis ", null, r.setAdj, VISIBLE_APP_ADJ);
8216 } else if (r.setAdj >= FOREGROUND_APP_ADJ) {
8217 oomAdj = buildOomTag("fore ", null, r.setAdj, FOREGROUND_APP_ADJ);
8218 } else if (r.setAdj >= CORE_SERVER_ADJ) {
8219 oomAdj = buildOomTag("core ", null, r.setAdj, CORE_SERVER_ADJ);
8220 } else if (r.setAdj >= SYSTEM_ADJ) {
8221 oomAdj = buildOomTag("sys ", null, r.setAdj, SYSTEM_ADJ);
8222 } else {
8223 oomAdj = Integer.toString(r.setAdj);
8224 }
8225 String schedGroup;
8226 switch (r.setSchedGroup) {
8227 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
8228 schedGroup = "B";
8229 break;
8230 case Process.THREAD_GROUP_DEFAULT:
8231 schedGroup = "F";
8232 break;
8233 default:
8234 schedGroup = Integer.toString(r.setSchedGroup);
8235 break;
8236 }
8237 pw.println(String.format("%s%s #%2d: adj=%s/%s %s (%s)",
8238 prefix, (r.persistent ? persistentLabel : normalLabel),
8239 N-i, oomAdj, schedGroup, r.toShortString(), r.adjType));
8240 if (r.adjSource != null || r.adjTarget != null) {
8241 pw.print(prefix);
8242 pw.print(" ");
8243 if (r.adjTarget instanceof ComponentName) {
8244 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
8245 } else if (r.adjTarget != null) {
8246 pw.print(r.adjTarget.toString());
8247 } else {
8248 pw.print("{null}");
8249 }
8250 pw.print("<=");
8251 if (r.adjSource instanceof ProcessRecord) {
8252 pw.print("Proc{");
8253 pw.print(((ProcessRecord)r.adjSource).toShortString());
8254 pw.println("}");
8255 } else if (r.adjSource != null) {
8256 pw.println(r.adjSource.toString());
8257 } else {
8258 pw.println("{null}");
8259 }
8260 }
8261 if (inclDetails) {
8262 pw.print(prefix);
8263 pw.print(" ");
8264 pw.print("oom: max="); pw.print(r.maxAdj);
8265 pw.print(" hidden="); pw.print(r.hiddenAdj);
8266 pw.print(" curRaw="); pw.print(r.curRawAdj);
8267 pw.print(" setRaw="); pw.print(r.setRawAdj);
8268 pw.print(" cur="); pw.print(r.curAdj);
8269 pw.print(" set="); pw.println(r.setAdj);
8270 pw.print(prefix);
8271 pw.print(" ");
8272 pw.print("keeping="); pw.print(r.keeping);
8273 pw.print(" hidden="); pw.print(r.hidden);
8274 pw.print(" empty="); pw.println(r.empty);
8275
8276 if (!r.keeping) {
8277 if (r.lastWakeTime != 0) {
8278 long wtime;
8279 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
8280 synchronized (stats) {
8281 wtime = stats.getProcessWakeTime(r.info.uid,
8282 r.pid, curRealtime);
8283 }
8284 long timeUsed = wtime - r.lastWakeTime;
8285 pw.print(prefix);
8286 pw.print(" ");
8287 pw.print("keep awake over ");
8288 TimeUtils.formatDuration(realtimeSince, pw);
8289 pw.print(" used ");
8290 TimeUtils.formatDuration(timeUsed, pw);
8291 pw.print(" (");
8292 pw.print((timeUsed*100)/realtimeSince);
8293 pw.println("%)");
8294 }
8295 if (r.lastCpuTime != 0) {
8296 long timeUsed = r.curCpuTime - r.lastCpuTime;
8297 pw.print(prefix);
8298 pw.print(" ");
8299 pw.print("run cpu over ");
8300 TimeUtils.formatDuration(uptimeSince, pw);
8301 pw.print(" used ");
8302 TimeUtils.formatDuration(timeUsed, pw);
8303 pw.print(" (");
8304 pw.print((timeUsed*100)/uptimeSince);
8305 pw.println("%)");
8306 }
8307 }
8308 }
8309 }
8310 }
8311
Dianne Hackborn472ad872010-04-07 17:31:48 -07008312 static final void dumpApplicationMemoryUsage(FileDescriptor fd,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008313 PrintWriter pw, List list, String prefix, String[] args) {
Dianne Hackborn6447ca32009-04-07 19:50:08 -07008314 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008315 long uptime = SystemClock.uptimeMillis();
8316 long realtime = SystemClock.elapsedRealtime();
8317
8318 if (isCheckinRequest) {
8319 // short checkin version
8320 pw.println(uptime + "," + realtime);
8321 pw.flush();
8322 } else {
8323 pw.println("Applications Memory Usage (kB):");
8324 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
8325 }
8326 for (int i = list.size() - 1 ; i >= 0 ; i--) {
8327 ProcessRecord r = (ProcessRecord)list.get(i);
8328 if (r.thread != null) {
8329 if (!isCheckinRequest) {
8330 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
8331 pw.flush();
8332 }
8333 try {
8334 r.thread.asBinder().dump(fd, args);
8335 } catch (RemoteException e) {
8336 if (!isCheckinRequest) {
8337 pw.println("Got RemoteException!");
8338 pw.flush();
8339 }
8340 }
8341 }
8342 }
8343 }
8344
8345 /**
8346 * Searches array of arguments for the specified string
8347 * @param args array of argument strings
8348 * @param value value to search for
8349 * @return true if the value is contained in the array
8350 */
8351 private static boolean scanArgs(String[] args, String value) {
8352 if (args != null) {
8353 for (String arg : args) {
8354 if (value.equals(arg)) {
8355 return true;
8356 }
8357 }
8358 }
8359 return false;
8360 }
8361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008362 private final void killServicesLocked(ProcessRecord app,
8363 boolean allowRestart) {
8364 // Report disconnected services.
8365 if (false) {
8366 // XXX we are letting the client link to the service for
8367 // death notifications.
8368 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008369 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008370 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008371 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008372 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008373 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008374 = r.connections.values().iterator();
8375 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008376 ArrayList<ConnectionRecord> cl = jt.next();
8377 for (int i=0; i<cl.size(); i++) {
8378 ConnectionRecord c = cl.get(i);
8379 if (c.binding.client != app) {
8380 try {
8381 //c.conn.connected(r.className, null);
8382 } catch (Exception e) {
8383 // todo: this should be asynchronous!
8384 Slog.w(TAG, "Exception thrown disconnected servce "
8385 + r.shortName
8386 + " from app " + app.processName, e);
8387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008388 }
8389 }
8390 }
8391 }
8392 }
8393 }
8394 }
8395
8396 // Clean up any connections this application has to other services.
8397 if (app.connections.size() > 0) {
8398 Iterator<ConnectionRecord> it = app.connections.iterator();
8399 while (it.hasNext()) {
8400 ConnectionRecord r = it.next();
8401 removeConnectionLocked(r, app, null);
8402 }
8403 }
8404 app.connections.clear();
8405
8406 if (app.services.size() != 0) {
8407 // Any services running in the application need to be placed
8408 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008409 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008410 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008411 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008412 synchronized (sr.stats.getBatteryStats()) {
8413 sr.stats.stopLaunchedLocked();
8414 }
8415 sr.app = null;
8416 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008417 if (mStoppingServices.remove(sr)) {
8418 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
8419 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008420
8421 boolean hasClients = sr.bindings.size() > 0;
8422 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008423 Iterator<IntentBindRecord> bindings
8424 = sr.bindings.values().iterator();
8425 while (bindings.hasNext()) {
8426 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -08008427 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008428 + ": shouldUnbind=" + b.hasBound);
8429 b.binder = null;
8430 b.requested = b.received = b.hasBound = false;
8431 }
8432 }
8433
8434 if (sr.crashCount >= 2) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008435 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008436 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -08008437 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008438 sr.crashCount, sr.shortName, app.pid);
8439 bringDownServiceLocked(sr, true);
8440 } else if (!allowRestart) {
8441 bringDownServiceLocked(sr, true);
8442 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008443 boolean canceled = scheduleServiceRestartLocked(sr, true);
8444
8445 // Should the service remain running? Note that in the
8446 // extreme case of so many attempts to deliver a command
8447 // that it failed, that we also will stop it here.
8448 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
8449 if (sr.pendingStarts.size() == 0) {
8450 sr.startRequested = false;
8451 if (!hasClients) {
8452 // Whoops, no reason to restart!
8453 bringDownServiceLocked(sr, true);
8454 }
8455 }
8456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008457 }
8458 }
8459
8460 if (!allowRestart) {
8461 app.services.clear();
8462 }
8463 }
8464
Dianne Hackbornde42bb62009-08-05 12:26:15 -07008465 // Make sure we have no more records on the stopping list.
8466 int i = mStoppingServices.size();
8467 while (i > 0) {
8468 i--;
8469 ServiceRecord sr = mStoppingServices.get(i);
8470 if (sr.app == app) {
8471 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008472 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -07008473 }
8474 }
8475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 app.executingServices.clear();
8477 }
8478
8479 private final void removeDyingProviderLocked(ProcessRecord proc,
8480 ContentProviderRecord cpr) {
8481 synchronized (cpr) {
8482 cpr.launchingApp = null;
8483 cpr.notifyAll();
8484 }
8485
8486 mProvidersByClass.remove(cpr.info.name);
8487 String names[] = cpr.info.authority.split(";");
8488 for (int j = 0; j < names.length; j++) {
8489 mProvidersByName.remove(names[j]);
8490 }
8491
8492 Iterator<ProcessRecord> cit = cpr.clients.iterator();
8493 while (cit.hasNext()) {
8494 ProcessRecord capp = cit.next();
8495 if (!capp.persistent && capp.thread != null
8496 && capp.pid != 0
8497 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07008498 Slog.i(TAG, "Kill " + capp.processName
8499 + " (pid " + capp.pid + "): provider " + cpr.info.name
8500 + " in dying process " + proc.processName);
8501 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
8502 capp.processName, capp.setAdj, "dying provider " + proc.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 Process.killProcess(capp.pid);
8504 }
8505 }
8506
8507 mLaunchingProviders.remove(cpr);
8508 }
8509
8510 /**
8511 * Main code for cleaning up a process when it has gone away. This is
8512 * called both as a result of the process dying, or directly when stopping
8513 * a process when running in single process mode.
8514 */
8515 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
8516 boolean restarting, int index) {
8517 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008518 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008519 }
8520
Dianne Hackborn36124872009-10-08 16:22:03 -07008521 mProcessesToGc.remove(app);
8522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008523 // Dismiss any open dialogs.
8524 if (app.crashDialog != null) {
8525 app.crashDialog.dismiss();
8526 app.crashDialog = null;
8527 }
8528 if (app.anrDialog != null) {
8529 app.anrDialog.dismiss();
8530 app.anrDialog = null;
8531 }
8532 if (app.waitDialog != null) {
8533 app.waitDialog.dismiss();
8534 app.waitDialog = null;
8535 }
8536
8537 app.crashing = false;
8538 app.notResponding = false;
8539
8540 app.resetPackageList();
8541 app.thread = null;
8542 app.forcingToForeground = null;
8543 app.foregroundServices = false;
8544
8545 killServicesLocked(app, true);
8546
8547 boolean restart = false;
8548
8549 int NL = mLaunchingProviders.size();
8550
8551 // Remove published content providers.
8552 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008553 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008555 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 cpr.provider = null;
8557 cpr.app = null;
8558
8559 // See if someone is waiting for this provider... in which
8560 // case we don't remove it, but just let it restart.
8561 int i = 0;
8562 if (!app.bad) {
8563 for (; i<NL; i++) {
8564 if (mLaunchingProviders.get(i) == cpr) {
8565 restart = true;
8566 break;
8567 }
8568 }
8569 } else {
8570 i = NL;
8571 }
8572
8573 if (i >= NL) {
8574 removeDyingProviderLocked(app, cpr);
8575 NL = mLaunchingProviders.size();
8576 }
8577 }
8578 app.pubProviders.clear();
8579 }
8580
Dianne Hackbornf670ef72009-11-16 13:59:16 -08008581 // Take care of any launching providers waiting for this process.
8582 if (checkAppInLaunchingProvidersLocked(app, false)) {
8583 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008584 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08008585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008586 // Unregister from connected content providers.
8587 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07008588 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008589 while (it.hasNext()) {
8590 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
8591 cpr.clients.remove(app);
8592 }
8593 app.conProviders.clear();
8594 }
8595
Dianne Hackbornde42bb62009-08-05 12:26:15 -07008596 // At this point there may be remaining entries in mLaunchingProviders
8597 // where we were the only one waiting, so they are no longer of use.
8598 // Look for these and clean up if found.
8599 // XXX Commented out for now. Trying to figure out a way to reproduce
8600 // the actual situation to identify what is actually going on.
8601 if (false) {
8602 for (int i=0; i<NL; i++) {
8603 ContentProviderRecord cpr = (ContentProviderRecord)
8604 mLaunchingProviders.get(i);
8605 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
8606 synchronized (cpr) {
8607 cpr.launchingApp = null;
8608 cpr.notifyAll();
8609 }
8610 }
8611 }
8612 }
8613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008614 skipCurrentReceiverLocked(app);
8615
8616 // Unregister any receivers.
8617 if (app.receivers.size() > 0) {
8618 Iterator<ReceiverList> it = app.receivers.iterator();
8619 while (it.hasNext()) {
8620 removeReceiverLocked(it.next());
8621 }
8622 app.receivers.clear();
8623 }
8624
Christopher Tate181fafa2009-05-14 11:12:14 -07008625 // If the app is undergoing backup, tell the backup manager about it
8626 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008627 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -07008628 try {
8629 IBackupManager bm = IBackupManager.Stub.asInterface(
8630 ServiceManager.getService(Context.BACKUP_SERVICE));
8631 bm.agentDisconnected(app.info.packageName);
8632 } catch (RemoteException e) {
8633 // can't happen; backup manager is local
8634 }
8635 }
8636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008637 // If the caller is restarting this app, then leave it in its
8638 // current lists and let the caller take care of it.
8639 if (restarting) {
8640 return;
8641 }
8642
8643 if (!app.persistent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008644 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008645 "Removing non-persistent process during cleanup: " + app);
8646 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07008647 if (mHeavyWeightProcess == app) {
8648 mHeavyWeightProcess = null;
8649 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
8650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651 } else if (!app.removed) {
8652 // This app is persistent, so we need to keep its record around.
8653 // If it is not already on the pending app list, add it there
8654 // and start a new process for it.
8655 app.thread = null;
8656 app.forcingToForeground = null;
8657 app.foregroundServices = false;
8658 if (mPersistentStartingProcesses.indexOf(app) < 0) {
8659 mPersistentStartingProcesses.add(app);
8660 restart = true;
8661 }
8662 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008663 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
8664 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008665 mProcessesOnHold.remove(app);
8666
The Android Open Source Project4df24232009-03-05 14:34:35 -08008667 if (app == mHomeProcess) {
8668 mHomeProcess = null;
8669 }
8670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008671 if (restart) {
8672 // We have components that still need to be running in the
8673 // process, so re-launch it.
8674 mProcessNames.put(app.processName, app.info.uid, app);
8675 startProcessLocked(app, "restart", app.processName);
8676 } else if (app.pid > 0 && app.pid != MY_PID) {
8677 // Goodbye!
8678 synchronized (mPidsSelfLocked) {
8679 mPidsSelfLocked.remove(app.pid);
8680 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
8681 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07008682 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008683 }
8684 }
8685
Dianne Hackbornf670ef72009-11-16 13:59:16 -08008686 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
8687 // Look through the content providers we are waiting to have launched,
8688 // and if any run in this process then either schedule a restart of
8689 // the process or kill the client waiting for it if this process has
8690 // gone bad.
8691 int NL = mLaunchingProviders.size();
8692 boolean restart = false;
8693 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008694 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08008695 if (cpr.launchingApp == app) {
8696 if (!alwaysBad && !app.bad) {
8697 restart = true;
8698 } else {
8699 removeDyingProviderLocked(app, cpr);
8700 NL = mLaunchingProviders.size();
8701 }
8702 }
8703 }
8704 return restart;
8705 }
8706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008707 // =========================================================
8708 // SERVICES
8709 // =========================================================
8710
8711 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
8712 ActivityManager.RunningServiceInfo info =
8713 new ActivityManager.RunningServiceInfo();
8714 info.service = r.name;
8715 if (r.app != null) {
8716 info.pid = r.app.pid;
8717 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -07008718 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008719 info.process = r.processName;
8720 info.foreground = r.isForeground;
8721 info.activeSince = r.createTime;
8722 info.started = r.startRequested;
8723 info.clientCount = r.connections.size();
8724 info.crashCount = r.crashCount;
8725 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07008726 if (r.isForeground) {
8727 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
8728 }
8729 if (r.startRequested) {
8730 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
8731 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008732 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -07008733 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
8734 }
8735 if (r.app != null && r.app.persistent) {
8736 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
8737 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008738
8739 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
8740 for (int i=0; i<connl.size(); i++) {
8741 ConnectionRecord conn = connl.get(i);
8742 if (conn.clientLabel != 0) {
8743 info.clientPackage = conn.binding.client.info.packageName;
8744 info.clientLabel = conn.clientLabel;
8745 return info;
8746 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008747 }
8748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749 return info;
8750 }
8751
8752 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
8753 int flags) {
8754 synchronized (this) {
8755 ArrayList<ActivityManager.RunningServiceInfo> res
8756 = new ArrayList<ActivityManager.RunningServiceInfo>();
8757
8758 if (mServices.size() > 0) {
8759 Iterator<ServiceRecord> it = mServices.values().iterator();
8760 while (it.hasNext() && res.size() < maxNum) {
8761 res.add(makeRunningServiceInfoLocked(it.next()));
8762 }
8763 }
8764
8765 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
8766 ServiceRecord r = mRestartingServices.get(i);
8767 ActivityManager.RunningServiceInfo info =
8768 makeRunningServiceInfoLocked(r);
8769 info.restarting = r.nextRestartTime;
8770 res.add(info);
8771 }
8772
8773 return res;
8774 }
8775 }
8776
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008777 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
8778 synchronized (this) {
8779 ServiceRecord r = mServices.get(name);
8780 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008781 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
8782 for (int i=0; i<conn.size(); i++) {
8783 if (conn.get(i).clientIntent != null) {
8784 return conn.get(i).clientIntent;
8785 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008786 }
8787 }
8788 }
8789 }
8790 return null;
8791 }
8792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008793 private final ServiceRecord findServiceLocked(ComponentName name,
8794 IBinder token) {
8795 ServiceRecord r = mServices.get(name);
8796 return r == token ? r : null;
8797 }
8798
8799 private final class ServiceLookupResult {
8800 final ServiceRecord record;
8801 final String permission;
8802
8803 ServiceLookupResult(ServiceRecord _record, String _permission) {
8804 record = _record;
8805 permission = _permission;
8806 }
8807 };
8808
8809 private ServiceLookupResult findServiceLocked(Intent service,
8810 String resolvedType) {
8811 ServiceRecord r = null;
8812 if (service.getComponent() != null) {
8813 r = mServices.get(service.getComponent());
8814 }
8815 if (r == null) {
8816 Intent.FilterComparison filter = new Intent.FilterComparison(service);
8817 r = mServicesByIntent.get(filter);
8818 }
8819
8820 if (r == null) {
8821 try {
8822 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008823 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008824 service, resolvedType, 0);
8825 ServiceInfo sInfo =
8826 rInfo != null ? rInfo.serviceInfo : null;
8827 if (sInfo == null) {
8828 return null;
8829 }
8830
8831 ComponentName name = new ComponentName(
8832 sInfo.applicationInfo.packageName, sInfo.name);
8833 r = mServices.get(name);
8834 } catch (RemoteException ex) {
8835 // pm is in same process, this will never happen.
8836 }
8837 }
8838 if (r != null) {
8839 int callingPid = Binder.getCallingPid();
8840 int callingUid = Binder.getCallingUid();
8841 if (checkComponentPermission(r.permission,
8842 callingPid, callingUid, r.exported ? -1 : r.appInfo.uid)
8843 != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008844 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 + " from pid=" + callingPid
8846 + ", uid=" + callingUid
8847 + " requires " + r.permission);
8848 return new ServiceLookupResult(null, r.permission);
8849 }
8850 return new ServiceLookupResult(r, null);
8851 }
8852 return null;
8853 }
8854
8855 private class ServiceRestarter implements Runnable {
8856 private ServiceRecord mService;
8857
8858 void setService(ServiceRecord service) {
8859 mService = service;
8860 }
8861
8862 public void run() {
8863 synchronized(ActivityManagerService.this) {
8864 performServiceRestartLocked(mService);
8865 }
8866 }
8867 }
8868
8869 private ServiceLookupResult retrieveServiceLocked(Intent service,
8870 String resolvedType, int callingPid, int callingUid) {
8871 ServiceRecord r = null;
8872 if (service.getComponent() != null) {
8873 r = mServices.get(service.getComponent());
8874 }
8875 Intent.FilterComparison filter = new Intent.FilterComparison(service);
8876 r = mServicesByIntent.get(filter);
8877 if (r == null) {
8878 try {
8879 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008880 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -07008881 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008882 ServiceInfo sInfo =
8883 rInfo != null ? rInfo.serviceInfo : null;
8884 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008885 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008886 ": not found");
8887 return null;
8888 }
8889
8890 ComponentName name = new ComponentName(
8891 sInfo.applicationInfo.packageName, sInfo.name);
8892 r = mServices.get(name);
8893 if (r == null) {
8894 filter = new Intent.FilterComparison(service.cloneFilter());
8895 ServiceRestarter res = new ServiceRestarter();
8896 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
8897 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
8898 synchronized (stats) {
8899 ss = stats.getServiceStatsLocked(
8900 sInfo.applicationInfo.uid, sInfo.packageName,
8901 sInfo.name);
8902 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -08008903 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008904 res.setService(r);
8905 mServices.put(name, r);
8906 mServicesByIntent.put(filter, r);
8907
8908 // Make sure this component isn't in the pending list.
8909 int N = mPendingServices.size();
8910 for (int i=0; i<N; i++) {
8911 ServiceRecord pr = mPendingServices.get(i);
8912 if (pr.name.equals(name)) {
8913 mPendingServices.remove(i);
8914 i--;
8915 N--;
8916 }
8917 }
8918 }
8919 } catch (RemoteException ex) {
8920 // pm is in same process, this will never happen.
8921 }
8922 }
8923 if (r != null) {
8924 if (checkComponentPermission(r.permission,
8925 callingPid, callingUid, r.exported ? -1 : r.appInfo.uid)
8926 != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008927 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 + " from pid=" + Binder.getCallingPid()
8929 + ", uid=" + Binder.getCallingUid()
8930 + " requires " + r.permission);
8931 return new ServiceLookupResult(null, r.permission);
8932 }
8933 return new ServiceLookupResult(r, null);
8934 }
8935 return null;
8936 }
8937
Dianne Hackborn287952c2010-09-22 22:34:31 -07008938 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
8939 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
8940 + why + " of " + r + " in app " + r.app);
8941 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
8942 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 long now = SystemClock.uptimeMillis();
8944 if (r.executeNesting == 0 && r.app != null) {
8945 if (r.app.executingServices.size() == 0) {
8946 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
8947 msg.obj = r.app;
8948 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
8949 }
8950 r.app.executingServices.add(r);
8951 }
8952 r.executeNesting++;
8953 r.executingStart = now;
8954 }
8955
8956 private final void sendServiceArgsLocked(ServiceRecord r,
8957 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008958 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008959 if (N == 0) {
8960 return;
8961 }
8962
Dianne Hackborn39792d22010-08-19 18:01:52 -07008963 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -07008965 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008966 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
8967 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn39792d22010-08-19 18:01:52 -07008968 if (si.intent == null) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008969 // If somehow we got a dummy start at the front, then
8970 // just drop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008971 continue;
8972 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07008973 si.deliveredTime = SystemClock.uptimeMillis();
8974 r.deliveredStarts.add(si);
8975 si.deliveryCount++;
8976 if (si.targetPermissionUid >= 0) {
8977 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -07008978 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07008979 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008980 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008981 if (!oomAdjusted) {
8982 oomAdjusted = true;
8983 updateOomAdjLocked(r.app);
8984 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008985 int flags = 0;
8986 if (si.deliveryCount > 0) {
8987 flags |= Service.START_FLAG_RETRY;
8988 }
8989 if (si.doneExecutingCount > 0) {
8990 flags |= Service.START_FLAG_REDELIVERY;
8991 }
8992 r.app.thread.scheduleServiceArgs(r, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008993 } catch (RemoteException e) {
8994 // Remote process gone... we'll let the normal cleanup take
8995 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07008996 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008997 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008999 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009000 break;
9001 }
9002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009003 }
9004
9005 private final boolean requestServiceBindingLocked(ServiceRecord r,
9006 IntentBindRecord i, boolean rebind) {
9007 if (r.app == null || r.app.thread == null) {
9008 // If service is not currently running, can't yet bind.
9009 return false;
9010 }
9011 if ((!i.requested || rebind) && i.apps.size() > 0) {
9012 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009013 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009014 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
9015 if (!rebind) {
9016 i.requested = true;
9017 }
9018 i.hasBound = true;
9019 i.doRebind = false;
9020 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009021 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009022 return false;
9023 }
9024 }
9025 return true;
9026 }
9027
9028 private final void requestServiceBindingsLocked(ServiceRecord r) {
9029 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
9030 while (bindings.hasNext()) {
9031 IntentBindRecord i = bindings.next();
9032 if (!requestServiceBindingLocked(r, i, false)) {
9033 break;
9034 }
9035 }
9036 }
9037
9038 private final void realStartServiceLocked(ServiceRecord r,
9039 ProcessRecord app) throws RemoteException {
9040 if (app.thread == null) {
9041 throw new RemoteException();
9042 }
9043
9044 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -07009045 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009046
9047 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009048 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009049 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009050
9051 boolean created = false;
9052 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07009053 mStringBuilder.setLength(0);
9054 r.intent.getIntent().toShortString(mStringBuilder, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -08009055 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009056 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -07009057 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009058 synchronized (r.stats.getBatteryStats()) {
9059 r.stats.startLaunchedLocked();
9060 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07009061 ensurePackageDexOpt(r.serviceInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009062 app.thread.scheduleCreateService(r, r.serviceInfo);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009063 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009064 created = true;
9065 } finally {
9066 if (!created) {
9067 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009068 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009069 }
9070 }
9071
9072 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009073
9074 // If the service is in the started state, and there are no
9075 // pending arguments, then fake up one so its onStartCommand() will
9076 // be called.
9077 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
9078 r.lastStartId++;
9079 if (r.lastStartId < 1) {
9080 r.lastStartId = 1;
9081 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07009082 r.pendingStarts.add(new ServiceRecord.StartItem(r, r.lastStartId, null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009083 }
9084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009085 sendServiceArgsLocked(r, true);
9086 }
9087
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009088 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
9089 boolean allowCancel) {
9090 boolean canceled = false;
9091
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009092 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009093 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -07009094 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009095
9096 // Any delivered but not yet finished starts should be put back
9097 // on the pending list.
9098 final int N = r.deliveredStarts.size();
9099 if (N > 0) {
9100 for (int i=N-1; i>=0; i--) {
9101 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -07009102 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009103 if (si.intent == null) {
9104 // We'll generate this again if needed.
9105 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
9106 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
9107 r.pendingStarts.add(0, si);
9108 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
9109 dur *= 2;
9110 if (minDuration < dur) minDuration = dur;
9111 if (resetTime < dur) resetTime = dur;
9112 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009113 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009114 + r.name);
9115 canceled = true;
9116 }
9117 }
9118 r.deliveredStarts.clear();
9119 }
9120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009121 r.totalRestartCount++;
9122 if (r.restartDelay == 0) {
9123 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009124 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009125 } else {
9126 // If it has been a "reasonably long time" since the service
9127 // was started, then reset our restart duration back to
9128 // the beginning, so we don't infinitely increase the duration
9129 // on a service that just occasionally gets killed (which is
9130 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009131 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009132 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009133 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009134 } else {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009135 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009136 if (r.restartDelay < minDuration) {
9137 r.restartDelay = minDuration;
9138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009139 }
9140 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009141
9142 r.nextRestartTime = now + r.restartDelay;
9143
9144 // Make sure that we don't end up restarting a bunch of services
9145 // all at the same time.
9146 boolean repeat;
9147 do {
9148 repeat = false;
9149 for (int i=mRestartingServices.size()-1; i>=0; i--) {
9150 ServiceRecord r2 = mRestartingServices.get(i);
9151 if (r2 != r && r.nextRestartTime
9152 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
9153 && r.nextRestartTime
9154 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
9155 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
9156 r.restartDelay = r.nextRestartTime - now;
9157 repeat = true;
9158 break;
9159 }
9160 }
9161 } while (repeat);
9162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009163 if (!mRestartingServices.contains(r)) {
9164 mRestartingServices.add(r);
9165 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009166
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009167 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009170 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009171 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -08009172 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009173 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -08009174 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009175 r.shortName, r.restartDelay);
9176
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009177 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009178 }
9179
9180 final void performServiceRestartLocked(ServiceRecord r) {
9181 if (!mRestartingServices.contains(r)) {
9182 return;
9183 }
9184 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
9185 }
9186
9187 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
9188 if (r.restartDelay == 0) {
9189 return false;
9190 }
9191 r.resetRestartCounter();
9192 mRestartingServices.remove(r);
9193 mHandler.removeCallbacks(r.restarter);
9194 return true;
9195 }
9196
9197 private final boolean bringUpServiceLocked(ServiceRecord r,
9198 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009199 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009200 //r.dump(" ");
9201
Dianne Hackborn36124872009-10-08 16:22:03 -07009202 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009203 sendServiceArgsLocked(r, false);
9204 return true;
9205 }
9206
9207 if (!whileRestarting && r.restartDelay > 0) {
9208 // If waiting for a restart, then do nothing.
9209 return true;
9210 }
9211
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009212 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009213
Dianne Hackbornde42bb62009-08-05 12:26:15 -07009214 // We are now bringing the service up, so no longer in the
9215 // restarting state.
9216 mRestartingServices.remove(r);
9217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009218 final String appName = r.processName;
9219 ProcessRecord app = getProcessRecordLocked(appName, r.appInfo.uid);
9220 if (app != null && app.thread != null) {
9221 try {
9222 realStartServiceLocked(r, app);
9223 return true;
9224 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009225 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009226 }
9227
9228 // If a dead object exception was thrown -- fall through to
9229 // restart the application.
9230 }
9231
Dianne Hackborn36124872009-10-08 16:22:03 -07009232 // Not running -- get it started, and enqueue this service record
9233 // to be executed when the app comes up.
9234 if (startProcessLocked(appName, r.appInfo, true, intentFlags,
9235 "service", r.name, false) == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009236 Slog.w(TAG, "Unable to launch app "
Dianne Hackborn36124872009-10-08 16:22:03 -07009237 + r.appInfo.packageName + "/"
9238 + r.appInfo.uid + " for service "
9239 + r.intent.getIntent() + ": process is bad");
9240 bringDownServiceLocked(r, true);
9241 return false;
9242 }
9243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009244 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009245 mPendingServices.add(r);
9246 }
Dianne Hackborn36124872009-10-08 16:22:03 -07009247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009248 return true;
9249 }
9250
9251 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009252 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009253 //r.dump(" ");
9254
9255 // Does it still need to run?
9256 if (!force && r.startRequested) {
9257 return;
9258 }
9259 if (r.connections.size() > 0) {
9260 if (!force) {
9261 // XXX should probably keep a count of the number of auto-create
9262 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009263 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009264 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009265 ArrayList<ConnectionRecord> cr = it.next();
9266 for (int i=0; i<cr.size(); i++) {
9267 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
9268 return;
9269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009270 }
9271 }
9272 }
9273
9274 // Report to all of the connections that the service is no longer
9275 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009276 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009277 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009278 ArrayList<ConnectionRecord> c = it.next();
9279 for (int i=0; i<c.size(); i++) {
9280 try {
9281 c.get(i).conn.connected(r.name, null);
9282 } catch (Exception e) {
9283 Slog.w(TAG, "Failure disconnecting service " + r.name +
9284 " to connection " + c.get(i).conn.asBinder() +
9285 " (in " + c.get(i).binding.client.processName + ")", e);
9286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009287 }
9288 }
9289 }
9290
9291 // Tell the service that it has been unbound.
9292 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
9293 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
9294 while (it.hasNext()) {
9295 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -08009296 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 + ": hasBound=" + ibr.hasBound);
9298 if (r.app != null && r.app.thread != null && ibr.hasBound) {
9299 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009300 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009301 updateOomAdjLocked(r.app);
9302 ibr.hasBound = false;
9303 r.app.thread.scheduleUnbindService(r,
9304 ibr.intent.getIntent());
9305 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009306 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009307 + r.shortName, e);
9308 serviceDoneExecutingLocked(r, true);
9309 }
9310 }
9311 }
9312 }
9313
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009314 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -08009315 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009316 System.identityHashCode(r), r.shortName,
9317 (r.app != null) ? r.app.pid : -1);
9318
9319 mServices.remove(r.name);
9320 mServicesByIntent.remove(r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009321 r.totalRestartCount = 0;
9322 unscheduleServiceRestartLocked(r);
9323
9324 // Also make sure it is not on the pending list.
9325 int N = mPendingServices.size();
9326 for (int i=0; i<N; i++) {
9327 if (mPendingServices.get(i) == r) {
9328 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009329 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009330 i--;
9331 N--;
9332 }
9333 }
9334
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009335 r.cancelNotification();
9336 r.isForeground = false;
9337 r.foregroundId = 0;
9338 r.foregroundNoti = null;
9339
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009340 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -07009341 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009342 r.pendingStarts.clear();
9343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009344 if (r.app != null) {
9345 synchronized (r.stats.getBatteryStats()) {
9346 r.stats.stopLaunchedLocked();
9347 }
9348 r.app.services.remove(r);
9349 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009350 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009351 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 mStoppingServices.add(r);
9353 updateOomAdjLocked(r.app);
9354 r.app.thread.scheduleStopService(r);
9355 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009356 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009357 + r.shortName, e);
9358 serviceDoneExecutingLocked(r, true);
9359 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009360 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009361 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009362 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009363 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009364 }
9365 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009366 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009367 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009368 }
9369 }
9370
9371 ComponentName startServiceLocked(IApplicationThread caller,
9372 Intent service, String resolvedType,
9373 int callingPid, int callingUid) {
9374 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009375 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009376 + " type=" + resolvedType + " args=" + service.getExtras());
9377
9378 if (caller != null) {
9379 final ProcessRecord callerApp = getRecordForAppLocked(caller);
9380 if (callerApp == null) {
9381 throw new SecurityException(
9382 "Unable to find app for caller " + caller
9383 + " (pid=" + Binder.getCallingPid()
9384 + ") when starting service " + service);
9385 }
9386 }
9387
9388 ServiceLookupResult res =
9389 retrieveServiceLocked(service, resolvedType,
9390 callingPid, callingUid);
9391 if (res == null) {
9392 return null;
9393 }
9394 if (res.record == null) {
9395 return new ComponentName("!", res.permission != null
9396 ? res.permission : "private to package");
9397 }
9398 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -07009399 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
9400 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009402 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009403 }
9404 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009405 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009406 r.lastStartId++;
9407 if (r.lastStartId < 1) {
9408 r.lastStartId = 1;
9409 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07009410 r.pendingStarts.add(new ServiceRecord.StartItem(r, r.lastStartId,
9411 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009412 r.lastActivity = SystemClock.uptimeMillis();
9413 synchronized (r.stats.getBatteryStats()) {
9414 r.stats.startRunningLocked();
9415 }
9416 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
9417 return new ComponentName("!", "Service process is bad");
9418 }
9419 return r.name;
9420 }
9421 }
9422
9423 public ComponentName startService(IApplicationThread caller, Intent service,
9424 String resolvedType) {
9425 // Refuse possible leaked file descriptors
9426 if (service != null && service.hasFileDescriptors() == true) {
9427 throw new IllegalArgumentException("File descriptors passed in Intent");
9428 }
9429
9430 synchronized(this) {
9431 final int callingPid = Binder.getCallingPid();
9432 final int callingUid = Binder.getCallingUid();
9433 final long origId = Binder.clearCallingIdentity();
9434 ComponentName res = startServiceLocked(caller, service,
9435 resolvedType, callingPid, callingUid);
9436 Binder.restoreCallingIdentity(origId);
9437 return res;
9438 }
9439 }
9440
9441 ComponentName startServiceInPackage(int uid,
9442 Intent service, String resolvedType) {
9443 synchronized(this) {
9444 final long origId = Binder.clearCallingIdentity();
9445 ComponentName res = startServiceLocked(null, service,
9446 resolvedType, -1, uid);
9447 Binder.restoreCallingIdentity(origId);
9448 return res;
9449 }
9450 }
9451
9452 public int stopService(IApplicationThread caller, Intent service,
9453 String resolvedType) {
9454 // Refuse possible leaked file descriptors
9455 if (service != null && service.hasFileDescriptors() == true) {
9456 throw new IllegalArgumentException("File descriptors passed in Intent");
9457 }
9458
9459 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009460 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009461 + " type=" + resolvedType);
9462
9463 final ProcessRecord callerApp = getRecordForAppLocked(caller);
9464 if (caller != null && callerApp == null) {
9465 throw new SecurityException(
9466 "Unable to find app for caller " + caller
9467 + " (pid=" + Binder.getCallingPid()
9468 + ") when stopping service " + service);
9469 }
9470
9471 // If this service is active, make sure it is stopped.
9472 ServiceLookupResult r = findServiceLocked(service, resolvedType);
9473 if (r != null) {
9474 if (r.record != null) {
9475 synchronized (r.record.stats.getBatteryStats()) {
9476 r.record.stats.stopRunningLocked();
9477 }
9478 r.record.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009479 r.record.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009480 final long origId = Binder.clearCallingIdentity();
9481 bringDownServiceLocked(r.record, false);
9482 Binder.restoreCallingIdentity(origId);
9483 return 1;
9484 }
9485 return -1;
9486 }
9487 }
9488
9489 return 0;
9490 }
9491
9492 public IBinder peekService(Intent service, String resolvedType) {
9493 // Refuse possible leaked file descriptors
9494 if (service != null && service.hasFileDescriptors() == true) {
9495 throw new IllegalArgumentException("File descriptors passed in Intent");
9496 }
9497
9498 IBinder ret = null;
9499
9500 synchronized(this) {
9501 ServiceLookupResult r = findServiceLocked(service, resolvedType);
9502
9503 if (r != null) {
9504 // r.record is null if findServiceLocked() failed the caller permission check
9505 if (r.record == null) {
9506 throw new SecurityException(
9507 "Permission Denial: Accessing service " + r.record.name
9508 + " from pid=" + Binder.getCallingPid()
9509 + ", uid=" + Binder.getCallingUid()
9510 + " requires " + r.permission);
9511 }
9512 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
9513 if (ib != null) {
9514 ret = ib.binder;
9515 }
9516 }
9517 }
9518
9519 return ret;
9520 }
9521
9522 public boolean stopServiceToken(ComponentName className, IBinder token,
9523 int startId) {
9524 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009525 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009526 + " " + token + " startId=" + startId);
9527 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009528 if (r != null) {
9529 if (startId >= 0) {
9530 // Asked to only stop if done with all work. Note that
9531 // to avoid leaks, we will take this as dropping all
9532 // start items up to and including this one.
9533 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
9534 if (si != null) {
9535 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07009536 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
9537 cur.removeUriPermissionsLocked();
9538 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009539 break;
9540 }
9541 }
9542 }
9543
9544 if (r.lastStartId != startId) {
9545 return false;
9546 }
9547
9548 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009549 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009550 + " is last, but have " + r.deliveredStarts.size()
9551 + " remaining args");
9552 }
9553 }
9554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009555 synchronized (r.stats.getBatteryStats()) {
9556 r.stats.stopRunningLocked();
9557 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009558 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009559 }
9560 final long origId = Binder.clearCallingIdentity();
9561 bringDownServiceLocked(r, false);
9562 Binder.restoreCallingIdentity(origId);
9563 return true;
9564 }
9565 }
9566 return false;
9567 }
9568
9569 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009570 int id, Notification notification, boolean removeNotification) {
9571 final long origId = Binder.clearCallingIdentity();
9572 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009573 synchronized(this) {
9574 ServiceRecord r = findServiceLocked(className, token);
9575 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009576 if (id != 0) {
9577 if (notification == null) {
9578 throw new IllegalArgumentException("null notification");
9579 }
9580 if (r.foregroundId != id) {
9581 r.cancelNotification();
9582 r.foregroundId = id;
9583 }
9584 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
9585 r.foregroundNoti = notification;
9586 r.isForeground = true;
9587 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009588 if (r.app != null) {
9589 updateServiceForegroundLocked(r.app, true);
9590 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009591 } else {
9592 if (r.isForeground) {
9593 r.isForeground = false;
9594 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07009595 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009596 updateServiceForegroundLocked(r.app, true);
9597 }
9598 }
9599 if (removeNotification) {
9600 r.cancelNotification();
9601 r.foregroundId = 0;
9602 r.foregroundNoti = null;
9603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009604 }
9605 }
9606 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07009607 } finally {
9608 Binder.restoreCallingIdentity(origId);
9609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009610 }
9611
9612 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
9613 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -07009614 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009615 if (sr.isForeground) {
9616 anyForeground = true;
9617 break;
9618 }
9619 }
9620 if (anyForeground != proc.foregroundServices) {
9621 proc.foregroundServices = anyForeground;
9622 if (oomAdj) {
9623 updateOomAdjLocked();
9624 }
9625 }
9626 }
9627
9628 public int bindService(IApplicationThread caller, IBinder token,
9629 Intent service, String resolvedType,
9630 IServiceConnection connection, int flags) {
9631 // Refuse possible leaked file descriptors
9632 if (service != null && service.hasFileDescriptors() == true) {
9633 throw new IllegalArgumentException("File descriptors passed in Intent");
9634 }
9635
9636 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009637 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009638 + " type=" + resolvedType + " conn=" + connection.asBinder()
9639 + " flags=0x" + Integer.toHexString(flags));
9640 final ProcessRecord callerApp = getRecordForAppLocked(caller);
9641 if (callerApp == null) {
9642 throw new SecurityException(
9643 "Unable to find app for caller " + caller
9644 + " (pid=" + Binder.getCallingPid()
9645 + ") when binding service " + service);
9646 }
9647
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009648 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009649 if (token != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009650 int aindex = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009651 if (aindex < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009652 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009653 return 0;
9654 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009655 activity = (ActivityRecord)mMainStack.mHistory.get(aindex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009656 }
9657
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009658 int clientLabel = 0;
9659 PendingIntent clientIntent = null;
9660
9661 if (callerApp.info.uid == Process.SYSTEM_UID) {
9662 // Hacky kind of thing -- allow system stuff to tell us
9663 // what they are, so we can report this elsewhere for
9664 // others to know why certain services are running.
9665 try {
9666 clientIntent = (PendingIntent)service.getParcelableExtra(
9667 Intent.EXTRA_CLIENT_INTENT);
9668 } catch (RuntimeException e) {
9669 }
9670 if (clientIntent != null) {
9671 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
9672 if (clientLabel != 0) {
9673 // There are no useful extras in the intent, trash them.
9674 // System code calling with this stuff just needs to know
9675 // this will happen.
9676 service = service.cloneFilter();
9677 }
9678 }
9679 }
9680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009681 ServiceLookupResult res =
9682 retrieveServiceLocked(service, resolvedType,
9683 Binder.getCallingPid(), Binder.getCallingUid());
9684 if (res == null) {
9685 return 0;
9686 }
9687 if (res.record == null) {
9688 return -1;
9689 }
9690 ServiceRecord s = res.record;
9691
9692 final long origId = Binder.clearCallingIdentity();
9693
9694 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009695 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009696 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009697 }
9698
9699 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
9700 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009701 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009702
9703 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009704 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
9705 if (clist == null) {
9706 clist = new ArrayList<ConnectionRecord>();
9707 s.connections.put(binder, clist);
9708 }
9709 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009710 b.connections.add(c);
9711 if (activity != null) {
9712 if (activity.connections == null) {
9713 activity.connections = new HashSet<ConnectionRecord>();
9714 }
9715 activity.connections.add(c);
9716 }
9717 b.client.connections.add(c);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009718 clist = mServiceConnections.get(binder);
9719 if (clist == null) {
9720 clist = new ArrayList<ConnectionRecord>();
9721 mServiceConnections.put(binder, clist);
9722 }
9723 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009724
9725 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
9726 s.lastActivity = SystemClock.uptimeMillis();
9727 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
9728 return 0;
9729 }
9730 }
9731
9732 if (s.app != null) {
9733 // This could have made the service more important.
9734 updateOomAdjLocked(s.app);
9735 }
9736
Joe Onorato8a9b2202010-02-26 18:56:32 -08009737 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009738 + ": received=" + b.intent.received
9739 + " apps=" + b.intent.apps.size()
9740 + " doRebind=" + b.intent.doRebind);
9741
9742 if (s.app != null && b.intent.received) {
9743 // Service is already running, so we can immediately
9744 // publish the connection.
9745 try {
9746 c.conn.connected(s.name, b.intent.binder);
9747 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009748 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009749 + " to connection " + c.conn.asBinder()
9750 + " (in " + c.binding.client.processName + ")", e);
9751 }
9752
9753 // If this is the first app connected back to this binding,
9754 // and the service had previously asked to be told when
9755 // rebound, then do so.
9756 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
9757 requestServiceBindingLocked(s, b.intent, true);
9758 }
9759 } else if (!b.intent.requested) {
9760 requestServiceBindingLocked(s, b.intent, false);
9761 }
9762
9763 Binder.restoreCallingIdentity(origId);
9764 }
9765
9766 return 1;
9767 }
9768
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009769 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009770 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009771 IBinder binder = c.conn.asBinder();
9772 AppBindRecord b = c.binding;
9773 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009774 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
9775 if (clist != null) {
9776 clist.remove(c);
9777 if (clist.size() == 0) {
9778 s.connections.remove(binder);
9779 }
9780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009781 b.connections.remove(c);
9782 if (c.activity != null && c.activity != skipAct) {
9783 if (c.activity.connections != null) {
9784 c.activity.connections.remove(c);
9785 }
9786 }
9787 if (b.client != skipApp) {
9788 b.client.connections.remove(c);
9789 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009790 clist = mServiceConnections.get(binder);
9791 if (clist != null) {
9792 clist.remove(c);
9793 if (clist.size() == 0) {
9794 mServiceConnections.remove(binder);
9795 }
9796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009797
9798 if (b.connections.size() == 0) {
9799 b.intent.apps.remove(b.client);
9800 }
9801
Joe Onorato8a9b2202010-02-26 18:56:32 -08009802 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009803 + ": shouldUnbind=" + b.intent.hasBound);
9804 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
9805 && b.intent.hasBound) {
9806 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009807 bumpServiceExecutingLocked(s, "unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009808 updateOomAdjLocked(s.app);
9809 b.intent.hasBound = false;
9810 // Assume the client doesn't want to know about a rebind;
9811 // we will deal with that later if it asks for one.
9812 b.intent.doRebind = false;
9813 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
9814 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009815 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009816 serviceDoneExecutingLocked(s, true);
9817 }
9818 }
9819
9820 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
9821 bringDownServiceLocked(s, false);
9822 }
9823 }
9824
9825 public boolean unbindService(IServiceConnection connection) {
9826 synchronized (this) {
9827 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -08009828 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009829 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
9830 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009831 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 + connection.asBinder());
9833 return false;
9834 }
9835
9836 final long origId = Binder.clearCallingIdentity();
9837
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009838 while (clist.size() > 0) {
9839 ConnectionRecord r = clist.get(0);
9840 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009841
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009842 if (r.binding.service.app != null) {
9843 // This could have made the service less important.
9844 updateOomAdjLocked(r.binding.service.app);
9845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009846 }
9847
9848 Binder.restoreCallingIdentity(origId);
9849 }
9850
9851 return true;
9852 }
9853
9854 public void publishService(IBinder token, Intent intent, IBinder service) {
9855 // Refuse possible leaked file descriptors
9856 if (intent != null && intent.hasFileDescriptors() == true) {
9857 throw new IllegalArgumentException("File descriptors passed in Intent");
9858 }
9859
9860 synchronized(this) {
9861 if (!(token instanceof ServiceRecord)) {
9862 throw new IllegalArgumentException("Invalid service token");
9863 }
9864 ServiceRecord r = (ServiceRecord)token;
9865
9866 final long origId = Binder.clearCallingIdentity();
9867
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009868 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009869 + " " + intent + ": " + service);
9870 if (r != null) {
9871 Intent.FilterComparison filter
9872 = new Intent.FilterComparison(intent);
9873 IntentBindRecord b = r.bindings.get(filter);
9874 if (b != null && !b.received) {
9875 b.binder = service;
9876 b.requested = true;
9877 b.received = true;
9878 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009879 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009880 = r.connections.values().iterator();
9881 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009882 ArrayList<ConnectionRecord> clist = it.next();
9883 for (int i=0; i<clist.size(); i++) {
9884 ConnectionRecord c = clist.get(i);
9885 if (!filter.equals(c.binding.intent.intent)) {
9886 if (DEBUG_SERVICE) Slog.v(
9887 TAG, "Not publishing to: " + c);
9888 if (DEBUG_SERVICE) Slog.v(
9889 TAG, "Bound intent: " + c.binding.intent.intent);
9890 if (DEBUG_SERVICE) Slog.v(
9891 TAG, "Published intent: " + intent);
9892 continue;
9893 }
9894 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
9895 try {
9896 c.conn.connected(r.name, service);
9897 } catch (Exception e) {
9898 Slog.w(TAG, "Failure sending service " + r.name +
9899 " to connection " + c.conn.asBinder() +
9900 " (in " + c.binding.client.processName + ")", e);
9901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009902 }
9903 }
9904 }
9905 }
9906
9907 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
9908
9909 Binder.restoreCallingIdentity(origId);
9910 }
9911 }
9912 }
9913
9914 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
9915 // Refuse possible leaked file descriptors
9916 if (intent != null && intent.hasFileDescriptors() == true) {
9917 throw new IllegalArgumentException("File descriptors passed in Intent");
9918 }
9919
9920 synchronized(this) {
9921 if (!(token instanceof ServiceRecord)) {
9922 throw new IllegalArgumentException("Invalid service token");
9923 }
9924 ServiceRecord r = (ServiceRecord)token;
9925
9926 final long origId = Binder.clearCallingIdentity();
9927
9928 if (r != null) {
9929 Intent.FilterComparison filter
9930 = new Intent.FilterComparison(intent);
9931 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -08009932 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009933 + " at " + b + ": apps="
9934 + (b != null ? b.apps.size() : 0));
9935 if (b != null) {
9936 if (b.apps.size() > 0) {
9937 // Applications have already bound since the last
9938 // unbind, so just rebind right here.
9939 requestServiceBindingLocked(r, b, true);
9940 } else {
9941 // Note to tell the service the next time there is
9942 // a new client.
9943 b.doRebind = true;
9944 }
9945 }
9946
9947 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
9948
9949 Binder.restoreCallingIdentity(origId);
9950 }
9951 }
9952 }
9953
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009954 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009955 synchronized(this) {
9956 if (!(token instanceof ServiceRecord)) {
9957 throw new IllegalArgumentException("Invalid service token");
9958 }
9959 ServiceRecord r = (ServiceRecord)token;
9960 boolean inStopping = mStoppingServices.contains(token);
9961 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009962 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009963 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009964 + " with incorrect token: given " + token
9965 + ", expected " + r);
9966 return;
9967 }
9968
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009969 if (type == 1) {
9970 // This is a call from a service start... take care of
9971 // book-keeping.
9972 r.callStart = true;
9973 switch (res) {
9974 case Service.START_STICKY_COMPATIBILITY:
9975 case Service.START_STICKY: {
9976 // We are done with the associated start arguments.
9977 r.findDeliveredStart(startId, true);
9978 // Don't stop if killed.
9979 r.stopIfKilled = false;
9980 break;
9981 }
9982 case Service.START_NOT_STICKY: {
9983 // We are done with the associated start arguments.
9984 r.findDeliveredStart(startId, true);
9985 if (r.lastStartId == startId) {
9986 // There is no more work, and this service
9987 // doesn't want to hang around if killed.
9988 r.stopIfKilled = true;
9989 }
9990 break;
9991 }
9992 case Service.START_REDELIVER_INTENT: {
9993 // We'll keep this item until they explicitly
9994 // call stop for it, but keep track of the fact
9995 // that it was delivered.
9996 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
9997 if (si != null) {
9998 si.deliveryCount = 0;
9999 si.doneExecutingCount++;
10000 // Don't stop if killed.
10001 r.stopIfKilled = true;
10002 }
10003 break;
10004 }
10005 default:
10006 throw new IllegalArgumentException(
10007 "Unknown service start result: " + res);
10008 }
10009 if (res == Service.START_STICKY_COMPATIBILITY) {
10010 r.callStart = false;
10011 }
10012 }
10013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010014 final long origId = Binder.clearCallingIdentity();
10015 serviceDoneExecutingLocked(r, inStopping);
10016 Binder.restoreCallingIdentity(origId);
10017 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010018 Slog.w(TAG, "Done executing unknown service from pid "
10019 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010020 }
10021 }
10022 }
10023
10024 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010025 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
10026 + ": nesting=" + r.executeNesting
10027 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010028 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010029 r.executeNesting--;
10030 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010031 if (DEBUG_SERVICE) Slog.v(TAG,
10032 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010033 r.app.executingServices.remove(r);
10034 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010035 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
10036 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010037 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
10038 }
10039 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010040 if (DEBUG_SERVICE) Slog.v(TAG,
10041 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010042 mStoppingServices.remove(r);
10043 }
10044 updateOomAdjLocked(r.app);
10045 }
10046 }
10047
10048 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010049 String anrMessage = null;
10050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010051 synchronized(this) {
10052 if (proc.executingServices.size() == 0 || proc.thread == null) {
10053 return;
10054 }
10055 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
10056 Iterator<ServiceRecord> it = proc.executingServices.iterator();
10057 ServiceRecord timeout = null;
10058 long nextTime = 0;
10059 while (it.hasNext()) {
10060 ServiceRecord sr = it.next();
10061 if (sr.executingStart < maxTime) {
10062 timeout = sr;
10063 break;
10064 }
10065 if (sr.executingStart > nextTime) {
10066 nextTime = sr.executingStart;
10067 }
10068 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010069 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010070 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010071 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010072 } else {
10073 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10074 msg.obj = proc;
10075 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
10076 }
10077 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010078
10079 if (anrMessage != null) {
10080 appNotResponding(proc, null, null, anrMessage);
10081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010082 }
10083
10084 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010085 // BACKUP AND RESTORE
10086 // =========================================================
10087
10088 // Cause the target app to be launched if necessary and its backup agent
10089 // instantiated. The backup agent will invoke backupAgentCreated() on the
10090 // activity manager to announce its creation.
10091 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010092 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010093 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10094
10095 synchronized(this) {
10096 // !!! TODO: currently no check here that we're already bound
10097 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10098 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10099 synchronized (stats) {
10100 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10101 }
10102
10103 BackupRecord r = new BackupRecord(ss, app, backupMode);
10104 ComponentName hostingName = new ComponentName(app.packageName, app.backupAgentName);
10105 // startProcessLocked() returns existing proc's record if it's already running
10106 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070010107 false, 0, "backup", hostingName, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010108 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010109 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010110 return false;
10111 }
10112
10113 r.app = proc;
10114 mBackupTarget = r;
10115 mBackupAppName = app.packageName;
10116
Christopher Tate6fa95972009-06-05 18:43:55 -070010117 // Try not to kill the process during backup
10118 updateOomAdjLocked(proc);
10119
Christopher Tate181fafa2009-05-14 11:12:14 -070010120 // If the process is already attached, schedule the creation of the backup agent now.
10121 // If it is not yet live, this will be done when it attaches to the framework.
10122 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010123 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010124 try {
10125 proc.thread.scheduleCreateBackupAgent(app, backupMode);
10126 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070010127 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070010128 }
10129 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010130 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070010131 }
10132 // Invariants: at this point, the target app process exists and the application
10133 // is either already running or in the process of coming up. mBackupTarget and
10134 // mBackupAppName describe the app, so that when it binds back to the AM we
10135 // know that it's scheduled for a backup-agent operation.
10136 }
10137
10138 return true;
10139 }
10140
10141 // A backup agent has just come up
10142 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010143 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070010144 + " = " + agent);
10145
10146 synchronized(this) {
10147 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010148 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070010149 return;
10150 }
Dianne Hackborn06740692010-09-22 22:46:21 -070010151 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010152
Dianne Hackborn06740692010-09-22 22:46:21 -070010153 long oldIdent = Binder.clearCallingIdentity();
10154 try {
10155 IBackupManager bm = IBackupManager.Stub.asInterface(
10156 ServiceManager.getService(Context.BACKUP_SERVICE));
10157 bm.agentConnected(agentPackageName, agent);
10158 } catch (RemoteException e) {
10159 // can't happen; the backup manager service is local
10160 } catch (Exception e) {
10161 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
10162 e.printStackTrace();
10163 } finally {
10164 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070010165 }
10166 }
10167
10168 // done with this agent
10169 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010170 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070010171 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010172 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070010173 return;
10174 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010175
10176 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070010177 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010178 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070010179 return;
10180 }
10181
Christopher Tate181fafa2009-05-14 11:12:14 -070010182 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010183 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070010184 return;
10185 }
10186
Christopher Tate6fa95972009-06-05 18:43:55 -070010187 ProcessRecord proc = mBackupTarget.app;
10188 mBackupTarget = null;
10189 mBackupAppName = null;
10190
10191 // Not backing this app up any more; reset its OOM adjustment
10192 updateOomAdjLocked(proc);
10193
Christopher Tatec7b31e32009-06-10 15:49:30 -070010194 // If the app crashed during backup, 'thread' will be null here
10195 if (proc.thread != null) {
10196 try {
10197 proc.thread.scheduleDestroyBackupAgent(appInfo);
10198 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010199 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070010200 e.printStackTrace();
10201 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010202 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010203 }
10204 }
10205 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010206 // BROADCASTS
10207 // =========================================================
10208
Josh Bartel7f208742010-02-25 11:01:44 -060010209 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010210 List cur) {
10211 final ContentResolver resolver = mContext.getContentResolver();
10212 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
10213 if (list == null) {
10214 return cur;
10215 }
10216 int N = list.size();
10217 for (int i=0; i<N; i++) {
10218 Intent intent = list.get(i);
10219 if (filter.match(resolver, intent, true, TAG) >= 0) {
10220 if (cur == null) {
10221 cur = new ArrayList<Intent>();
10222 }
10223 cur.add(intent);
10224 }
10225 }
10226 return cur;
10227 }
10228
10229 private final void scheduleBroadcastsLocked() {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010230 if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts: current="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010231 + mBroadcastsScheduled);
10232
10233 if (mBroadcastsScheduled) {
10234 return;
10235 }
10236 mHandler.sendEmptyMessage(BROADCAST_INTENT_MSG);
10237 mBroadcastsScheduled = true;
10238 }
10239
10240 public Intent registerReceiver(IApplicationThread caller,
10241 IIntentReceiver receiver, IntentFilter filter, String permission) {
10242 synchronized(this) {
10243 ProcessRecord callerApp = null;
10244 if (caller != null) {
10245 callerApp = getRecordForAppLocked(caller);
10246 if (callerApp == null) {
10247 throw new SecurityException(
10248 "Unable to find app for caller " + caller
10249 + " (pid=" + Binder.getCallingPid()
10250 + ") when registering receiver " + receiver);
10251 }
10252 }
10253
10254 List allSticky = null;
10255
10256 // Look for any matching sticky broadcasts...
10257 Iterator actions = filter.actionsIterator();
10258 if (actions != null) {
10259 while (actions.hasNext()) {
10260 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060010261 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010262 }
10263 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060010264 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010265 }
10266
10267 // The first sticky in the list is returned directly back to
10268 // the client.
10269 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
10270
Joe Onorato8a9b2202010-02-26 18:56:32 -080010271 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010272 + ": " + sticky);
10273
10274 if (receiver == null) {
10275 return sticky;
10276 }
10277
10278 ReceiverList rl
10279 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
10280 if (rl == null) {
10281 rl = new ReceiverList(this, callerApp,
10282 Binder.getCallingPid(),
10283 Binder.getCallingUid(), receiver);
10284 if (rl.app != null) {
10285 rl.app.receivers.add(rl);
10286 } else {
10287 try {
10288 receiver.asBinder().linkToDeath(rl, 0);
10289 } catch (RemoteException e) {
10290 return sticky;
10291 }
10292 rl.linkedToDeath = true;
10293 }
10294 mRegisteredReceivers.put(receiver.asBinder(), rl);
10295 }
10296 BroadcastFilter bf = new BroadcastFilter(filter, rl, permission);
10297 rl.add(bf);
10298 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010299 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010300 }
10301 mReceiverResolver.addFilter(bf);
10302
10303 // Enqueue broadcasts for all existing stickies that match
10304 // this filter.
10305 if (allSticky != null) {
10306 ArrayList receivers = new ArrayList();
10307 receivers.add(bf);
10308
10309 int N = allSticky.size();
10310 for (int i=0; i<N; i++) {
10311 Intent intent = (Intent)allSticky.get(i);
10312 BroadcastRecord r = new BroadcastRecord(intent, null,
10313 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080010314 false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010315 if (mParallelBroadcasts.size() == 0) {
10316 scheduleBroadcastsLocked();
10317 }
10318 mParallelBroadcasts.add(r);
10319 }
10320 }
10321
10322 return sticky;
10323 }
10324 }
10325
10326 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010327 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010328
10329 boolean doNext = false;
10330
10331 synchronized(this) {
10332 ReceiverList rl
10333 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
10334 if (rl != null) {
10335 if (rl.curBroadcast != null) {
10336 BroadcastRecord r = rl.curBroadcast;
10337 doNext = finishReceiverLocked(
10338 receiver.asBinder(), r.resultCode, r.resultData,
10339 r.resultExtras, r.resultAbort, true);
10340 }
10341
10342 if (rl.app != null) {
10343 rl.app.receivers.remove(rl);
10344 }
10345 removeReceiverLocked(rl);
10346 if (rl.linkedToDeath) {
10347 rl.linkedToDeath = false;
10348 rl.receiver.asBinder().unlinkToDeath(rl, 0);
10349 }
10350 }
10351 }
10352
10353 if (!doNext) {
10354 return;
10355 }
10356
10357 final long origId = Binder.clearCallingIdentity();
10358 processNextBroadcast(false);
10359 trimApplications();
10360 Binder.restoreCallingIdentity(origId);
10361 }
10362
10363 void removeReceiverLocked(ReceiverList rl) {
10364 mRegisteredReceivers.remove(rl.receiver.asBinder());
10365 int N = rl.size();
10366 for (int i=0; i<N; i++) {
10367 mReceiverResolver.removeFilter(rl.get(i));
10368 }
10369 }
10370
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070010371 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
10372 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
10373 ProcessRecord r = mLruProcesses.get(i);
10374 if (r.thread != null) {
10375 try {
10376 r.thread.dispatchPackageBroadcast(cmd, packages);
10377 } catch (RemoteException ex) {
10378 }
10379 }
10380 }
10381 }
10382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010383 private final int broadcastIntentLocked(ProcessRecord callerApp,
10384 String callerPackage, Intent intent, String resolvedType,
10385 IIntentReceiver resultTo, int resultCode, String resultData,
10386 Bundle map, String requiredPermission,
10387 boolean ordered, boolean sticky, int callingPid, int callingUid) {
10388 intent = new Intent(intent);
10389
Joe Onorato8a9b2202010-02-26 18:56:32 -080010390 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010391 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
10392 + " ordered=" + ordered);
10393 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010394 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010395 }
10396
10397 // Handle special intents: if this broadcast is from the package
10398 // manager about a package being removed, we need to remove all of
10399 // its activities from the history stack.
10400 final boolean uidRemoved = intent.ACTION_UID_REMOVED.equals(
10401 intent.getAction());
10402 if (intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
10403 || intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010404 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010405 || uidRemoved) {
10406 if (checkComponentPermission(
10407 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
10408 callingPid, callingUid, -1)
10409 == PackageManager.PERMISSION_GRANTED) {
10410 if (uidRemoved) {
10411 final Bundle intentExtras = intent.getExtras();
10412 final int uid = intentExtras != null
10413 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
10414 if (uid >= 0) {
10415 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
10416 synchronized (bs) {
10417 bs.removeUidStatsLocked(uid);
10418 }
10419 }
10420 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010421 // If resources are unvailble just force stop all
10422 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010423 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010424 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
10425 if (list != null && (list.length > 0)) {
10426 for (String pkg : list) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080010427 forceStopPackageLocked(pkg, -1, false, true, true);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010428 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070010429 sendPackageBroadcastLocked(
10430 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010431 }
10432 } else {
10433 Uri data = intent.getData();
10434 String ssp;
10435 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
10436 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
10437 forceStopPackageLocked(ssp,
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080010438 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070010439 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070010440 if (intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
10441 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
10442 new String[] {ssp});
10443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010444 }
10445 }
10446 }
10447 } else {
10448 String msg = "Permission Denial: " + intent.getAction()
10449 + " broadcast from " + callerPackage + " (pid=" + callingPid
10450 + ", uid=" + callingUid + ")"
10451 + " requires "
10452 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010453 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010454 throw new SecurityException(msg);
10455 }
10456 }
10457
10458 /*
10459 * If this is the time zone changed action, queue up a message that will reset the timezone
10460 * of all currently running processes. This message will get queued up before the broadcast
10461 * happens.
10462 */
10463 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
10464 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
10465 }
10466
Robert Greenwalt03595d02010-11-02 14:08:23 -070010467 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
10468 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
10469 }
10470
Robert Greenwalt434203a2010-10-11 16:00:27 -070010471 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
10472 ProxyProperties proxy = intent.getParcelableExtra("proxy");
10473 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
10474 }
10475
Dianne Hackborn854060af2009-07-09 18:14:31 -070010476 /*
10477 * Prevent non-system code (defined here to be non-persistent
10478 * processes) from sending protected broadcasts.
10479 */
10480 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
10481 || callingUid == Process.SHELL_UID || callingUid == 0) {
10482 // Always okay.
10483 } else if (callerApp == null || !callerApp.persistent) {
10484 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010485 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070010486 intent.getAction())) {
10487 String msg = "Permission Denial: not allowed to send broadcast "
10488 + intent.getAction() + " from pid="
10489 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010490 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070010491 throw new SecurityException(msg);
10492 }
10493 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010494 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070010495 return BROADCAST_SUCCESS;
10496 }
10497 }
10498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010499 // Add to the sticky list if requested.
10500 if (sticky) {
10501 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
10502 callingPid, callingUid)
10503 != PackageManager.PERMISSION_GRANTED) {
10504 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
10505 + callingPid + ", uid=" + callingUid
10506 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010507 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010508 throw new SecurityException(msg);
10509 }
10510 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010511 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010512 + " and enforce permission " + requiredPermission);
10513 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
10514 }
10515 if (intent.getComponent() != null) {
10516 throw new SecurityException(
10517 "Sticky broadcasts can't target a specific component");
10518 }
10519 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
10520 if (list == null) {
10521 list = new ArrayList<Intent>();
10522 mStickyBroadcasts.put(intent.getAction(), list);
10523 }
10524 int N = list.size();
10525 int i;
10526 for (i=0; i<N; i++) {
10527 if (intent.filterEquals(list.get(i))) {
10528 // This sticky already exists, replace it.
10529 list.set(i, new Intent(intent));
10530 break;
10531 }
10532 }
10533 if (i >= N) {
10534 list.add(new Intent(intent));
10535 }
10536 }
10537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010538 // Figure out who all will receive this broadcast.
10539 List receivers = null;
10540 List<BroadcastFilter> registeredReceivers = null;
10541 try {
10542 if (intent.getComponent() != null) {
10543 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010544 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070010545 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010546 if (ai != null) {
10547 receivers = new ArrayList();
10548 ResolveInfo ri = new ResolveInfo();
10549 ri.activityInfo = ai;
10550 receivers.add(ri);
10551 }
10552 } else {
10553 // Need to resolve the intent to interested receivers...
10554 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
10555 == 0) {
10556 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010557 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010558 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010559 }
Mihai Preda074edef2009-05-18 17:13:31 +020010560 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010561 }
10562 } catch (RemoteException ex) {
10563 // pm is in same process, this will never happen.
10564 }
10565
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010566 final boolean replacePending =
10567 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
10568
Joe Onorato8a9b2202010-02-26 18:56:32 -080010569 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010570 + " replacePending=" + replacePending);
10571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010572 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
10573 if (!ordered && NR > 0) {
10574 // If we are not serializing this broadcast, then send the
10575 // registered receivers separately so they don't wait for the
10576 // components to be launched.
10577 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
10578 callerPackage, callingPid, callingUid, requiredPermission,
10579 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080010580 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010581 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582 TAG, "Enqueueing parallel broadcast " + r
10583 + ": prev had " + mParallelBroadcasts.size());
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010584 boolean replaced = false;
10585 if (replacePending) {
10586 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
10587 if (intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010588 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010589 "***** DROPPING PARALLEL: " + intent);
10590 mParallelBroadcasts.set(i, r);
10591 replaced = true;
10592 break;
10593 }
10594 }
10595 }
10596 if (!replaced) {
10597 mParallelBroadcasts.add(r);
10598 scheduleBroadcastsLocked();
10599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010600 registeredReceivers = null;
10601 NR = 0;
10602 }
10603
10604 // Merge into one list.
10605 int ir = 0;
10606 if (receivers != null) {
10607 // A special case for PACKAGE_ADDED: do not allow the package
10608 // being added to see this broadcast. This prevents them from
10609 // using this as a back door to get run as soon as they are
10610 // installed. Maybe in the future we want to have a special install
10611 // broadcast or such for apps, but we'd like to deliberately make
10612 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010613 String skipPackages[] = null;
10614 if (intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
10615 || intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
10616 || intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
10617 Uri data = intent.getData();
10618 if (data != null) {
10619 String pkgName = data.getSchemeSpecificPart();
10620 if (pkgName != null) {
10621 skipPackages = new String[] { pkgName };
10622 }
10623 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010624 } else if (intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010625 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070010626 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010627 if (skipPackages != null && (skipPackages.length > 0)) {
10628 for (String skipPackage : skipPackages) {
10629 if (skipPackage != null) {
10630 int NT = receivers.size();
10631 for (int it=0; it<NT; it++) {
10632 ResolveInfo curt = (ResolveInfo)receivers.get(it);
10633 if (curt.activityInfo.packageName.equals(skipPackage)) {
10634 receivers.remove(it);
10635 it--;
10636 NT--;
10637 }
10638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639 }
10640 }
10641 }
10642
10643 int NT = receivers != null ? receivers.size() : 0;
10644 int it = 0;
10645 ResolveInfo curt = null;
10646 BroadcastFilter curr = null;
10647 while (it < NT && ir < NR) {
10648 if (curt == null) {
10649 curt = (ResolveInfo)receivers.get(it);
10650 }
10651 if (curr == null) {
10652 curr = registeredReceivers.get(ir);
10653 }
10654 if (curr.getPriority() >= curt.priority) {
10655 // Insert this broadcast record into the final list.
10656 receivers.add(it, curr);
10657 ir++;
10658 curr = null;
10659 it++;
10660 NT++;
10661 } else {
10662 // Skip to the next ResolveInfo in the final list.
10663 it++;
10664 curt = null;
10665 }
10666 }
10667 }
10668 while (ir < NR) {
10669 if (receivers == null) {
10670 receivers = new ArrayList();
10671 }
10672 receivers.add(registeredReceivers.get(ir));
10673 ir++;
10674 }
10675
10676 if ((receivers != null && receivers.size() > 0)
10677 || resultTo != null) {
10678 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
10679 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080010680 receivers, resultTo, resultCode, resultData, map, ordered,
10681 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010682 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010683 TAG, "Enqueueing ordered broadcast " + r
10684 + ": prev had " + mOrderedBroadcasts.size());
10685 if (DEBUG_BROADCAST) {
10686 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010687 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010689 boolean replaced = false;
10690 if (replacePending) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010691 for (int i=mOrderedBroadcasts.size()-1; i>0; i--) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010692 if (intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010693 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010694 "***** DROPPING ORDERED: " + intent);
10695 mOrderedBroadcasts.set(i, r);
10696 replaced = true;
10697 break;
10698 }
10699 }
10700 }
10701 if (!replaced) {
10702 mOrderedBroadcasts.add(r);
10703 scheduleBroadcastsLocked();
10704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010705 }
10706
10707 return BROADCAST_SUCCESS;
10708 }
10709
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010710 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010711 // Refuse possible leaked file descriptors
10712 if (intent != null && intent.hasFileDescriptors() == true) {
10713 throw new IllegalArgumentException("File descriptors passed in Intent");
10714 }
10715
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010716 int flags = intent.getFlags();
10717
10718 if (!mProcessesReady) {
10719 // if the caller really truly claims to know what they're doing, go
10720 // ahead and allow the broadcast without launching any receivers
10721 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
10722 intent = new Intent(intent);
10723 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
10724 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
10725 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
10726 + " before boot completion");
10727 throw new IllegalStateException("Cannot broadcast before boot completed");
10728 }
10729 }
10730
10731 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
10732 throw new IllegalArgumentException(
10733 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
10734 }
10735
10736 return intent;
10737 }
10738
10739 public final int broadcastIntent(IApplicationThread caller,
10740 Intent intent, String resolvedType, IIntentReceiver resultTo,
10741 int resultCode, String resultData, Bundle map,
10742 String requiredPermission, boolean serialized, boolean sticky) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010743 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010744 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070010745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010746 final ProcessRecord callerApp = getRecordForAppLocked(caller);
10747 final int callingPid = Binder.getCallingPid();
10748 final int callingUid = Binder.getCallingUid();
10749 final long origId = Binder.clearCallingIdentity();
10750 int res = broadcastIntentLocked(callerApp,
10751 callerApp != null ? callerApp.info.packageName : null,
10752 intent, resolvedType, resultTo,
10753 resultCode, resultData, map, requiredPermission, serialized,
10754 sticky, callingPid, callingUid);
10755 Binder.restoreCallingIdentity(origId);
10756 return res;
10757 }
10758 }
10759
10760 int broadcastIntentInPackage(String packageName, int uid,
10761 Intent intent, String resolvedType, IIntentReceiver resultTo,
10762 int resultCode, String resultData, Bundle map,
10763 String requiredPermission, boolean serialized, boolean sticky) {
10764 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010765 intent = verifyBroadcastLocked(intent);
10766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010767 final long origId = Binder.clearCallingIdentity();
10768 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
10769 resultTo, resultCode, resultData, map, requiredPermission,
10770 serialized, sticky, -1, uid);
10771 Binder.restoreCallingIdentity(origId);
10772 return res;
10773 }
10774 }
10775
10776 public final void unbroadcastIntent(IApplicationThread caller,
10777 Intent intent) {
10778 // Refuse possible leaked file descriptors
10779 if (intent != null && intent.hasFileDescriptors() == true) {
10780 throw new IllegalArgumentException("File descriptors passed in Intent");
10781 }
10782
10783 synchronized(this) {
10784 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
10785 != PackageManager.PERMISSION_GRANTED) {
10786 String msg = "Permission Denial: unbroadcastIntent() from pid="
10787 + Binder.getCallingPid()
10788 + ", uid=" + Binder.getCallingUid()
10789 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010790 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010791 throw new SecurityException(msg);
10792 }
10793 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
10794 if (list != null) {
10795 int N = list.size();
10796 int i;
10797 for (i=0; i<N; i++) {
10798 if (intent.filterEquals(list.get(i))) {
10799 list.remove(i);
10800 break;
10801 }
10802 }
10803 }
10804 }
10805 }
10806
10807 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
10808 String resultData, Bundle resultExtras, boolean resultAbort,
10809 boolean explicit) {
10810 if (mOrderedBroadcasts.size() == 0) {
10811 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010812 Slog.w(TAG, "finishReceiver called but no pending broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010813 }
10814 return false;
10815 }
10816 BroadcastRecord r = mOrderedBroadcasts.get(0);
10817 if (r.receiver == null) {
10818 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010819 Slog.w(TAG, "finishReceiver called but none active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010820 }
10821 return false;
10822 }
10823 if (r.receiver != receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010824 Slog.w(TAG, "finishReceiver called but active receiver is different");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 return false;
10826 }
10827 int state = r.state;
10828 r.state = r.IDLE;
10829 if (state == r.IDLE) {
10830 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010831 Slog.w(TAG, "finishReceiver called but state is IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010832 }
10833 }
10834 r.receiver = null;
10835 r.intent.setComponent(null);
10836 if (r.curApp != null) {
10837 r.curApp.curReceiver = null;
10838 }
10839 if (r.curFilter != null) {
10840 r.curFilter.receiverList.curBroadcast = null;
10841 }
10842 r.curFilter = null;
10843 r.curApp = null;
10844 r.curComponent = null;
10845 r.curReceiver = null;
10846 mPendingBroadcast = null;
10847
10848 r.resultCode = resultCode;
10849 r.resultData = resultData;
10850 r.resultExtras = resultExtras;
10851 r.resultAbort = resultAbort;
10852
10853 // We will process the next receiver right now if this is finishing
10854 // an app receiver (which is always asynchronous) or after we have
10855 // come back from calling a receiver.
10856 return state == BroadcastRecord.APP_RECEIVE
10857 || state == BroadcastRecord.CALL_DONE_RECEIVE;
10858 }
10859
10860 public void finishReceiver(IBinder who, int resultCode, String resultData,
10861 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010862 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010863
10864 // Refuse possible leaked file descriptors
10865 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
10866 throw new IllegalArgumentException("File descriptors passed in Bundle");
10867 }
10868
10869 boolean doNext;
10870
10871 final long origId = Binder.clearCallingIdentity();
10872
10873 synchronized(this) {
10874 doNext = finishReceiverLocked(
10875 who, resultCode, resultData, resultExtras, resultAbort, true);
10876 }
10877
10878 if (doNext) {
10879 processNextBroadcast(false);
10880 }
10881 trimApplications();
10882
10883 Binder.restoreCallingIdentity(origId);
10884 }
10885
Jeff Brown4d94a762010-09-23 11:33:28 -070010886 private final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010887 if (r.nextReceiver > 0) {
10888 Object curReceiver = r.receivers.get(r.nextReceiver-1);
10889 if (curReceiver instanceof BroadcastFilter) {
10890 BroadcastFilter bf = (BroadcastFilter) curReceiver;
Doug Zongker2bec3d42009-12-04 12:52:44 -080010891 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010892 System.identityHashCode(r),
10893 r.intent.getAction(),
10894 r.nextReceiver - 1,
10895 System.identityHashCode(bf));
10896 } else {
Doug Zongker2bec3d42009-12-04 12:52:44 -080010897 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010898 System.identityHashCode(r),
10899 r.intent.getAction(),
10900 r.nextReceiver - 1,
10901 ((ResolveInfo)curReceiver).toString());
10902 }
10903 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010904 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010905 + r);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010906 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010907 System.identityHashCode(r),
10908 r.intent.getAction(),
10909 r.nextReceiver,
10910 "NONE");
10911 }
10912 }
10913
Jeff Brown4d94a762010-09-23 11:33:28 -070010914 private final void setBroadcastTimeoutLocked(long timeoutTime) {
10915 if (! mPendingBroadcastTimeoutMessage) {
10916 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
10917 mHandler.sendMessageAtTime(msg, timeoutTime);
10918 mPendingBroadcastTimeoutMessage = true;
10919 }
10920 }
10921
10922 private final void cancelBroadcastTimeoutLocked() {
10923 if (mPendingBroadcastTimeoutMessage) {
10924 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG);
10925 mPendingBroadcastTimeoutMessage = false;
10926 }
10927 }
10928
10929 private final void broadcastTimeoutLocked(boolean fromMsg) {
10930 if (fromMsg) {
10931 mPendingBroadcastTimeoutMessage = false;
10932 }
10933
10934 if (mOrderedBroadcasts.size() == 0) {
10935 return;
10936 }
10937
10938 long now = SystemClock.uptimeMillis();
10939 BroadcastRecord r = mOrderedBroadcasts.get(0);
10940 if (fromMsg) {
10941 if (mDidDexOpt) {
10942 // Delay timeouts until dexopt finishes.
10943 mDidDexOpt = false;
10944 long timeoutTime = SystemClock.uptimeMillis() + BROADCAST_TIMEOUT;
10945 setBroadcastTimeoutLocked(timeoutTime);
10946 return;
10947 }
10948 if (! mProcessesReady) {
10949 // Only process broadcast timeouts if the system is ready. That way
10950 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
10951 // to do heavy lifting for system up.
10952 return;
10953 }
10954
10955 long timeoutTime = r.receiverTime + BROADCAST_TIMEOUT;
10956 if (timeoutTime > now) {
10957 // We can observe premature timeouts because we do not cancel and reset the
10958 // broadcast timeout message after each receiver finishes. Instead, we set up
10959 // an initial timeout then kick it down the road a little further as needed
10960 // when it expires.
10961 if (DEBUG_BROADCAST) Slog.v(TAG,
10962 "Premature timeout @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
10963 + timeoutTime);
10964 setBroadcastTimeoutLocked(timeoutTime);
10965 return;
10966 }
10967 }
10968
10969 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
10970 + ", started " + (now - r.receiverTime) + "ms ago");
10971 r.receiverTime = now;
10972 r.anrCount++;
10973
10974 // Current receiver has passed its expiration date.
10975 if (r.nextReceiver <= 0) {
10976 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
10977 return;
10978 }
10979
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010980 ProcessRecord app = null;
10981 String anrMessage = null;
10982
Jeff Brown4d94a762010-09-23 11:33:28 -070010983 Object curReceiver = r.receivers.get(r.nextReceiver-1);
10984 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
10985 logBroadcastReceiverDiscardLocked(r);
10986 if (curReceiver instanceof BroadcastFilter) {
10987 BroadcastFilter bf = (BroadcastFilter)curReceiver;
10988 if (bf.receiverList.pid != 0
10989 && bf.receiverList.pid != MY_PID) {
10990 synchronized (this.mPidsSelfLocked) {
10991 app = this.mPidsSelfLocked.get(
10992 bf.receiverList.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994 }
Jeff Brown4d94a762010-09-23 11:33:28 -070010995 } else {
10996 app = r.curApp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010997 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010998
Jeff Brown4d94a762010-09-23 11:33:28 -070010999 if (app != null) {
11000 anrMessage = "Broadcast of " + r.intent.toString();
11001 }
11002
11003 if (mPendingBroadcast == r) {
11004 mPendingBroadcast = null;
11005 }
11006
11007 // Move on to the next receiver.
11008 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
11009 r.resultExtras, r.resultAbort, true);
11010 scheduleBroadcastsLocked();
11011
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011012 if (anrMessage != null) {
Jeff Brown4d94a762010-09-23 11:33:28 -070011013 // Post the ANR to the handler since we do not want to process ANRs while
11014 // potentially holding our lock.
11015 mHandler.post(new AppNotResponding(app, anrMessage));
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011017 }
11018
11019 private final void processCurBroadcastLocked(BroadcastRecord r,
11020 ProcessRecord app) throws RemoteException {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011021 if (DEBUG_BROADCAST) Slog.v(TAG,
11022 "Process cur broadcast " + r + " for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 if (app.thread == null) {
11024 throw new RemoteException();
11025 }
11026 r.receiver = app.thread.asBinder();
11027 r.curApp = app;
11028 app.curReceiver = r;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011029 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011030
11031 // Tell the application to launch this receiver.
11032 r.intent.setComponent(r.curComponent);
11033
11034 boolean started = false;
11035 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011036 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011037 "Delivering to component " + r.curComponent
11038 + ": " + r);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011039 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011040 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
11041 r.resultCode, r.resultData, r.resultExtras, r.ordered);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011042 if (DEBUG_BROADCAST) Slog.v(TAG,
11043 "Process cur broadcast " + r + " DELIVERED for app " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011044 started = true;
11045 } finally {
11046 if (!started) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011047 if (DEBUG_BROADCAST) Slog.v(TAG,
11048 "Process cur broadcast " + r + ": NOT STARTED!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011049 r.receiver = null;
11050 r.curApp = null;
11051 app.curReceiver = null;
11052 }
11053 }
11054
11055 }
11056
Jeff Brown4d94a762010-09-23 11:33:28 -070011057 static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011058 Intent intent, int resultCode, String data, Bundle extras,
11059 boolean ordered, boolean sticky) throws RemoteException {
Jeff Brown4d94a762010-09-23 11:33:28 -070011060 // Send the intent to the receiver asynchronously using one-way binder calls.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011061 if (app != null && app.thread != null) {
11062 // If we have an app thread, do the call through that so it is
11063 // correctly ordered with other one-way calls.
11064 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011065 data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011066 } else {
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011067 receiver.performReceive(intent, resultCode, data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011068 }
11069 }
11070
Jeff Brown4d94a762010-09-23 11:33:28 -070011071 private final void deliverToRegisteredReceiverLocked(BroadcastRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011072 BroadcastFilter filter, boolean ordered) {
11073 boolean skip = false;
11074 if (filter.requiredPermission != null) {
11075 int perm = checkComponentPermission(filter.requiredPermission,
11076 r.callingPid, r.callingUid, -1);
11077 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011078 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011079 + r.intent.toString()
11080 + " from " + r.callerPackage + " (pid="
11081 + r.callingPid + ", uid=" + r.callingUid + ")"
11082 + " requires " + filter.requiredPermission
11083 + " due to registered receiver " + filter);
11084 skip = true;
11085 }
11086 }
11087 if (r.requiredPermission != null) {
11088 int perm = checkComponentPermission(r.requiredPermission,
11089 filter.receiverList.pid, filter.receiverList.uid, -1);
11090 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011091 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011092 + r.intent.toString()
11093 + " to " + filter.receiverList.app
11094 + " (pid=" + filter.receiverList.pid
11095 + ", uid=" + filter.receiverList.uid + ")"
11096 + " requires " + r.requiredPermission
11097 + " due to sender " + r.callerPackage
11098 + " (uid " + r.callingUid + ")");
11099 skip = true;
11100 }
11101 }
11102
11103 if (!skip) {
11104 // If this is not being sent as an ordered broadcast, then we
11105 // don't want to touch the fields that keep track of the current
11106 // state of ordered broadcasts.
11107 if (ordered) {
11108 r.receiver = filter.receiverList.receiver.asBinder();
11109 r.curFilter = filter;
11110 filter.receiverList.curBroadcast = r;
11111 r.state = BroadcastRecord.CALL_IN_RECEIVE;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011112 if (filter.receiverList.app != null) {
11113 // Bump hosting application to no longer be in background
11114 // scheduling class. Note that we can't do that if there
11115 // isn't an app... but we can only be in that case for
11116 // things that directly call the IActivityManager API, which
11117 // are already core system stuff so don't matter for this.
11118 r.curApp = filter.receiverList.app;
11119 filter.receiverList.app.curReceiver = r;
11120 updateOomAdjLocked();
11121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011122 }
11123 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011124 if (DEBUG_BROADCAST_LIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011125 int seq = r.intent.getIntExtra("seq", -1);
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011126 Slog.i(TAG, "Delivering to " + filter
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011127 + " (seq=" + seq + "): " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011128 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011129 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011130 new Intent(r.intent), r.resultCode,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011131 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011132 if (ordered) {
11133 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
11134 }
11135 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011136 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011137 if (ordered) {
11138 r.receiver = null;
11139 r.curFilter = null;
11140 filter.receiverList.curBroadcast = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011141 if (filter.receiverList.app != null) {
11142 filter.receiverList.app.curReceiver = null;
11143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011144 }
11145 }
11146 }
11147 }
11148
Dianne Hackborn12527f92009-11-11 17:39:50 -080011149 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
11150 if (r.callingUid < 0) {
11151 // This was from a registerReceiver() call; ignore it.
11152 return;
11153 }
11154 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
11155 MAX_BROADCAST_HISTORY-1);
11156 r.finishTime = SystemClock.uptimeMillis();
11157 mBroadcastHistory[0] = r;
11158 }
11159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011160 private final void processNextBroadcast(boolean fromMsg) {
11161 synchronized(this) {
11162 BroadcastRecord r;
11163
Joe Onorato8a9b2202010-02-26 18:56:32 -080011164 if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 + mParallelBroadcasts.size() + " broadcasts, "
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011166 + mOrderedBroadcasts.size() + " ordered broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167
11168 updateCpuStats();
11169
11170 if (fromMsg) {
11171 mBroadcastsScheduled = false;
11172 }
11173
11174 // First, deliver any non-serialized broadcasts right away.
11175 while (mParallelBroadcasts.size() > 0) {
11176 r = mParallelBroadcasts.remove(0);
Dianne Hackborn12527f92009-11-11 17:39:50 -080011177 r.dispatchTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011178 final int N = r.receivers.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011179 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011180 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011181 for (int i=0; i<N; i++) {
11182 Object target = r.receivers.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011183 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011184 "Delivering non-ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011185 + target + ": " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070011186 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011187 }
Dianne Hackborn12527f92009-11-11 17:39:50 -080011188 addBroadcastToHistoryLocked(r);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011189 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011190 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011191 }
11192
11193 // Now take care of the next serialized one...
11194
11195 // If we are waiting for a process to come up to handle the next
11196 // broadcast, then do nothing at this point. Just in case, we
11197 // check that the process we're waiting for still exists.
11198 if (mPendingBroadcast != null) {
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070011199 if (DEBUG_BROADCAST_LIGHT) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011200 Slog.v(TAG, "processNextBroadcast: waiting for "
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070011201 + mPendingBroadcast.curApp);
11202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011203
11204 boolean isDead;
11205 synchronized (mPidsSelfLocked) {
11206 isDead = (mPidsSelfLocked.get(mPendingBroadcast.curApp.pid) == null);
11207 }
11208 if (!isDead) {
11209 // It's still alive, so keep waiting
11210 return;
11211 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011212 Slog.w(TAG, "pending app " + mPendingBroadcast.curApp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011213 + " died before responding to broadcast");
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011214 mPendingBroadcast.state = BroadcastRecord.IDLE;
11215 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011216 mPendingBroadcast = null;
11217 }
11218 }
11219
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011220 boolean looped = false;
11221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011222 do {
11223 if (mOrderedBroadcasts.size() == 0) {
11224 // No more broadcasts pending, so all done!
11225 scheduleAppGcsLocked();
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011226 if (looped) {
11227 // If we had finished the last ordered broadcast, then
11228 // make sure all processes have correct oom and sched
11229 // adjustments.
11230 updateOomAdjLocked();
11231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011232 return;
11233 }
11234 r = mOrderedBroadcasts.get(0);
11235 boolean forceReceive = false;
11236
11237 // Ensure that even if something goes awry with the timeout
11238 // detection, we catch "hung" broadcasts here, discard them,
Jeff Hamiltonacf84742010-05-25 22:10:18 -050011239 // and continue to make progress.
11240 //
11241 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
Jeff Brown4d94a762010-09-23 11:33:28 -070011242 // receivers don't get executed with timeouts. They're intended for
Jeff Hamiltonacf84742010-05-25 22:10:18 -050011243 // one time heavy lifting after system upgrades and can take
11244 // significant amounts of time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011245 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011246 if (mProcessesReady && r.dispatchTime > 0) {
Jeff Hamiltonacf84742010-05-25 22:10:18 -050011247 long now = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011248 if ((numReceivers > 0) &&
11249 (now > r.dispatchTime + (2*BROADCAST_TIMEOUT*numReceivers))) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011250 Slog.w(TAG, "Hung broadcast discarded after timeout failure:"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011251 + " now=" + now
11252 + " dispatchTime=" + r.dispatchTime
Dianne Hackborn12527f92009-11-11 17:39:50 -080011253 + " startTime=" + r.receiverTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011254 + " intent=" + r.intent
11255 + " numReceivers=" + numReceivers
11256 + " nextReceiver=" + r.nextReceiver
11257 + " state=" + r.state);
Jeff Brown4d94a762010-09-23 11:33:28 -070011258 broadcastTimeoutLocked(false); // forcibly finish this broadcast
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011259 forceReceive = true;
11260 r.state = BroadcastRecord.IDLE;
11261 }
11262 }
11263
11264 if (r.state != BroadcastRecord.IDLE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011265 if (DEBUG_BROADCAST) Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011266 "processNextBroadcast() called when not idle (state="
11267 + r.state + ")");
11268 return;
11269 }
11270
11271 if (r.receivers == null || r.nextReceiver >= numReceivers
11272 || r.resultAbort || forceReceive) {
11273 // No more receivers for this broadcast! Send the final
11274 // result if requested...
11275 if (r.resultTo != null) {
11276 try {
11277 if (DEBUG_BROADCAST) {
11278 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011279 Slog.i(TAG, "Finishing broadcast " + r.intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011280 + " seq=" + seq + " app=" + r.callerApp);
11281 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011282 performReceiveLocked(r.callerApp, r.resultTo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011283 new Intent(r.intent), r.resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070011284 r.resultData, r.resultExtras, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011285 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011286 Slog.w(TAG, "Failure sending broadcast result of " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 }
11288 }
11289
Joe Onorato8a9b2202010-02-26 18:56:32 -080011290 if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
Jeff Brown4d94a762010-09-23 11:33:28 -070011291 cancelBroadcastTimeoutLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011292
Joe Onorato8a9b2202010-02-26 18:56:32 -080011293 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011294 + r);
11295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011296 // ... and on to the next...
Dianne Hackborn12527f92009-11-11 17:39:50 -080011297 addBroadcastToHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011298 mOrderedBroadcasts.remove(0);
11299 r = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011300 looped = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011301 continue;
11302 }
11303 } while (r == null);
11304
11305 // Get the next receiver...
11306 int recIdx = r.nextReceiver++;
11307
11308 // Keep track of when this receiver started, and make sure there
11309 // is a timeout message pending to kill it if need be.
Dianne Hackborn12527f92009-11-11 17:39:50 -080011310 r.receiverTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011311 if (recIdx == 0) {
Dianne Hackborn12527f92009-11-11 17:39:50 -080011312 r.dispatchTime = r.receiverTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313
Joe Onorato8a9b2202010-02-26 18:56:32 -080011314 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011315 + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070011316 }
11317 if (! mPendingBroadcastTimeoutMessage) {
11318 long timeoutTime = r.receiverTime + BROADCAST_TIMEOUT;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011319 if (DEBUG_BROADCAST) Slog.v(TAG,
Jeff Brown4d94a762010-09-23 11:33:28 -070011320 "Submitting BROADCAST_TIMEOUT_MSG for " + r + " at " + timeoutTime);
11321 setBroadcastTimeoutLocked(timeoutTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011322 }
11323
11324 Object nextReceiver = r.receivers.get(recIdx);
11325 if (nextReceiver instanceof BroadcastFilter) {
11326 // Simple case: this is a registered receiver who gets
11327 // a direct call.
11328 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011329 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011330 "Delivering ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 + filter + ": " + r);
Jeff Brown4d94a762010-09-23 11:33:28 -070011332 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 if (r.receiver == null || !r.ordered) {
11334 // The receiver has already finished, so schedule to
11335 // process the next one.
Dianne Hackborn399cccb2010-04-13 22:57:49 -070011336 if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing: ordered="
11337 + r.ordered + " receiver=" + r.receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011338 r.state = BroadcastRecord.IDLE;
11339 scheduleBroadcastsLocked();
11340 }
11341 return;
11342 }
11343
11344 // Hard case: need to instantiate the receiver, possibly
11345 // starting its application process to host it.
11346
11347 ResolveInfo info =
11348 (ResolveInfo)nextReceiver;
11349
11350 boolean skip = false;
11351 int perm = checkComponentPermission(info.activityInfo.permission,
11352 r.callingPid, r.callingUid,
11353 info.activityInfo.exported
11354 ? -1 : info.activityInfo.applicationInfo.uid);
11355 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011356 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011357 + r.intent.toString()
11358 + " from " + r.callerPackage + " (pid=" + r.callingPid
11359 + ", uid=" + r.callingUid + ")"
11360 + " requires " + info.activityInfo.permission
11361 + " due to receiver " + info.activityInfo.packageName
11362 + "/" + info.activityInfo.name);
11363 skip = true;
11364 }
11365 if (r.callingUid != Process.SYSTEM_UID &&
11366 r.requiredPermission != null) {
11367 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011368 perm = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 checkPermission(r.requiredPermission,
11370 info.activityInfo.applicationInfo.packageName);
11371 } catch (RemoteException e) {
11372 perm = PackageManager.PERMISSION_DENIED;
11373 }
11374 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011375 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011376 + r.intent + " to "
11377 + info.activityInfo.applicationInfo.packageName
11378 + " requires " + r.requiredPermission
11379 + " due to sender " + r.callerPackage
11380 + " (uid " + r.callingUid + ")");
11381 skip = true;
11382 }
11383 }
11384 if (r.curApp != null && r.curApp.crashing) {
11385 // If the target process is crashing, just skip it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011386 if (DEBUG_BROADCAST) Slog.v(TAG,
11387 "Skipping deliver ordered " + r + " to " + r.curApp
11388 + ": process crashing");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011389 skip = true;
11390 }
11391
11392 if (skip) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011393 if (DEBUG_BROADCAST) Slog.v(TAG,
11394 "Skipping delivery of ordered " + r + " for whatever reason");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011395 r.receiver = null;
11396 r.curFilter = null;
11397 r.state = BroadcastRecord.IDLE;
11398 scheduleBroadcastsLocked();
11399 return;
11400 }
11401
11402 r.state = BroadcastRecord.APP_RECEIVE;
11403 String targetProcess = info.activityInfo.processName;
11404 r.curComponent = new ComponentName(
11405 info.activityInfo.applicationInfo.packageName,
11406 info.activityInfo.name);
11407 r.curReceiver = info.activityInfo;
11408
11409 // Is this receiver's application already running?
11410 ProcessRecord app = getProcessRecordLocked(targetProcess,
11411 info.activityInfo.applicationInfo.uid);
11412 if (app != null && app.thread != null) {
11413 try {
11414 processCurBroadcastLocked(r, app);
11415 return;
11416 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011417 Slog.w(TAG, "Exception when sending broadcast to "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 + r.curComponent, e);
11419 }
11420
11421 // If a dead object exception was thrown -- fall through to
11422 // restart the application.
11423 }
11424
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011425 // Not running -- get it started, to be executed when the app comes up.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011426 if (DEBUG_BROADCAST) Slog.v(TAG,
11427 "Need to start app " + targetProcess + " for broadcast " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011428 if ((r.curApp=startProcessLocked(targetProcess,
11429 info.activityInfo.applicationInfo, true,
11430 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011431 "broadcast", r.curComponent,
11432 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0))
11433 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011434 // Ah, this recipient is unavailable. Finish it if necessary,
11435 // and mark the broadcast record as ready for the next.
Joe Onorato8a9b2202010-02-26 18:56:32 -080011436 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011437 + info.activityInfo.applicationInfo.packageName + "/"
11438 + info.activityInfo.applicationInfo.uid + " for broadcast "
11439 + r.intent + ": process is bad");
Jeff Brown4d94a762010-09-23 11:33:28 -070011440 logBroadcastReceiverDiscardLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011441 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
11442 r.resultExtras, r.resultAbort, true);
11443 scheduleBroadcastsLocked();
11444 r.state = BroadcastRecord.IDLE;
11445 return;
11446 }
11447
11448 mPendingBroadcast = r;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011449 mPendingBroadcastRecvIndex = recIdx;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011450 }
11451 }
11452
11453 // =========================================================
11454 // INSTRUMENTATION
11455 // =========================================================
11456
11457 public boolean startInstrumentation(ComponentName className,
11458 String profileFile, int flags, Bundle arguments,
11459 IInstrumentationWatcher watcher) {
11460 // Refuse possible leaked file descriptors
11461 if (arguments != null && arguments.hasFileDescriptors()) {
11462 throw new IllegalArgumentException("File descriptors passed in Bundle");
11463 }
11464
11465 synchronized(this) {
11466 InstrumentationInfo ii = null;
11467 ApplicationInfo ai = null;
11468 try {
11469 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011470 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011471 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011472 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 } catch (PackageManager.NameNotFoundException e) {
11474 }
11475 if (ii == null) {
11476 reportStartInstrumentationFailure(watcher, className,
11477 "Unable to find instrumentation info for: " + className);
11478 return false;
11479 }
11480 if (ai == null) {
11481 reportStartInstrumentationFailure(watcher, className,
11482 "Unable to find instrumentation target package: " + ii.targetPackage);
11483 return false;
11484 }
11485
11486 int match = mContext.getPackageManager().checkSignatures(
11487 ii.targetPackage, ii.packageName);
11488 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11489 String msg = "Permission Denial: starting instrumentation "
11490 + className + " from pid="
11491 + Binder.getCallingPid()
11492 + ", uid=" + Binder.getCallingPid()
11493 + " not allowed because package " + ii.packageName
11494 + " does not have a signature matching the target "
11495 + ii.targetPackage;
11496 reportStartInstrumentationFailure(watcher, className, msg);
11497 throw new SecurityException(msg);
11498 }
11499
11500 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080011501 forceStopPackageLocked(ii.targetPackage, -1, true, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011502 ProcessRecord app = addAppLocked(ai);
11503 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011504 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011505 app.instrumentationProfileFile = profileFile;
11506 app.instrumentationArguments = arguments;
11507 app.instrumentationWatcher = watcher;
11508 app.instrumentationResultClass = className;
11509 Binder.restoreCallingIdentity(origId);
11510 }
11511
11512 return true;
11513 }
11514
11515 /**
11516 * Report errors that occur while attempting to start Instrumentation. Always writes the
11517 * error to the logs, but if somebody is watching, send the report there too. This enables
11518 * the "am" command to report errors with more information.
11519 *
11520 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11521 * @param cn The component name of the instrumentation.
11522 * @param report The error report.
11523 */
11524 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11525 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011526 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011527 try {
11528 if (watcher != null) {
11529 Bundle results = new Bundle();
11530 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11531 results.putString("Error", report);
11532 watcher.instrumentationStatus(cn, -1, results);
11533 }
11534 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011535 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011536 }
11537 }
11538
11539 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11540 if (app.instrumentationWatcher != null) {
11541 try {
11542 // NOTE: IInstrumentationWatcher *must* be oneway here
11543 app.instrumentationWatcher.instrumentationFinished(
11544 app.instrumentationClass,
11545 resultCode,
11546 results);
11547 } catch (RemoteException e) {
11548 }
11549 }
11550 app.instrumentationWatcher = null;
11551 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011552 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011553 app.instrumentationProfileFile = null;
11554 app.instrumentationArguments = null;
11555
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080011556 forceStopPackageLocked(app.processName, -1, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011557 }
11558
11559 public void finishInstrumentation(IApplicationThread target,
11560 int resultCode, Bundle results) {
11561 // Refuse possible leaked file descriptors
11562 if (results != null && results.hasFileDescriptors()) {
11563 throw new IllegalArgumentException("File descriptors passed in Intent");
11564 }
11565
11566 synchronized(this) {
11567 ProcessRecord app = getRecordForAppLocked(target);
11568 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011569 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011570 return;
11571 }
11572 final long origId = Binder.clearCallingIdentity();
11573 finishInstrumentationLocked(app, resultCode, results);
11574 Binder.restoreCallingIdentity(origId);
11575 }
11576 }
11577
11578 // =========================================================
11579 // CONFIGURATION
11580 // =========================================================
11581
11582 public ConfigurationInfo getDeviceConfigurationInfo() {
11583 ConfigurationInfo config = new ConfigurationInfo();
11584 synchronized (this) {
11585 config.reqTouchScreen = mConfiguration.touchscreen;
11586 config.reqKeyboardType = mConfiguration.keyboard;
11587 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011588 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
11589 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011590 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
11591 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011592 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
11593 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011594 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
11595 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070011596 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011597 }
11598 return config;
11599 }
11600
11601 public Configuration getConfiguration() {
11602 Configuration ci;
11603 synchronized(this) {
11604 ci = new Configuration(mConfiguration);
11605 }
11606 return ci;
11607 }
11608
11609 public void updateConfiguration(Configuration values) {
11610 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11611 "updateConfiguration()");
11612
11613 synchronized(this) {
11614 if (values == null && mWindowManager != null) {
11615 // sentinel: fetch the current configuration from the window manager
11616 values = mWindowManager.computeNewConfiguration();
11617 }
11618
11619 final long origId = Binder.clearCallingIdentity();
11620 updateConfigurationLocked(values, null);
11621 Binder.restoreCallingIdentity(origId);
11622 }
11623 }
11624
11625 /**
11626 * Do either or both things: (1) change the current configuration, and (2)
11627 * make sure the given activity is running with the (now) current
11628 * configuration. Returns true if the activity has been left running, or
11629 * false if <var>starting</var> is being destroyed to match the new
11630 * configuration.
11631 */
11632 public boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011633 ActivityRecord starting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011634 int changes = 0;
11635
11636 boolean kept = true;
11637
11638 if (values != null) {
11639 Configuration newConfig = new Configuration(mConfiguration);
11640 changes = newConfig.updateFrom(values);
11641 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011642 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011643 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011644 }
11645
Doug Zongker2bec3d42009-12-04 12:52:44 -080011646 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011647
11648 if (values.locale != null) {
11649 saveLocaleLocked(values.locale,
11650 !values.locale.equals(mConfiguration.locale),
11651 values.userSetLocale);
11652 }
11653
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011654 mConfigurationSeq++;
11655 if (mConfigurationSeq <= 0) {
11656 mConfigurationSeq = 1;
11657 }
11658 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011659 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011660 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011661
11662 AttributeCache ac = AttributeCache.instance();
11663 if (ac != null) {
11664 ac.updateConfiguration(mConfiguration);
11665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011666
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011667 if (Settings.System.hasInterestingConfigurationChanges(changes)) {
11668 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
11669 msg.obj = new Configuration(mConfiguration);
11670 mHandler.sendMessage(msg);
11671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011672
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011673 for (int i=mLruProcesses.size()-1; i>=0; i--) {
11674 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011675 try {
11676 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011677 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011678 + app.processName + " new config " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011679 app.thread.scheduleConfigurationChanged(mConfiguration);
11680 }
11681 } catch (Exception e) {
11682 }
11683 }
11684 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011685 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
11686 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011687 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
11688 null, false, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011689 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
11690 broadcastIntentLocked(null, null,
11691 new Intent(Intent.ACTION_LOCALE_CHANGED),
11692 null, null, 0, null, null,
11693 null, false, false, MY_PID, Process.SYSTEM_UID);
11694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011695 }
11696 }
11697
11698 if (changes != 0 && starting == null) {
11699 // If the configuration changed, and the caller is not already
11700 // in the process of starting an activity, then find the top
11701 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011702 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011703 }
11704
11705 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011706 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011707 if (kept) {
11708 // If this didn't result in the starting activity being
11709 // destroyed, then we need to make sure at this point that all
11710 // other activities are made visible.
Joe Onorato8a9b2202010-02-26 18:56:32 -080011711 if (DEBUG_SWITCH) Slog.i(TAG, "Config didn't destroy " + starting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011712 + ", ensuring others are correct.");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011713 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011714 }
11715 }
11716
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011717 if (values != null && mWindowManager != null) {
11718 mWindowManager.setNewConfiguration(mConfiguration);
11719 }
11720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011721 return kept;
11722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011723
11724 /**
11725 * Save the locale. You must be inside a synchronized (this) block.
11726 */
11727 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
11728 if(isDiff) {
11729 SystemProperties.set("user.language", l.getLanguage());
11730 SystemProperties.set("user.region", l.getCountry());
11731 }
11732
11733 if(isPersist) {
11734 SystemProperties.set("persist.sys.language", l.getLanguage());
11735 SystemProperties.set("persist.sys.country", l.getCountry());
11736 SystemProperties.set("persist.sys.localevar", l.getVariant());
11737 }
11738 }
11739
11740 // =========================================================
11741 // LIFETIME MANAGEMENT
11742 // =========================================================
11743
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011744 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
11745 ProcessRecord TOP_APP, boolean recursed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011746 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011747 // This adjustment has already been computed. If we are calling
11748 // from the top, we may have already computed our adjustment with
11749 // an earlier hidden adjustment that isn't really for us... if
11750 // so, use the new hidden adjustment.
11751 if (!recursed && app.hidden) {
11752 app.curAdj = hiddenAdj;
11753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011754 return app.curAdj;
11755 }
11756
11757 if (app.thread == null) {
11758 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011759 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011760 return (app.curAdj=EMPTY_APP_ADJ);
11761 }
11762
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011763 if (app.maxAdj <= FOREGROUND_APP_ADJ) {
11764 // The max adjustment doesn't allow this app to be anything
11765 // below foreground, so it is not worth doing work for it.
11766 app.adjType = "fixed";
11767 app.adjSeq = mAdjSeq;
11768 app.curRawAdj = app.maxAdj;
Dianne Hackborn287952c2010-09-22 22:34:31 -070011769 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011770 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
11771 return (app.curAdj=app.maxAdj);
11772 }
11773
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011774 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011775 app.adjSource = null;
11776 app.adjTarget = null;
Dianne Hackborn287952c2010-09-22 22:34:31 -070011777 app.keeping = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011778 app.empty = false;
11779 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011780
The Android Open Source Project4df24232009-03-05 14:34:35 -080011781 // Determine the importance of the process, starting with most
11782 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011783 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011784 int schedGroup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011785 int N;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011786 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011787 // The last app on the list is the foreground app.
11788 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011789 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011790 app.adjType = "top-activity";
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011791 } else if (app.instrumentationClass != null) {
11792 // Don't want to kill running instrumentation.
11793 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011794 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011795 app.adjType = "instrumentation";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011796 } else if (app.curReceiver != null ||
11797 (mPendingBroadcast != null && mPendingBroadcast.curApp == app)) {
11798 // An app that is currently receiving a broadcast also
11799 // counts as being in the foreground.
11800 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011801 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011802 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011803 } else if (app.executingServices.size() > 0) {
11804 // An app that is currently executing a service callback also
11805 // counts as being in the foreground.
11806 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011807 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011808 app.adjType = "exec-service";
11809 } else if (app.foregroundServices) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011810 // The user is aware of this app, so make it visible.
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011811 adj = PERCEPTIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011812 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011813 app.adjType = "foreground-service";
11814 } else if (app.forcingToForeground != null) {
11815 // The user is aware of this app, so make it visible.
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011816 adj = PERCEPTIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011817 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011818 app.adjType = "force-foreground";
11819 app.adjSource = app.forcingToForeground;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011820 } else if (app == mHeavyWeightProcess) {
11821 // We don't want to kill the current heavy-weight process.
11822 adj = HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080011823 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011824 app.adjType = "heavy";
The Android Open Source Project4df24232009-03-05 14:34:35 -080011825 } else if (app == mHomeProcess) {
11826 // This process is hosting what we currently consider to be the
11827 // home app, so we don't want to let it go into the background.
11828 adj = HOME_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011829 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011830 app.adjType = "home";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011831 } else if ((N=app.activities.size()) != 0) {
11832 // This app is in the background with paused activities.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011833 app.hidden = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011834 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011835 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011836 app.adjType = "bg-activities";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011837 N = app.activities.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011838 for (int j=0; j<N; j++) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080011839 ActivityRecord r = app.activities.get(j);
11840 if (r.visible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011841 // This app has a visible activity!
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011842 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011843 adj = VISIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011844 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011845 app.adjType = "visible";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011846 break;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080011847 } else if (r.state == ActivityState.PAUSING
11848 || r.state == ActivityState.PAUSED
11849 || r.state == ActivityState.STOPPING) {
11850 adj = PERCEPTIBLE_APP_ADJ;
11851 app.adjType = "stopping";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011852 }
11853 }
11854 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011855 // A very not-needed process. If this is lower in the lru list,
11856 // we will push it in to the empty bucket.
11857 app.hidden = true;
11858 app.empty = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011859 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011860 adj = hiddenAdj;
11861 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011862 }
11863
Joe Onorato8a9b2202010-02-26 18:56:32 -080011864 //Slog.i(TAG, "OOM " + app + ": initial adj=" + adj);
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011865
The Android Open Source Project4df24232009-03-05 14:34:35 -080011866 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011867 // there are applications dependent on our services or providers, but
11868 // this gives us a baseline and makes sure we don't get into an
11869 // infinite recursion.
11870 app.adjSeq = mAdjSeq;
11871 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011872
Christopher Tate6fa95972009-06-05 18:43:55 -070011873 if (mBackupTarget != null && app == mBackupTarget.app) {
11874 // If possible we want to avoid killing apps while they're being backed up
11875 if (adj > BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011876 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Christopher Tate6fa95972009-06-05 18:43:55 -070011877 adj = BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011878 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011879 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070011880 }
11881 }
11882
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011883 if (app.services.size() != 0 && (adj > FOREGROUND_APP_ADJ
11884 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011885 final long now = SystemClock.uptimeMillis();
11886 // This process is more important if the top activity is
11887 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070011888 Iterator<ServiceRecord> jt = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011889 while (jt.hasNext() && adj > FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011890 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011891 if (s.startRequested) {
11892 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
11893 // This service has seen some activity within
11894 // recent memory, so we will keep its process ahead
11895 // of the background processes.
11896 if (adj > SECONDARY_SERVER_ADJ) {
11897 adj = SECONDARY_SERVER_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011898 app.adjType = "started-services";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011899 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011900 }
11901 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080011902 // If we have let the service slide into the background
11903 // state, still have some text describing what it is doing
11904 // even though the service no longer has an impact.
11905 if (adj > SECONDARY_SERVER_ADJ) {
11906 app.adjType = "started-bg-services";
11907 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011908 // Don't kill this process because it is doing work; it
11909 // has said it is doing work.
11910 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011911 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011912 if (s.connections.size() > 0 && (adj > FOREGROUND_APP_ADJ
11913 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011914 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011915 = s.connections.values().iterator();
11916 while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011917 ArrayList<ConnectionRecord> clist = kt.next();
11918 for (int i=0; i<clist.size() && adj > FOREGROUND_APP_ADJ; i++) {
11919 // XXX should compute this based on the max of
11920 // all connected clients.
11921 ConnectionRecord cr = clist.get(i);
11922 if (cr.binding.client == app) {
11923 // Binding to ourself is not interesting.
11924 continue;
11925 }
11926 if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
11927 ProcessRecord client = cr.binding.client;
11928 int myHiddenAdj = hiddenAdj;
11929 if (myHiddenAdj > client.hiddenAdj) {
11930 if (client.hiddenAdj >= VISIBLE_APP_ADJ) {
11931 myHiddenAdj = client.hiddenAdj;
11932 } else {
11933 myHiddenAdj = VISIBLE_APP_ADJ;
11934 }
11935 }
11936 int clientAdj = computeOomAdjLocked(
11937 client, myHiddenAdj, TOP_APP, true);
11938 if (adj > clientAdj) {
11939 adj = clientAdj >= VISIBLE_APP_ADJ
11940 ? clientAdj : VISIBLE_APP_ADJ;
11941 if (!client.hidden) {
11942 app.hidden = false;
11943 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011944 if (client.keeping) {
11945 app.keeping = true;
11946 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011947 app.adjType = "service";
11948 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
11949 .REASON_SERVICE_IN_USE;
11950 app.adjSource = cr.binding.client;
11951 app.adjTarget = s.name;
11952 }
11953 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
11954 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
11955 schedGroup = Process.THREAD_GROUP_DEFAULT;
11956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011957 }
11958 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011959 ActivityRecord a = cr.activity;
11960 //if (a != null) {
11961 // Slog.i(TAG, "Connection to " + a ": state=" + a.state);
11962 //}
11963 if (a != null && adj > FOREGROUND_APP_ADJ &&
11964 (a.state == ActivityState.RESUMED
11965 || a.state == ActivityState.PAUSING)) {
11966 adj = FOREGROUND_APP_ADJ;
11967 schedGroup = Process.THREAD_GROUP_DEFAULT;
11968 app.hidden = false;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011969 app.adjType = "service";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011970 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
11971 .REASON_SERVICE_IN_USE;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011972 app.adjSource = a;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070011973 app.adjTarget = s.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011975 }
11976 }
11977 }
11978 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070011979
Dianne Hackborn287952c2010-09-22 22:34:31 -070011980 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070011981 // would like to avoid killing it unless it would prevent the current
11982 // application from running. By default we put the process in
11983 // with the rest of the background processes; as we scan through
11984 // its services we may bump it up from there.
11985 if (adj > hiddenAdj) {
11986 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011987 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070011988 app.adjType = "bg-services";
11989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011990 }
11991
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011992 if (app.pubProviders.size() != 0 && (adj > FOREGROUND_APP_ADJ
11993 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011994 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011995 while (jt.hasNext() && (adj > FOREGROUND_APP_ADJ
11996 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011997 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011998 if (cpr.clients.size() != 0) {
11999 Iterator<ProcessRecord> kt = cpr.clients.iterator();
12000 while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
12001 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070012002 if (client == app) {
12003 // Being our own client is not interesting.
12004 continue;
12005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012006 int myHiddenAdj = hiddenAdj;
12007 if (myHiddenAdj > client.hiddenAdj) {
12008 if (client.hiddenAdj > FOREGROUND_APP_ADJ) {
12009 myHiddenAdj = client.hiddenAdj;
12010 } else {
12011 myHiddenAdj = FOREGROUND_APP_ADJ;
12012 }
12013 }
12014 int clientAdj = computeOomAdjLocked(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012015 client, myHiddenAdj, TOP_APP, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012016 if (adj > clientAdj) {
12017 adj = clientAdj > FOREGROUND_APP_ADJ
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012018 ? clientAdj : FOREGROUND_APP_ADJ;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012019 if (!client.hidden) {
12020 app.hidden = false;
12021 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012022 if (client.keeping) {
12023 app.keeping = true;
12024 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012025 app.adjType = "provider";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012026 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12027 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012028 app.adjSource = client;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012029 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012030 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012031 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12032 schedGroup = Process.THREAD_GROUP_DEFAULT;
12033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012034 }
12035 }
12036 // If the provider has external (non-framework) process
12037 // dependencies, ensure that its adjustment is at least
12038 // FOREGROUND_APP_ADJ.
12039 if (cpr.externals != 0) {
12040 if (adj > FOREGROUND_APP_ADJ) {
12041 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012042 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012043 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012044 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012045 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012046 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012047 }
12048 }
12049 }
12050 }
12051
12052 app.curRawAdj = adj;
12053
Joe Onorato8a9b2202010-02-26 18:56:32 -080012054 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012055 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12056 if (adj > app.maxAdj) {
12057 adj = app.maxAdj;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012058 if (app.maxAdj <= PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012059 schedGroup = Process.THREAD_GROUP_DEFAULT;
12060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012061 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012062 if (adj < HIDDEN_APP_MIN_ADJ) {
12063 app.keeping = true;
12064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012065
12066 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012067 app.curSchedGroup = schedGroup;
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012069 return adj;
12070 }
12071
12072 /**
12073 * Ask a given process to GC right now.
12074 */
12075 final void performAppGcLocked(ProcessRecord app) {
12076 try {
12077 app.lastRequestedGc = SystemClock.uptimeMillis();
12078 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012079 if (app.reportLowMemory) {
12080 app.reportLowMemory = false;
12081 app.thread.scheduleLowMemory();
12082 } else {
12083 app.thread.processInBackground();
12084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012085 }
12086 } catch (Exception e) {
12087 // whatever.
12088 }
12089 }
12090
12091 /**
12092 * Returns true if things are idle enough to perform GCs.
12093 */
Josh Bartel7f208742010-02-25 11:01:44 -060012094 private final boolean canGcNowLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012095 return mParallelBroadcasts.size() == 0
12096 && mOrderedBroadcasts.size() == 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012097 && (mSleeping || (mMainStack.mResumedActivity != null &&
12098 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012099 }
12100
12101 /**
12102 * Perform GCs on all processes that are waiting for it, but only
12103 * if things are idle.
12104 */
12105 final void performAppGcsLocked() {
12106 final int N = mProcessesToGc.size();
12107 if (N <= 0) {
12108 return;
12109 }
Josh Bartel7f208742010-02-25 11:01:44 -060012110 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012111 while (mProcessesToGc.size() > 0) {
12112 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012113 if (proc.curRawAdj > PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012114 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
12115 <= SystemClock.uptimeMillis()) {
12116 // To avoid spamming the system, we will GC processes one
12117 // at a time, waiting a few seconds between each.
12118 performAppGcLocked(proc);
12119 scheduleAppGcsLocked();
12120 return;
12121 } else {
12122 // It hasn't been long enough since we last GCed this
12123 // process... put it in the list to wait for its time.
12124 addProcessToGcListLocked(proc);
12125 break;
12126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012127 }
12128 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012129
12130 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012131 }
12132 }
12133
12134 /**
12135 * If all looks good, perform GCs on all processes waiting for them.
12136 */
12137 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060012138 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012139 performAppGcsLocked();
12140 return;
12141 }
12142 // Still not idle, wait some more.
12143 scheduleAppGcsLocked();
12144 }
12145
12146 /**
12147 * Schedule the execution of all pending app GCs.
12148 */
12149 final void scheduleAppGcsLocked() {
12150 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012151
12152 if (mProcessesToGc.size() > 0) {
12153 // Schedule a GC for the time to the next process.
12154 ProcessRecord proc = mProcessesToGc.get(0);
12155 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
12156
12157 long when = mProcessesToGc.get(0).lastRequestedGc + GC_MIN_INTERVAL;
12158 long now = SystemClock.uptimeMillis();
12159 if (when < (now+GC_TIMEOUT)) {
12160 when = now + GC_TIMEOUT;
12161 }
12162 mHandler.sendMessageAtTime(msg, when);
12163 }
12164 }
12165
12166 /**
12167 * Add a process to the array of processes waiting to be GCed. Keeps the
12168 * list in sorted order by the last GC time. The process can't already be
12169 * on the list.
12170 */
12171 final void addProcessToGcListLocked(ProcessRecord proc) {
12172 boolean added = false;
12173 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
12174 if (mProcessesToGc.get(i).lastRequestedGc <
12175 proc.lastRequestedGc) {
12176 added = true;
12177 mProcessesToGc.add(i+1, proc);
12178 break;
12179 }
12180 }
12181 if (!added) {
12182 mProcessesToGc.add(0, proc);
12183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012184 }
12185
12186 /**
12187 * Set up to ask a process to GC itself. This will either do it
12188 * immediately, or put it on the list of processes to gc the next
12189 * time things are idle.
12190 */
12191 final void scheduleAppGcLocked(ProcessRecord app) {
12192 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012193 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012194 return;
12195 }
12196 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012197 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012198 scheduleAppGcsLocked();
12199 }
12200 }
12201
Dianne Hackborn287952c2010-09-22 22:34:31 -070012202 final void checkExcessivePowerUsageLocked(boolean doKills) {
12203 updateCpuStatsNow();
12204
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012205 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012206 boolean doWakeKills = doKills;
12207 boolean doCpuKills = doKills;
12208 if (mLastPowerCheckRealtime == 0) {
12209 doWakeKills = false;
12210 }
12211 if (mLastPowerCheckUptime == 0) {
12212 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012213 }
12214 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012215 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012216 }
12217 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012218 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
12219 final long curUptime = SystemClock.uptimeMillis();
12220 final long uptimeSince = curUptime - mLastPowerCheckUptime;
12221 mLastPowerCheckRealtime = curRealtime;
12222 mLastPowerCheckUptime = curUptime;
12223 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
12224 doWakeKills = false;
12225 }
12226 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
12227 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012228 }
12229 int i = mLruProcesses.size();
12230 while (i > 0) {
12231 i--;
12232 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012233 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012234 long wtime;
12235 synchronized (stats) {
12236 wtime = stats.getProcessWakeTime(app.info.uid,
12237 app.pid, curRealtime);
12238 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012239 long wtimeUsed = wtime - app.lastWakeTime;
12240 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
12241 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012242 StringBuilder sb = new StringBuilder(128);
12243 sb.append("Wake for ");
12244 app.toShortString(sb);
12245 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012246 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012247 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012248 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012249 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012250 sb.append((wtimeUsed*100)/realtimeSince);
12251 sb.append("%)");
12252 Slog.i(TAG, sb.toString());
12253 sb.setLength(0);
12254 sb.append("CPU for ");
12255 app.toShortString(sb);
12256 sb.append(": over ");
12257 TimeUtils.formatDuration(uptimeSince, sb);
12258 sb.append(" used ");
12259 TimeUtils.formatDuration(cputimeUsed, sb);
12260 sb.append(" (");
12261 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012262 sb.append("%)");
12263 Slog.i(TAG, sb.toString());
12264 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012265 // If a process has held a wake lock for more
12266 // than 50% of the time during this period,
12267 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070012268 if (doWakeKills && realtimeSince > 0
12269 && ((wtimeUsed*100)/realtimeSince) >= 50) {
12270 synchronized (stats) {
12271 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
12272 realtimeSince, wtimeUsed);
12273 }
12274 Slog.w(TAG, "Excessive wake lock in " + app.processName
12275 + " (pid " + app.pid + "): held " + wtimeUsed
12276 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012277 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12278 app.processName, app.setAdj, "excessive wake lock");
12279 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012280 } else if (doCpuKills && uptimeSince > 0
12281 && ((cputimeUsed*100)/uptimeSince) >= 50) {
12282 synchronized (stats) {
12283 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
12284 uptimeSince, cputimeUsed);
12285 }
12286 Slog.w(TAG, "Excessive CPU in " + app.processName
12287 + " (pid " + app.pid + "): used " + cputimeUsed
12288 + " during " + uptimeSince);
12289 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12290 app.processName, app.setAdj, "excessive cpu");
12291 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012292 } else {
12293 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012294 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012295 }
12296 }
12297 }
12298 }
12299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012300 private final boolean updateOomAdjLocked(
12301 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP) {
12302 app.hiddenAdj = hiddenAdj;
12303
12304 if (app.thread == null) {
12305 return true;
12306 }
12307
Dianne Hackborn287952c2010-09-22 22:34:31 -070012308 final boolean wasKeeping = app.keeping;
12309
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012310 int adj = computeOomAdjLocked(app, hiddenAdj, TOP_APP, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012311
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012312 if ((app.pid != 0 && app.pid != MY_PID) || Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012313 if (app.curRawAdj != app.setRawAdj) {
12314 if (app.curRawAdj > FOREGROUND_APP_ADJ
12315 && app.setRawAdj <= FOREGROUND_APP_ADJ) {
12316 // If this app is transitioning from foreground to
12317 // non-foreground, have it do a gc.
12318 scheduleAppGcLocked(app);
12319 } else if (app.curRawAdj >= HIDDEN_APP_MIN_ADJ
12320 && app.setRawAdj < HIDDEN_APP_MIN_ADJ) {
12321 // Likewise do a gc when an app is moving in to the
12322 // background (such as a service stopping).
12323 scheduleAppGcLocked(app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012324 }
12325
12326 if (wasKeeping && !app.keeping) {
12327 // This app is no longer something we want to keep. Note
12328 // its current wake lock time to later know to kill it if
12329 // it is not behaving well.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012330 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12331 synchronized (stats) {
12332 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
12333 app.pid, SystemClock.elapsedRealtime());
12334 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012335 app.lastCpuTime = app.curCpuTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012336 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012338 app.setRawAdj = app.curRawAdj;
12339 }
12340 if (adj != app.setAdj) {
12341 if (Process.setOomAdj(app.pid, adj)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012342 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012343 TAG, "Set app " + app.processName +
12344 " oom adj to " + adj);
12345 app.setAdj = adj;
12346 } else {
12347 return false;
12348 }
12349 }
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012350 if (app.setSchedGroup != app.curSchedGroup) {
12351 app.setSchedGroup = app.curSchedGroup;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012352 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012353 "Setting process group of " + app.processName
12354 + " to " + app.curSchedGroup);
12355 if (true) {
San Mehat9438de22009-06-10 09:11:28 -070012356 long oldId = Binder.clearCallingIdentity();
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012357 try {
12358 Process.setProcessGroup(app.pid, app.curSchedGroup);
12359 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012360 Slog.w(TAG, "Failed setting process group of " + app.pid
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012361 + " to " + app.curSchedGroup);
San Mehat9438de22009-06-10 09:11:28 -070012362 e.printStackTrace();
12363 } finally {
12364 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012365 }
12366 }
12367 if (false) {
12368 if (app.thread != null) {
12369 try {
12370 app.thread.setSchedulingGroup(app.curSchedGroup);
12371 } catch (RemoteException e) {
12372 }
12373 }
12374 }
12375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012376 }
12377
12378 return true;
12379 }
12380
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012381 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012382 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012383 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012384 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012385 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012386 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012387 }
12388 }
12389 return resumedActivity;
12390 }
12391
12392 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012393 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012394 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12395 int curAdj = app.curAdj;
12396 final boolean wasHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
12397 && app.curAdj <= HIDDEN_APP_MAX_ADJ;
12398
12399 mAdjSeq++;
12400
12401 final boolean res = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP);
12402 if (res) {
12403 final boolean nowHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
12404 && app.curAdj <= HIDDEN_APP_MAX_ADJ;
12405 if (nowHidden != wasHidden) {
12406 // Changed to/from hidden state, so apps after it in the LRU
12407 // list may also be changed.
12408 updateOomAdjLocked();
12409 }
12410 }
12411 return res;
12412 }
12413
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012414 final boolean updateOomAdjLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012415 boolean didOomAdj = true;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012416 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012417 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12418
12419 if (false) {
12420 RuntimeException e = new RuntimeException();
12421 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012422 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012423 }
12424
12425 mAdjSeq++;
12426
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012427 // Let's determine how many processes we have running vs.
12428 // how many slots we have for background processes; we may want
12429 // to put multiple processes in a slot of there are enough of
12430 // them.
12431 int numSlots = HIDDEN_APP_MAX_ADJ - HIDDEN_APP_MIN_ADJ + 1;
12432 int factor = (mLruProcesses.size()-4)/numSlots;
12433 if (factor < 1) factor = 1;
12434 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070012435 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012437 // First try updating the OOM adjustment for each of the
12438 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012439 int i = mLruProcesses.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012440 int curHiddenAdj = HIDDEN_APP_MIN_ADJ;
12441 while (i > 0) {
12442 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012443 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012444 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445 if (updateOomAdjLocked(app, curHiddenAdj, TOP_APP)) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012446 if (curHiddenAdj < EMPTY_APP_ADJ
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012447 && app.curAdj == curHiddenAdj) {
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012448 step++;
12449 if (step >= factor) {
12450 step = 0;
12451 curHiddenAdj++;
12452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012453 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070012454 if (app.curAdj >= HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn149427c2010-04-23 14:20:03 -070012455 if (!app.killedBackground) {
12456 numHidden++;
12457 if (numHidden > MAX_HIDDEN_APPS) {
Dianne Hackborn906497c2010-05-10 15:57:38 -070012458 Slog.i(TAG, "No longer want " + app.processName
12459 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackborn149427c2010-04-23 14:20:03 -070012460 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12461 app.processName, app.setAdj, "too many background");
12462 app.killedBackground = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -070012463 Process.killProcessQuiet(app.pid);
Dianne Hackborn149427c2010-04-23 14:20:03 -070012464 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070012465 }
12466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012467 } else {
12468 didOomAdj = false;
12469 }
12470 }
12471
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012472 // If we return false, we will fall back on killing processes to
12473 // have a fixed limit. Do this if a limit has been requested; else
12474 // only return false if one of the adjustments failed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012475 return ENFORCE_PROCESS_LIMIT || mProcessLimit > 0 ? false : didOomAdj;
12476 }
12477
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012478 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012479 synchronized (this) {
12480 int i;
12481
12482 // First remove any unused application processes whose package
12483 // has been removed.
12484 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
12485 final ProcessRecord app = mRemovedProcesses.get(i);
12486 if (app.activities.size() == 0
12487 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012488 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012489 TAG, "Exiting empty application process "
12490 + app.processName + " ("
12491 + (app.thread != null ? app.thread.asBinder() : null)
12492 + ")\n");
12493 if (app.pid > 0 && app.pid != MY_PID) {
12494 Process.killProcess(app.pid);
12495 } else {
12496 try {
12497 app.thread.scheduleExit();
12498 } catch (Exception e) {
12499 // Ignore exceptions.
12500 }
12501 }
12502 cleanUpApplicationRecordLocked(app, false, -1);
12503 mRemovedProcesses.remove(i);
12504
12505 if (app.persistent) {
12506 if (app.persistent) {
12507 addAppLocked(app.info);
12508 }
12509 }
12510 }
12511 }
12512
12513 // Now try updating the OOM adjustment for each of the
12514 // application processes based on their current state.
12515 // If the setOomAdj() API is not supported, then go with our
12516 // back-up plan...
12517 if (!updateOomAdjLocked()) {
12518
12519 // Count how many processes are running services.
12520 int numServiceProcs = 0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012521 for (i=mLruProcesses.size()-1; i>=0; i--) {
12522 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012523
12524 if (app.persistent || app.services.size() != 0
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -070012525 || app.curReceiver != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012526 // Don't count processes holding services against our
12527 // maximum process count.
Joe Onorato8a9b2202010-02-26 18:56:32 -080012528 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012529 TAG, "Not trimming app " + app + " with services: "
12530 + app.services);
12531 numServiceProcs++;
12532 }
12533 }
12534
12535 int curMaxProcs = mProcessLimit;
12536 if (curMaxProcs <= 0) curMaxProcs = MAX_PROCESSES;
12537 if (mAlwaysFinishActivities) {
12538 curMaxProcs = 1;
12539 }
12540 curMaxProcs += numServiceProcs;
12541
12542 // Quit as many processes as we can to get down to the desired
12543 // process count. First remove any processes that no longer
12544 // have activites running in them.
12545 for ( i=0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012546 i<mLruProcesses.size()
12547 && mLruProcesses.size() > curMaxProcs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012548 i++) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012549 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012550 // Quit an application only if it is not currently
12551 // running any activities.
12552 if (!app.persistent && app.activities.size() == 0
12553 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012554 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012555 TAG, "Exiting empty application process "
12556 + app.processName + " ("
12557 + (app.thread != null ? app.thread.asBinder() : null)
12558 + ")\n");
12559 if (app.pid > 0 && app.pid != MY_PID) {
12560 Process.killProcess(app.pid);
12561 } else {
12562 try {
12563 app.thread.scheduleExit();
12564 } catch (Exception e) {
12565 // Ignore exceptions.
12566 }
12567 }
12568 // todo: For now we assume the application is not buggy
12569 // or evil, and will quit as a result of our request.
12570 // Eventually we need to drive this off of the death
12571 // notification, and kill the process if it takes too long.
12572 cleanUpApplicationRecordLocked(app, false, i);
12573 i--;
12574 }
12575 }
12576
12577 // If we still have too many processes, now from the least
12578 // recently used process we start finishing activities.
Joe Onorato8a9b2202010-02-26 18:56:32 -080012579 if (Config.LOGV) Slog.v(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012580 TAG, "*** NOW HAVE " + mLruProcesses.size() +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012581 " of " + curMaxProcs + " processes");
12582 for ( i=0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012583 i<mLruProcesses.size()
12584 && mLruProcesses.size() > curMaxProcs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585 i++) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012586 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012587 // Quit the application only if we have a state saved for
12588 // all of its activities.
12589 boolean canQuit = !app.persistent && app.curReceiver == null
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -070012590 && app.services.size() == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012591 int NUMA = app.activities.size();
12592 int j;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012593 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012594 TAG, "Looking to quit " + app.processName);
12595 for (j=0; j<NUMA && canQuit; j++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012596 ActivityRecord r = app.activities.get(j);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012597 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012598 TAG, " " + r.intent.getComponent().flattenToShortString()
12599 + ": frozen=" + r.haveState + ", visible=" + r.visible);
12600 canQuit = (r.haveState || !r.stateNotNeeded)
12601 && !r.visible && r.stopped;
12602 }
12603 if (canQuit) {
12604 // Finish all of the activities, and then the app itself.
12605 for (j=0; j<NUMA; j++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012606 ActivityRecord r = app.activities.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012607 if (!r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012608 r.stack.destroyActivityLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012609 }
12610 r.resultTo = null;
12611 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080012612 Slog.i(TAG, "Exiting application process "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012613 + app.processName + " ("
12614 + (app.thread != null ? app.thread.asBinder() : null)
12615 + ")\n");
12616 if (app.pid > 0 && app.pid != MY_PID) {
12617 Process.killProcess(app.pid);
12618 } else {
12619 try {
12620 app.thread.scheduleExit();
12621 } catch (Exception e) {
12622 // Ignore exceptions.
12623 }
12624 }
12625 // todo: For now we assume the application is not buggy
12626 // or evil, and will quit as a result of our request.
12627 // Eventually we need to drive this off of the death
12628 // notification, and kill the process if it takes too long.
12629 cleanUpApplicationRecordLocked(app, false, i);
12630 i--;
12631 //dump();
12632 }
12633 }
12634
12635 }
12636
12637 int curMaxActivities = MAX_ACTIVITIES;
12638 if (mAlwaysFinishActivities) {
12639 curMaxActivities = 1;
12640 }
12641
12642 // Finally, if there are too many activities now running, try to
12643 // finish as many as we can to get back down to the limit.
12644 for ( i=0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012645 i<mMainStack.mLRUActivities.size()
12646 && mMainStack.mLRUActivities.size() > curMaxActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012647 i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012648 final ActivityRecord r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012649 = (ActivityRecord)mMainStack.mLRUActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012650
12651 // We can finish this one if we have its icicle saved and
12652 // it is not persistent.
12653 if ((r.haveState || !r.stateNotNeeded) && !r.visible
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -070012654 && r.stopped && !r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012655 final int origSize = mMainStack.mLRUActivities.size();
12656 r.stack.destroyActivityLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012657
12658 // This will remove it from the LRU list, so keep
12659 // our index at the same value. Note that this check to
12660 // see if the size changes is just paranoia -- if
12661 // something unexpected happens, we don't want to end up
12662 // in an infinite loop.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012663 if (origSize > mMainStack.mLRUActivities.size()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012664 i--;
12665 }
12666 }
12667 }
12668 }
12669 }
12670
12671 /** This method sends the specified signal to each of the persistent apps */
12672 public void signalPersistentProcesses(int sig) throws RemoteException {
12673 if (sig != Process.SIGNAL_USR1) {
12674 throw new SecurityException("Only SIGNAL_USR1 is allowed");
12675 }
12676
12677 synchronized (this) {
12678 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
12679 != PackageManager.PERMISSION_GRANTED) {
12680 throw new SecurityException("Requires permission "
12681 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
12682 }
12683
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012684 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12685 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012686 if (r.thread != null && r.persistent) {
12687 Process.sendSignal(r.pid, sig);
12688 }
12689 }
12690 }
12691 }
12692
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012693 public boolean profileControl(String process, boolean start,
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012694 String path, ParcelFileDescriptor fd) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012695
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012696 try {
12697 synchronized (this) {
12698 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
12699 // its own permission.
12700 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
12701 != PackageManager.PERMISSION_GRANTED) {
12702 throw new SecurityException("Requires permission "
12703 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012704 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012705
12706 if (start && fd == null) {
12707 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012708 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012709
12710 ProcessRecord proc = null;
12711 try {
12712 int pid = Integer.parseInt(process);
12713 synchronized (mPidsSelfLocked) {
12714 proc = mPidsSelfLocked.get(pid);
12715 }
12716 } catch (NumberFormatException e) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012717 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012718
12719 if (proc == null) {
12720 HashMap<String, SparseArray<ProcessRecord>> all
12721 = mProcessNames.getMap();
12722 SparseArray<ProcessRecord> procs = all.get(process);
12723 if (procs != null && procs.size() > 0) {
12724 proc = procs.valueAt(0);
12725 }
12726 }
12727
12728 if (proc == null || proc.thread == null) {
12729 throw new IllegalArgumentException("Unknown process: " + process);
12730 }
12731
12732 boolean isSecure = "1".equals(SystemProperties.get(SYSTEM_SECURE, "0"));
12733 if (isSecure) {
12734 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
12735 throw new SecurityException("Process not debuggable: " + proc);
12736 }
12737 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012738
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012739 proc.thread.profilerControl(start, path, fd);
12740 fd = null;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012741 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070012742 }
12743 } catch (RemoteException e) {
12744 throw new IllegalStateException("Process disappeared");
12745 } finally {
12746 if (fd != null) {
12747 try {
12748 fd.close();
12749 } catch (IOException e) {
12750 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080012751 }
12752 }
12753 }
Andy McFadden824c5102010-07-09 16:26:57 -070012754
12755 public boolean dumpHeap(String process, boolean managed,
12756 String path, ParcelFileDescriptor fd) throws RemoteException {
12757
12758 try {
12759 synchronized (this) {
12760 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
12761 // its own permission (same as profileControl).
12762 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
12763 != PackageManager.PERMISSION_GRANTED) {
12764 throw new SecurityException("Requires permission "
12765 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
12766 }
12767
12768 if (fd == null) {
12769 throw new IllegalArgumentException("null fd");
12770 }
12771
12772 ProcessRecord proc = null;
12773 try {
12774 int pid = Integer.parseInt(process);
12775 synchronized (mPidsSelfLocked) {
12776 proc = mPidsSelfLocked.get(pid);
12777 }
12778 } catch (NumberFormatException e) {
12779 }
12780
12781 if (proc == null) {
12782 HashMap<String, SparseArray<ProcessRecord>> all
12783 = mProcessNames.getMap();
12784 SparseArray<ProcessRecord> procs = all.get(process);
12785 if (procs != null && procs.size() > 0) {
12786 proc = procs.valueAt(0);
12787 }
12788 }
12789
12790 if (proc == null || proc.thread == null) {
12791 throw new IllegalArgumentException("Unknown process: " + process);
12792 }
12793
12794 boolean isSecure = "1".equals(SystemProperties.get(SYSTEM_SECURE, "0"));
12795 if (isSecure) {
12796 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
12797 throw new SecurityException("Process not debuggable: " + proc);
12798 }
12799 }
12800
12801 proc.thread.dumpHeap(managed, path, fd);
12802 fd = null;
12803 return true;
12804 }
12805 } catch (RemoteException e) {
12806 throw new IllegalStateException("Process disappeared");
12807 } finally {
12808 if (fd != null) {
12809 try {
12810 fd.close();
12811 } catch (IOException e) {
12812 }
12813 }
12814 }
12815 }
12816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012817 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
12818 public void monitor() {
12819 synchronized (this) { }
12820 }
12821}