blob: bcbda3e0940febc96f3583eb4444ccb28c4463e5 [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;
20import com.android.internal.app.HeavyWeightSwitcherActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.internal.os.BatteryStatsImpl;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070022import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import com.android.server.IntentResolver;
24import com.android.server.ProcessMap;
25import com.android.server.ProcessStats;
26import com.android.server.SystemServer;
27import com.android.server.Watchdog;
28import com.android.server.WindowManagerService;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import com.android.server.am.ActivityStack.ActivityState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030
Dianne Hackborndd71fc82009-12-16 19:24:32 -080031import dalvik.system.Zygote;
32
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.app.Activity;
34import android.app.ActivityManager;
35import android.app.ActivityManagerNative;
36import android.app.ActivityThread;
37import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070038import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020039import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070041import android.app.IActivityController;
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -080042import android.app.IActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.app.IActivityWatcher;
44import android.app.IApplicationThread;
45import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070046import android.app.INotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.app.IServiceConnection;
48import android.app.IThumbnailReceiver;
49import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070050import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070051import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.app.PendingIntent;
53import android.app.ResultInfo;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070054import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080055import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020056import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080057import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.content.ComponentName;
59import android.content.ContentResolver;
60import android.content.Context;
61import android.content.Intent;
62import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070063import android.content.IIntentReceiver;
64import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070065import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.content.pm.ActivityInfo;
67import android.content.pm.ApplicationInfo;
68import android.content.pm.ConfigurationInfo;
69import android.content.pm.IPackageDataObserver;
70import android.content.pm.IPackageManager;
71import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080072import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070074import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.content.pm.ProviderInfo;
76import android.content.pm.ResolveInfo;
77import android.content.pm.ServiceInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070078import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.content.res.Configuration;
80import android.graphics.Bitmap;
81import 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;
97import android.os.PowerManager;
98import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070099import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.os.RemoteException;
101import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700102import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.os.SystemClock;
104import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.util.Config;
107import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800108import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800109import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.util.PrintWriterPrinter;
111import android.util.SparseArray;
112import android.view.Gravity;
113import android.view.LayoutInflater;
114import android.view.View;
115import android.view.WindowManager;
116import android.view.WindowManagerPolicy;
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.io.File;
119import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import java.io.FileNotFoundException;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200121import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800122import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import java.io.PrintWriter;
124import java.lang.IllegalStateException;
125import java.lang.ref.WeakReference;
126import java.util.ArrayList;
127import java.util.HashMap;
128import java.util.HashSet;
129import java.util.Iterator;
130import java.util.List;
131import java.util.Locale;
132import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700133import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700134import java.util.concurrent.atomic.AtomicBoolean;
135import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
137public final class ActivityManagerService extends ActivityManagerNative implements Watchdog.Monitor {
138 static final String TAG = "ActivityManager";
139 static final boolean DEBUG = false;
140 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
141 static final boolean DEBUG_SWITCH = localLOGV || false;
142 static final boolean DEBUG_TASKS = localLOGV || false;
143 static final boolean DEBUG_PAUSE = localLOGV || false;
144 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
145 static final boolean DEBUG_TRANSITION = localLOGV || false;
146 static final boolean DEBUG_BROADCAST = localLOGV || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700147 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 static final boolean DEBUG_SERVICE = localLOGV || false;
149 static final boolean DEBUG_VISBILITY = localLOGV || false;
150 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700151 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800152 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700154 static final boolean DEBUG_RESULTS = localLOGV || false;
Christopher Tate436344a2009-09-30 16:17:37 -0700155 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700156 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 static final boolean VALIDATE_TOKENS = false;
158 static final boolean SHOW_ACTIVITY_START_TIME = true;
159
160 // Control over CPU and battery monitoring.
161 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
162 static final boolean MONITOR_CPU_USAGE = true;
163 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
164 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
165 static final boolean MONITOR_THREAD_CPU_USAGE = false;
166
Dianne Hackborn1655be42009-05-08 14:29:01 -0700167 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700168 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 private static final String SYSTEM_SECURE = "ro.secure";
171
172 // This is the maximum number of application processes we would like
173 // to have running. Due to the asynchronous nature of things, we can
174 // temporarily go beyond this limit.
175 static final int MAX_PROCESSES = 2;
176
177 // Set to false to leave processes running indefinitely, relying on
178 // the kernel killing them as resources are required.
179 static final boolean ENFORCE_PROCESS_LIMIT = false;
180
181 // This is the maximum number of activities that we would like to have
182 // running at a given time.
183 static final int MAX_ACTIVITIES = 20;
184
185 // Maximum number of recent tasks that we can remember.
186 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700187
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700188 // Amount of time after a call to stopAppSwitches() during which we will
189 // prevent further untrusted switches from happening.
190 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
192 // How long we wait for a launched process to attach to the activity manager
193 // before we decide it's never going to come up for real.
194 static final int PROC_START_TIMEOUT = 10*1000;
195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 // How long to wait after going idle before forcing apps to GC.
197 static final int GC_TIMEOUT = 5*1000;
198
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700199 // The minimum amount of time between successive GC requests for a process.
200 static final int GC_MIN_INTERVAL = 60*1000;
201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 // How long we allow a receiver to run before giving up on it.
203 static final int BROADCAST_TIMEOUT = 10*1000;
204
205 // How long we wait for a service to finish executing.
206 static final int SERVICE_TIMEOUT = 20*1000;
207
208 // How long a service needs to be running until restarting its process
209 // is no longer considered to be a relaunch of the service.
210 static final int SERVICE_RESTART_DURATION = 5*1000;
211
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700212 // How long a service needs to be running until it will start back at
213 // SERVICE_RESTART_DURATION after being killed.
214 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
215
216 // Multiplying factor to increase restart duration time by, for each time
217 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
218 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
219
220 // The minimum amount of time between restarting services that we allow.
221 // That is, when multiple services are restarting, we won't allow each
222 // to restart less than this amount of time from the last one.
223 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 // Maximum amount of time for there to be no activity on a service before
226 // we consider it non-essential and allow its process to go on the
227 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700228 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
230 // How long we wait until we timeout on key dispatching.
231 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
232
233 // The minimum time we allow between crashes, for us to consider this
234 // application to be bad and stop and its services and reject broadcasts.
235 static final int MIN_CRASH_INTERVAL = 60*1000;
236
237 // How long we wait until we timeout on key dispatching during instrumentation.
238 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
239
240 // OOM adjustments for processes in various states:
241
242 // This is a process without anything currently running in it. Definitely
243 // the first to go! Value set in system/rootdir/init.rc on startup.
244 // This value is initalized in the constructor, careful when refering to
245 // this static variable externally.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800246 static final int EMPTY_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
248 // This is a process only hosting activities that are not visible,
249 // so it can be killed without any disruption. Value set in
250 // system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800251 static final int HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 static int HIDDEN_APP_MIN_ADJ;
253
The Android Open Source Project4df24232009-03-05 14:34:35 -0800254 // This is a process holding the home application -- we want to try
255 // avoiding killing it, even if it would normally be in the background,
256 // because the user interacts with it so much.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800257 static final int HOME_APP_ADJ;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800258
Christopher Tate6fa95972009-06-05 18:43:55 -0700259 // This is a process currently hosting a backup operation. Killing it
260 // is not entirely fatal but is generally a bad idea.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800261 static final int BACKUP_APP_ADJ;
Christopher Tate6fa95972009-06-05 18:43:55 -0700262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 // This is a process holding a secondary server -- killing it will not
264 // have much of an impact as far as the user is concerned. Value set in
265 // system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800266 static final int SECONDARY_SERVER_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700268 // This is a process with a heavy-weight application. It is in the
269 // background, but we want to try to avoid killing it. Value set in
270 // system/rootdir/init.rc on startup.
271 static final int HEAVY_WEIGHT_APP_ADJ;
272
273 // This is a process only hosting components that are perceptible to the
274 // user, and we really want to avoid killing them, but they are not
275 // immediately visible. An example is background music playback. Value set in
276 // system/rootdir/init.rc on startup.
277 static final int PERCEPTIBLE_APP_ADJ;
278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 // This is a process only hosting activities that are visible to the
280 // user, so we'd prefer they don't disappear. Value set in
281 // system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800282 static final int VISIBLE_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283
284 // This is the process running the current foreground app. We'd really
285 // rather not kill it! Value set in system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800286 static final int FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287
288 // This is a process running a core server, such as telephony. Definitely
289 // don't want to kill it, but doing so is not completely fatal.
290 static final int CORE_SERVER_ADJ = -12;
291
292 // The system process runs at the default adjustment.
293 static final int SYSTEM_ADJ = -16;
294
295 // Memory pages are 4K.
296 static final int PAGE_SIZE = 4*1024;
297
298 // Corresponding memory levels for above adjustments.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800299 static final int EMPTY_APP_MEM;
300 static final int HIDDEN_APP_MEM;
301 static final int HOME_APP_MEM;
302 static final int BACKUP_APP_MEM;
303 static final int SECONDARY_SERVER_MEM;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700304 static final int HEAVY_WEIGHT_APP_MEM;
305 static final int PERCEPTIBLE_APP_MEM;
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800306 static final int VISIBLE_APP_MEM;
307 static final int FOREGROUND_APP_MEM;
308
309 // The minimum number of hidden apps we want to be able to keep around,
310 // without empty apps being able to push them out of memory.
311 static final int MIN_HIDDEN_APPS = 2;
312
Dianne Hackborn8633e682010-04-22 16:03:41 -0700313 // The maximum number of hidden processes we will keep around before
314 // killing them; this is just a control to not let us go too crazy with
315 // keeping around processes on devices with large amounts of RAM.
316 static final int MAX_HIDDEN_APPS = 15;
317
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800318 // We put empty content processes after any hidden processes that have
Dianne Hackborn906497c2010-05-10 15:57:38 -0700319 // been idle for less than 15 seconds.
320 static final long CONTENT_APP_IDLE_OFFSET = 15*1000;
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800321
322 // We put empty content processes after any hidden processes that have
Dianne Hackborn906497c2010-05-10 15:57:38 -0700323 // been idle for less than 120 seconds.
324 static final long EMPTY_APP_IDLE_OFFSET = 120*1000;
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800325
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700326 static int getIntProp(String name, boolean allowZero) {
327 String str = SystemProperties.get(name);
328 if (str == null) {
329 throw new IllegalArgumentException("Property not defined: " + name);
330 }
331 int val = Integer.valueOf(str);
332 if (val == 0 && !allowZero) {
333 throw new IllegalArgumentException("Property must not be zero: " + name);
334 }
335 return val;
336 }
337
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800338 static {
339 // These values are set in system/rootdir/init.rc on startup.
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700340 FOREGROUND_APP_ADJ = getIntProp("ro.FOREGROUND_APP_ADJ", true);
341 VISIBLE_APP_ADJ = getIntProp("ro.VISIBLE_APP_ADJ", true);
342 PERCEPTIBLE_APP_ADJ = getIntProp("ro.PERCEPTIBLE_APP_ADJ", true);
343 HEAVY_WEIGHT_APP_ADJ = getIntProp("ro.HEAVY_WEIGHT_APP_ADJ", true);
344 SECONDARY_SERVER_ADJ = getIntProp("ro.SECONDARY_SERVER_ADJ", true);
345 BACKUP_APP_ADJ = getIntProp("ro.BACKUP_APP_ADJ", true);
346 HOME_APP_ADJ = getIntProp("ro.HOME_APP_ADJ", true);
347 HIDDEN_APP_MIN_ADJ = getIntProp("ro.HIDDEN_APP_MIN_ADJ", true);
348 EMPTY_APP_ADJ = getIntProp("ro.EMPTY_APP_ADJ", true);
349 // These days we use the last empty slot for hidden apps as well.
350 HIDDEN_APP_MAX_ADJ = EMPTY_APP_ADJ;
351 FOREGROUND_APP_MEM = getIntProp("ro.FOREGROUND_APP_MEM", false)*PAGE_SIZE;
352 VISIBLE_APP_MEM = getIntProp("ro.VISIBLE_APP_MEM", false)*PAGE_SIZE;
353 PERCEPTIBLE_APP_MEM = getIntProp("ro.PERCEPTIBLE_APP_MEM", false)*PAGE_SIZE;
354 HEAVY_WEIGHT_APP_MEM = getIntProp("ro.HEAVY_WEIGHT_APP_MEM", false)*PAGE_SIZE;
355 SECONDARY_SERVER_MEM = getIntProp("ro.SECONDARY_SERVER_MEM", false)*PAGE_SIZE;
356 BACKUP_APP_MEM = getIntProp("ro.BACKUP_APP_MEM", false)*PAGE_SIZE;
357 HOME_APP_MEM = getIntProp("ro.HOME_APP_MEM", false)*PAGE_SIZE;
358 HIDDEN_APP_MEM = getIntProp("ro.HIDDEN_APP_MEM", false)*PAGE_SIZE;
359 EMPTY_APP_MEM = getIntProp("ro.EMPTY_APP_MEM", false)*PAGE_SIZE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361
Dan Egnor42471dd2010-01-07 17:25:22 -0800362 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363
364 static final String[] EMPTY_STRING_ARRAY = new String[0];
365
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700366 public ActivityStack mMainStack;
367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700369 * Description of a request to start a new activity, which has been held
370 * due to app switches being disabled.
371 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700372 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700373 ActivityRecord r;
374 ActivityRecord sourceRecord;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700375 Uri[] grantedUriPermissions;
376 int grantedMode;
377 boolean onlyIfNeeded;
378 }
379
380 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
381 = new ArrayList<PendingActivityLaunch>();
382
383 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 * List of all active broadcasts that are to be executed immediately
385 * (without waiting for another broadcast to finish). Currently this only
386 * contains broadcasts to registered receivers, to avoid spinning up
387 * a bunch of processes to execute IntentReceiver components.
388 */
389 final ArrayList<BroadcastRecord> mParallelBroadcasts
390 = new ArrayList<BroadcastRecord>();
391
392 /**
393 * List of all active broadcasts that are to be executed one at a time.
394 * The object at the top of the list is the currently activity broadcasts;
395 * those after it are waiting for the top to finish..
396 */
397 final ArrayList<BroadcastRecord> mOrderedBroadcasts
398 = new ArrayList<BroadcastRecord>();
399
400 /**
Dianne Hackborn12527f92009-11-11 17:39:50 -0800401 * Historical data of past broadcasts, for debugging.
402 */
403 static final int MAX_BROADCAST_HISTORY = 100;
404 final BroadcastRecord[] mBroadcastHistory
405 = new BroadcastRecord[MAX_BROADCAST_HISTORY];
406
407 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 * Set when we current have a BROADCAST_INTENT_MSG in flight.
409 */
410 boolean mBroadcastsScheduled = false;
411
412 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 * Activity we have told the window manager to have key focus.
414 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700415 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700416 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 * List of intents that were used to start the most recent tasks.
418 */
419 final ArrayList<TaskRecord> mRecentTasks
420 = new ArrayList<TaskRecord>();
421
422 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 * All of the applications we currently have running organized by name.
424 * The keys are strings of the application package name (as
425 * returned by the package manager), and the keys are ApplicationRecord
426 * objects.
427 */
428 final ProcessMap<ProcessRecord> mProcessNames
429 = new ProcessMap<ProcessRecord>();
430
431 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700432 * The currently running heavy-weight process, if any.
433 */
434 ProcessRecord mHeavyWeightProcess = null;
435
436 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 * The last time that various processes have crashed.
438 */
439 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
440
441 /**
442 * Set of applications that we consider to be bad, and will reject
443 * incoming broadcasts from (which the user has no control over).
444 * Processes are added to this set when they have crashed twice within
445 * a minimum amount of time; they are removed from it when they are
446 * later restarted (hopefully due to some user action). The value is the
447 * time it was added to the list.
448 */
449 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
450
451 /**
452 * All of the processes we currently have running organized by pid.
453 * The keys are the pid running the application.
454 *
455 * <p>NOTE: This object is protected by its own lock, NOT the global
456 * activity manager lock!
457 */
458 final SparseArray<ProcessRecord> mPidsSelfLocked
459 = new SparseArray<ProcessRecord>();
460
461 /**
462 * All of the processes that have been forced to be foreground. The key
463 * is the pid of the caller who requested it (we hold a death
464 * link on it).
465 */
466 abstract class ForegroundToken implements IBinder.DeathRecipient {
467 int pid;
468 IBinder token;
469 }
470 final SparseArray<ForegroundToken> mForegroundProcesses
471 = new SparseArray<ForegroundToken>();
472
473 /**
474 * List of records for processes that someone had tried to start before the
475 * system was ready. We don't start them at that point, but ensure they
476 * are started by the time booting is complete.
477 */
478 final ArrayList<ProcessRecord> mProcessesOnHold
479 = new ArrayList<ProcessRecord>();
480
481 /**
482 * List of records for processes that we have started and are waiting
483 * for them to call back. This is really only needed when running in
484 * single processes mode, in which case we do not have a unique pid for
485 * each process.
486 */
487 final ArrayList<ProcessRecord> mStartingProcesses
488 = new ArrayList<ProcessRecord>();
489
490 /**
491 * List of persistent applications that are in the process
492 * of being started.
493 */
494 final ArrayList<ProcessRecord> mPersistentStartingProcesses
495 = new ArrayList<ProcessRecord>();
496
497 /**
498 * Processes that are being forcibly torn down.
499 */
500 final ArrayList<ProcessRecord> mRemovedProcesses
501 = new ArrayList<ProcessRecord>();
502
503 /**
504 * List of running applications, sorted by recent usage.
505 * The first entry in the list is the least recently used.
506 * It contains ApplicationRecord objects. This list does NOT include
507 * any persistent application records (since we never want to exit them).
508 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800509 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 = new ArrayList<ProcessRecord>();
511
512 /**
513 * List of processes that should gc as soon as things are idle.
514 */
515 final ArrayList<ProcessRecord> mProcessesToGc
516 = new ArrayList<ProcessRecord>();
517
518 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800519 * This is the process holding what we currently consider to be
520 * the "home" activity.
521 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700522 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800523
524 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 * Set of PendingResultRecord objects that are currently active.
526 */
527 final HashSet mPendingResultRecords = new HashSet();
528
529 /**
530 * Set of IntentSenderRecord objects that are currently active.
531 */
532 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
533 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
534
535 /**
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700536 * Fingerprints (String.hashCode()) of stack traces that we've
537 * already logged DropBox entries for. Guarded by itself. If
538 * something (rogue user app) forces this over
539 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
540 */
541 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
542 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
543
544 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700545 * Strict Mode background batched logging state.
546 *
547 * The string buffer is guarded by itself, and its lock is also
548 * used to determine if another batched write is already
549 * in-flight.
550 */
551 private final StringBuilder mStrictModeBuffer = new StringBuilder();
552
553 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 * Intent broadcast that we have tried to start, but are
555 * waiting for its application's process to be created. We only
556 * need one (instead of a list) because we always process broadcasts
557 * one at a time, so no others can be started while waiting for this
558 * one.
559 */
560 BroadcastRecord mPendingBroadcast = null;
561
562 /**
563 * Keeps track of all IIntentReceivers that have been registered for
564 * broadcasts. Hash keys are the receiver IBinder, hash value is
565 * a ReceiverList.
566 */
567 final HashMap mRegisteredReceivers = new HashMap();
568
569 /**
570 * Resolver for broadcast intents to registered receivers.
571 * Holds BroadcastFilter (subclass of IntentFilter).
572 */
573 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
574 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
575 @Override
576 protected boolean allowFilterResult(
577 BroadcastFilter filter, List<BroadcastFilter> dest) {
578 IBinder target = filter.receiverList.receiver.asBinder();
579 for (int i=dest.size()-1; i>=0; i--) {
580 if (dest.get(i).receiverList.receiver.asBinder() == target) {
581 return false;
582 }
583 }
584 return true;
585 }
586 };
587
588 /**
589 * State of all active sticky broadcasts. Keys are the action of the
590 * sticky Intent, values are an ArrayList of all broadcasted intents with
591 * that action (which should usually be one).
592 */
593 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
594 new HashMap<String, ArrayList<Intent>>();
595
596 /**
597 * All currently running services.
598 */
599 final HashMap<ComponentName, ServiceRecord> mServices =
600 new HashMap<ComponentName, ServiceRecord>();
601
602 /**
603 * All currently running services indexed by the Intent used to start them.
604 */
605 final HashMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent =
606 new HashMap<Intent.FilterComparison, ServiceRecord>();
607
608 /**
609 * All currently bound service connections. Keys are the IBinder of
610 * the client's IServiceConnection.
611 */
612 final HashMap<IBinder, ConnectionRecord> mServiceConnections
613 = new HashMap<IBinder, ConnectionRecord>();
614
615 /**
616 * List of services that we have been asked to start,
617 * but haven't yet been able to. It is used to hold start requests
618 * while waiting for their corresponding application thread to get
619 * going.
620 */
621 final ArrayList<ServiceRecord> mPendingServices
622 = new ArrayList<ServiceRecord>();
623
624 /**
625 * List of services that are scheduled to restart following a crash.
626 */
627 final ArrayList<ServiceRecord> mRestartingServices
628 = new ArrayList<ServiceRecord>();
629
630 /**
631 * List of services that are in the process of being stopped.
632 */
633 final ArrayList<ServiceRecord> mStoppingServices
634 = new ArrayList<ServiceRecord>();
635
636 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700637 * Backup/restore process management
638 */
639 String mBackupAppName = null;
640 BackupRecord mBackupTarget = null;
641
642 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 * List of PendingThumbnailsRecord objects of clients who are still
644 * waiting to receive all of the thumbnails for a task.
645 */
646 final ArrayList mPendingThumbnails = new ArrayList();
647
648 /**
649 * List of HistoryRecord objects that have been finished and must
650 * still report back to a pending thumbnail receiver.
651 */
652 final ArrayList mCancelledThumbnails = new ArrayList();
653
654 /**
655 * All of the currently running global content providers. Keys are a
656 * string containing the provider name and values are a
657 * ContentProviderRecord object containing the data about it. Note
658 * that a single provider may be published under multiple names, so
659 * there may be multiple entries here for a single one in mProvidersByClass.
660 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700661 final HashMap<String, ContentProviderRecord> mProvidersByName
662 = new HashMap<String, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663
664 /**
665 * All of the currently running global content providers. Keys are a
666 * string containing the provider's implementation class and values are a
667 * ContentProviderRecord object containing the data about it.
668 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700669 final HashMap<String, ContentProviderRecord> mProvidersByClass
670 = new HashMap<String, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671
672 /**
673 * List of content providers who have clients waiting for them. The
674 * application is currently being launched and the provider will be
675 * removed from this list once it is published.
676 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700677 final ArrayList<ContentProviderRecord> mLaunchingProviders
678 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679
680 /**
681 * Global set of specific Uri permissions that have been granted.
682 */
683 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
684 = new SparseArray<HashMap<Uri, UriPermission>>();
685
686 /**
687 * Thread-local storage used to carry caller permissions over through
688 * indirect content-provider access.
689 * @see #ActivityManagerService.openContentUri()
690 */
691 private class Identity {
692 public int pid;
693 public int uid;
694
695 Identity(int _pid, int _uid) {
696 pid = _pid;
697 uid = _uid;
698 }
699 }
700 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
701
702 /**
703 * All information we have collected about the runtime performance of
704 * any user id that can impact battery performance.
705 */
706 final BatteryStatsService mBatteryStatsService;
707
708 /**
709 * information about component usage
710 */
711 final UsageStatsService mUsageStatsService;
712
713 /**
714 * Current configuration information. HistoryRecord objects are given
715 * a reference to this object to indicate which configuration they are
716 * currently running in, so this object must be kept immutable.
717 */
718 Configuration mConfiguration = new Configuration();
719
720 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800721 * Current sequencing integer of the configuration, for skipping old
722 * configurations.
723 */
724 int mConfigurationSeq = 0;
725
726 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700727 * Hardware-reported OpenGLES version.
728 */
729 final int GL_ES_VERSION;
730
731 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 * List of initialization arguments to pass to all processes when binding applications to them.
733 * For example, references to the commonly used services.
734 */
735 HashMap<String, IBinder> mAppBindArgs;
736
737 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700738 * Temporary to avoid allocations. Protected by main lock.
739 */
740 final StringBuilder mStringBuilder = new StringBuilder(256);
741
742 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 * Used to control how we initialize the service.
744 */
745 boolean mStartRunning = false;
746 ComponentName mTopComponent;
747 String mTopAction;
748 String mTopData;
749 boolean mSystemReady = false;
750 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700751 boolean mWaitingUpdate = false;
752 boolean mDidUpdate = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753
754 Context mContext;
755
756 int mFactoryTest;
757
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700758 boolean mCheckedForSetup;
759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700761 * The time at which we will allow normal application switches again,
762 * after a call to {@link #stopAppSwitches()}.
763 */
764 long mAppSwitchesAllowedTime;
765
766 /**
767 * This is set to true after the first switch after mAppSwitchesAllowedTime
768 * is set; any switches after that will clear the time.
769 */
770 boolean mDidAppSwitch;
771
772 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 * Set while we are wanting to sleep, to prevent any
774 * activities from being started/resumed.
775 */
776 boolean mSleeping = false;
777
778 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700779 * Set if we are shutting down the system, similar to sleeping.
780 */
781 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782
783 /**
784 * Task identifier that activities are currently being started
785 * in. Incremented each time a new task is created.
786 * todo: Replace this with a TokenSpace class that generates non-repeating
787 * integers that won't wrap.
788 */
789 int mCurTask = 1;
790
791 /**
792 * Current sequence id for oom_adj computation traversal.
793 */
794 int mAdjSeq = 0;
795
796 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700797 * Current sequence id for process LRU updating.
798 */
799 int mLruSeq = 0;
800
801 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 * Set to true if the ANDROID_SIMPLE_PROCESS_MANAGEMENT envvar
803 * is set, indicating the user wants processes started in such a way
804 * that they can use ANDROID_PROCESS_WRAPPER and know what will be
805 * running in each process (thus no pre-initialized process, etc).
806 */
807 boolean mSimpleProcessManagement = false;
808
809 /**
810 * System monitoring: number of processes that died since the last
811 * N procs were started.
812 */
813 int[] mProcDeaths = new int[20];
814
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700815 /**
816 * This is set if we had to do a delayed dexopt of an app before launching
817 * it, to increasing the ANR timeouts in that case.
818 */
819 boolean mDidDexOpt;
820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 String mDebugApp = null;
822 boolean mWaitForDebugger = false;
823 boolean mDebugTransient = false;
824 String mOrigDebugApp = null;
825 boolean mOrigWaitForDebugger = false;
826 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700827 IActivityController mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700829 final RemoteCallbackList<IActivityWatcher> mWatchers
830 = new RemoteCallbackList<IActivityWatcher>();
831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 /**
833 * Callback of last caller to {@link #requestPss}.
834 */
835 Runnable mRequestPssCallback;
836
837 /**
838 * Remaining processes for which we are waiting results from the last
839 * call to {@link #requestPss}.
840 */
841 final ArrayList<ProcessRecord> mRequestPssList
842 = new ArrayList<ProcessRecord>();
843
844 /**
845 * Runtime statistics collection thread. This object's lock is used to
846 * protect all related state.
847 */
848 final Thread mProcessStatsThread;
849
850 /**
851 * Used to collect process stats when showing not responding dialog.
852 * Protected by mProcessStatsThread.
853 */
854 final ProcessStats mProcessStats = new ProcessStats(
855 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700856 final AtomicLong mLastCpuTime = new AtomicLong(0);
857 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 long mLastWriteTime = 0;
860
861 /**
862 * Set to true after the system has finished booting.
863 */
864 boolean mBooted = false;
865
866 int mProcessLimit = 0;
867
868 WindowManagerService mWindowManager;
869
870 static ActivityManagerService mSelf;
871 static ActivityThread mSystemThread;
872
873 private final class AppDeathRecipient implements IBinder.DeathRecipient {
874 final ProcessRecord mApp;
875 final int mPid;
876 final IApplicationThread mAppThread;
877
878 AppDeathRecipient(ProcessRecord app, int pid,
879 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800880 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 TAG, "New death recipient " + this
882 + " for thread " + thread.asBinder());
883 mApp = app;
884 mPid = pid;
885 mAppThread = thread;
886 }
887
888 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800889 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 TAG, "Death received in " + this
891 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 synchronized(ActivityManagerService.this) {
893 appDiedLocked(mApp, mPid, mAppThread);
894 }
895 }
896 }
897
898 static final int SHOW_ERROR_MSG = 1;
899 static final int SHOW_NOT_RESPONDING_MSG = 2;
900 static final int SHOW_FACTORY_ERROR_MSG = 3;
901 static final int UPDATE_CONFIGURATION_MSG = 4;
902 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
903 static final int WAIT_FOR_DEBUGGER_MSG = 6;
904 static final int BROADCAST_INTENT_MSG = 7;
905 static final int BROADCAST_TIMEOUT_MSG = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 static final int SERVICE_TIMEOUT_MSG = 12;
907 static final int UPDATE_TIME_ZONE = 13;
908 static final int SHOW_UID_ERROR_MSG = 14;
909 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700911 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700912 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800913 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700914 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
915 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700916 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917
918 AlertDialog mUidAlert;
919
920 final Handler mHandler = new Handler() {
921 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800922 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 //}
924
925 public void handleMessage(Message msg) {
926 switch (msg.what) {
927 case SHOW_ERROR_MSG: {
928 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 synchronized (ActivityManagerService.this) {
930 ProcessRecord proc = (ProcessRecord)data.get("app");
931 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800932 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 return;
934 }
935 AppErrorResult res = (AppErrorResult) data.get("result");
Dianne Hackborn55280a92009-05-07 15:53:46 -0700936 if (!mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800937 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 d.show();
939 proc.crashDialog = d;
940 } else {
941 // The device is asleep, so just pretend that the user
942 // saw a crash dialog and hit "force quit".
943 res.set(0);
944 }
945 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700946
947 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 } break;
949 case SHOW_NOT_RESPONDING_MSG: {
950 synchronized (ActivityManagerService.this) {
951 HashMap data = (HashMap) msg.obj;
952 ProcessRecord proc = (ProcessRecord)data.get("app");
953 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800954 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 return;
956 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800957
958 broadcastIntentLocked(null, null, new Intent("android.intent.action.ANR"),
959 null, null, 0, null, null, null,
960 false, false, MY_PID, Process.SYSTEM_UID);
961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700963 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 d.show();
965 proc.anrDialog = d;
966 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700967
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700968 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700970 case SHOW_STRICT_MODE_VIOLATION_MSG: {
971 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
972 synchronized (ActivityManagerService.this) {
973 ProcessRecord proc = (ProcessRecord) data.get("app");
974 if (proc == null) {
975 Slog.e(TAG, "App not found when showing strict mode dialog.");
976 break;
977 }
978 if (proc.crashDialog != null) {
979 Slog.e(TAG, "App already has strict mode dialog: " + proc);
980 return;
981 }
982 AppErrorResult res = (AppErrorResult) data.get("result");
983 if (!mSleeping && !mShuttingDown) {
984 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
985 d.show();
986 proc.crashDialog = d;
987 } else {
988 // The device is asleep, so just pretend that the user
989 // saw a crash dialog and hit "force quit".
990 res.set(0);
991 }
992 }
993 ensureBootCompleted();
994 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 case SHOW_FACTORY_ERROR_MSG: {
996 Dialog d = new FactoryErrorDialog(
997 mContext, msg.getData().getCharSequence("msg"));
998 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700999 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 } break;
1001 case UPDATE_CONFIGURATION_MSG: {
1002 final ContentResolver resolver = mContext.getContentResolver();
1003 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1004 } break;
1005 case GC_BACKGROUND_PROCESSES_MSG: {
1006 synchronized (ActivityManagerService.this) {
1007 performAppGcsIfAppropriateLocked();
1008 }
1009 } break;
1010 case WAIT_FOR_DEBUGGER_MSG: {
1011 synchronized (ActivityManagerService.this) {
1012 ProcessRecord app = (ProcessRecord)msg.obj;
1013 if (msg.arg1 != 0) {
1014 if (!app.waitedForDebugger) {
1015 Dialog d = new AppWaitingForDebuggerDialog(
1016 ActivityManagerService.this,
1017 mContext, app);
1018 app.waitDialog = d;
1019 app.waitedForDebugger = true;
1020 d.show();
1021 }
1022 } else {
1023 if (app.waitDialog != null) {
1024 app.waitDialog.dismiss();
1025 app.waitDialog = null;
1026 }
1027 }
1028 }
1029 } break;
1030 case BROADCAST_INTENT_MSG: {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001031 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 TAG, "Received BROADCAST_INTENT_MSG");
1033 processNextBroadcast(true);
1034 } break;
1035 case BROADCAST_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001036 if (mDidDexOpt) {
1037 mDidDexOpt = false;
1038 Message nmsg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
1039 mHandler.sendMessageDelayed(nmsg, BROADCAST_TIMEOUT);
1040 return;
1041 }
Jeff Hamiltonacf84742010-05-25 22:10:18 -05001042 // Only process broadcast timeouts if the system is ready. That way
1043 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1044 // to do heavy lifting for system up
1045 if (mSystemReady) {
1046 broadcastTimeout();
1047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001050 if (mDidDexOpt) {
1051 mDidDexOpt = false;
1052 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1053 nmsg.obj = msg.obj;
1054 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
1055 return;
1056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 serviceTimeout((ProcessRecord)msg.obj);
1058 } break;
1059 case UPDATE_TIME_ZONE: {
1060 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001061 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1062 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 if (r.thread != null) {
1064 try {
1065 r.thread.updateTimeZone();
1066 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001067 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069 }
1070 }
1071 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001072 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 case SHOW_UID_ERROR_MSG: {
1074 // XXX This is a temporary dialog, no need to localize.
1075 AlertDialog d = new BaseErrorDialog(mContext);
1076 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1077 d.setCancelable(false);
1078 d.setTitle("System UIDs Inconsistent");
1079 d.setMessage("UIDs on the system are inconsistent, you need to wipe your data partition or your device will be unstable.");
1080 d.setButton("I'm Feeling Lucky",
1081 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1082 mUidAlert = d;
1083 d.show();
1084 } break;
1085 case IM_FEELING_LUCKY_MSG: {
1086 if (mUidAlert != null) {
1087 mUidAlert.dismiss();
1088 mUidAlert = null;
1089 }
1090 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001092 if (mDidDexOpt) {
1093 mDidDexOpt = false;
1094 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1095 nmsg.obj = msg.obj;
1096 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1097 return;
1098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 ProcessRecord app = (ProcessRecord)msg.obj;
1100 synchronized (ActivityManagerService.this) {
1101 processStartTimedOutLocked(app);
1102 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001103 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001104 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1105 synchronized (ActivityManagerService.this) {
1106 doPendingActivityLaunchesLocked(true);
1107 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001108 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001109 case KILL_APPLICATION_MSG: {
1110 synchronized (ActivityManagerService.this) {
1111 int uid = msg.arg1;
1112 boolean restart = (msg.arg2 == 1);
1113 String pkg = (String) msg.obj;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001114 forceStopPackageLocked(pkg, uid, restart, false, true);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001115 }
1116 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001117 case FINALIZE_PENDING_INTENT_MSG: {
1118 ((PendingIntentRecord)msg.obj).completeFinalize();
1119 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001120 case POST_HEAVY_NOTIFICATION_MSG: {
1121 INotificationManager inm = NotificationManager.getService();
1122 if (inm == null) {
1123 return;
1124 }
1125
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001126 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001127 ProcessRecord process = root.app;
1128 if (process == null) {
1129 return;
1130 }
1131
1132 try {
1133 Context context = mContext.createPackageContext(process.info.packageName, 0);
1134 String text = mContext.getString(R.string.heavy_weight_notification,
1135 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1136 Notification notification = new Notification();
1137 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1138 notification.when = 0;
1139 notification.flags = Notification.FLAG_ONGOING_EVENT;
1140 notification.tickerText = text;
1141 notification.defaults = 0; // please be quiet
1142 notification.sound = null;
1143 notification.vibrate = null;
1144 notification.setLatestEventInfo(context, text,
1145 mContext.getText(R.string.heavy_weight_notification_detail),
1146 PendingIntent.getActivity(mContext, 0, root.intent,
1147 PendingIntent.FLAG_CANCEL_CURRENT));
1148
1149 try {
1150 int[] outId = new int[1];
1151 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1152 notification, outId);
1153 } catch (RuntimeException e) {
1154 Slog.w(ActivityManagerService.TAG,
1155 "Error showing notification for heavy-weight app", e);
1156 } catch (RemoteException e) {
1157 }
1158 } catch (NameNotFoundException e) {
1159 Log.w(TAG, "Unable to create context for heavy notification", e);
1160 }
1161 } break;
1162 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1163 INotificationManager inm = NotificationManager.getService();
1164 if (inm == null) {
1165 return;
1166 }
1167 try {
1168 inm.cancelNotification("android",
1169 R.string.heavy_weight_notification);
1170 } catch (RuntimeException e) {
1171 Slog.w(ActivityManagerService.TAG,
1172 "Error canceling notification for service", e);
1173 } catch (RemoteException e) {
1174 }
1175 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 }
1177 }
1178 };
1179
1180 public static void setSystemProcess() {
1181 try {
1182 ActivityManagerService m = mSelf;
1183
1184 ServiceManager.addService("activity", m);
1185 ServiceManager.addService("meminfo", new MemBinder(m));
1186 if (MONITOR_CPU_USAGE) {
1187 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 ServiceManager.addService("permission", new PermissionController(m));
1190
1191 ApplicationInfo info =
1192 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001193 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001194 mSystemThread.installSystemApplicationInfo(info);
1195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 synchronized (mSelf) {
1197 ProcessRecord app = mSelf.newProcessRecordLocked(
1198 mSystemThread.getApplicationThread(), info,
1199 info.processName);
1200 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001201 app.pid = MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 app.maxAdj = SYSTEM_ADJ;
1203 mSelf.mProcessNames.put(app.processName, app.info.uid, app);
1204 synchronized (mSelf.mPidsSelfLocked) {
1205 mSelf.mPidsSelfLocked.put(app.pid, app);
1206 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001207 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
1209 } catch (PackageManager.NameNotFoundException e) {
1210 throw new RuntimeException(
1211 "Unable to find android system package", e);
1212 }
1213 }
1214
1215 public void setWindowManager(WindowManagerService wm) {
1216 mWindowManager = wm;
1217 }
1218
1219 public static final Context main(int factoryTest) {
1220 AThread thr = new AThread();
1221 thr.start();
1222
1223 synchronized (thr) {
1224 while (thr.mService == null) {
1225 try {
1226 thr.wait();
1227 } catch (InterruptedException e) {
1228 }
1229 }
1230 }
1231
1232 ActivityManagerService m = thr.mService;
1233 mSelf = m;
1234 ActivityThread at = ActivityThread.systemMain();
1235 mSystemThread = at;
1236 Context context = at.getSystemContext();
1237 m.mContext = context;
1238 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001239 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240
1241 m.mBatteryStatsService.publish(context);
1242 m.mUsageStatsService.publish(context);
1243
1244 synchronized (thr) {
1245 thr.mReady = true;
1246 thr.notifyAll();
1247 }
1248
1249 m.startRunning(null, null, null, null);
1250
1251 return context;
1252 }
1253
1254 public static ActivityManagerService self() {
1255 return mSelf;
1256 }
1257
1258 static class AThread extends Thread {
1259 ActivityManagerService mService;
1260 boolean mReady = false;
1261
1262 public AThread() {
1263 super("ActivityManager");
1264 }
1265
1266 public void run() {
1267 Looper.prepare();
1268
1269 android.os.Process.setThreadPriority(
1270 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001271 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272
1273 ActivityManagerService m = new ActivityManagerService();
1274
1275 synchronized (this) {
1276 mService = m;
1277 notifyAll();
1278 }
1279
1280 synchronized (this) {
1281 while (!mReady) {
1282 try {
1283 wait();
1284 } catch (InterruptedException e) {
1285 }
1286 }
1287 }
1288
1289 Looper.loop();
1290 }
1291 }
1292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 static class MemBinder extends Binder {
1294 ActivityManagerService mActivityManagerService;
1295 MemBinder(ActivityManagerService activityManagerService) {
1296 mActivityManagerService = activityManagerService;
1297 }
1298
1299 @Override
1300 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1301 ActivityManagerService service = mActivityManagerService;
1302 ArrayList<ProcessRecord> procs;
1303 synchronized (mActivityManagerService) {
1304 if (args != null && args.length > 0
1305 && args[0].charAt(0) != '-') {
1306 procs = new ArrayList<ProcessRecord>();
1307 int pid = -1;
1308 try {
1309 pid = Integer.parseInt(args[0]);
1310 } catch (NumberFormatException e) {
1311
1312 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001313 for (int i=service.mLruProcesses.size()-1; i>=0; i--) {
1314 ProcessRecord proc = service.mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 if (proc.pid == pid) {
1316 procs.add(proc);
1317 } else if (proc.processName.equals(args[0])) {
1318 procs.add(proc);
1319 }
1320 }
1321 if (procs.size() <= 0) {
1322 pw.println("No process found for: " + args[0]);
1323 return;
1324 }
1325 } else {
Dianne Hackborn472ad872010-04-07 17:31:48 -07001326 procs = new ArrayList<ProcessRecord>(service.mLruProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 }
1328 }
1329 dumpApplicationMemoryUsage(fd, pw, procs, " ", args);
1330 }
1331 }
1332
1333 static class CpuBinder extends Binder {
1334 ActivityManagerService mActivityManagerService;
1335 CpuBinder(ActivityManagerService activityManagerService) {
1336 mActivityManagerService = activityManagerService;
1337 }
1338
1339 @Override
1340 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1341 synchronized (mActivityManagerService.mProcessStatsThread) {
1342 pw.print(mActivityManagerService.mProcessStats.printCurrentState());
1343 }
1344 }
1345 }
1346
1347 private ActivityManagerService() {
1348 String v = System.getenv("ANDROID_SIMPLE_PROCESS_MANAGEMENT");
1349 if (v != null && Integer.getInteger(v) != 0) {
1350 mSimpleProcessManagement = true;
1351 }
1352 v = System.getenv("ANDROID_DEBUG_APP");
1353 if (v != null) {
1354 mSimpleProcessManagement = true;
1355 }
1356
Joe Onorato8a9b2202010-02-26 18:56:32 -08001357 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 File dataDir = Environment.getDataDirectory();
1360 File systemDir = new File(dataDir, "system");
1361 systemDir.mkdirs();
1362 mBatteryStatsService = new BatteryStatsService(new File(
1363 systemDir, "batterystats.bin").toString());
1364 mBatteryStatsService.getActiveStatistics().readLocked();
1365 mBatteryStatsService.getActiveStatistics().writeLocked();
1366
1367 mUsageStatsService = new UsageStatsService( new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001368 systemDir, "usagestats").toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369
Jack Palevichb90d28c2009-07-22 15:35:24 -07001370 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1371 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1372
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001373 mConfiguration.setToDefaults();
1374 mConfiguration.locale = Locale.getDefault();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 mProcessStats.init();
1376
1377 // Add ourself to the Watchdog monitors.
1378 Watchdog.getInstance().addMonitor(this);
1379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 mProcessStatsThread = new Thread("ProcessStats") {
1381 public void run() {
1382 while (true) {
1383 try {
1384 try {
1385 synchronized(this) {
1386 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001387 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001389 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 // + ", write delay=" + nextWriteDelay);
1391 if (nextWriteDelay < nextCpuDelay) {
1392 nextCpuDelay = nextWriteDelay;
1393 }
1394 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001395 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 this.wait(nextCpuDelay);
1397 }
1398 }
1399 } catch (InterruptedException e) {
1400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 updateCpuStatsNow();
1402 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001403 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
1405 }
1406 }
1407 };
1408 mProcessStatsThread.start();
1409 }
1410
1411 @Override
1412 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1413 throws RemoteException {
1414 try {
1415 return super.onTransact(code, data, reply, flags);
1416 } catch (RuntimeException e) {
1417 // The activity manager only throws security exceptions, so let's
1418 // log all others.
1419 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001420 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 }
1422 throw e;
1423 }
1424 }
1425
1426 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001427 final long now = SystemClock.uptimeMillis();
1428 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1429 return;
1430 }
1431 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1432 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 mProcessStatsThread.notify();
1434 }
1435 }
1436 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 void updateCpuStatsNow() {
1439 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001440 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 final long now = SystemClock.uptimeMillis();
1442 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001445 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1446 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 haveNewCpuStats = true;
1448 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001449 //Slog.i(TAG, mProcessStats.printCurrentState());
1450 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 // + mProcessStats.getTotalCpuPercent() + "%");
1452
Joe Onorato8a9b2202010-02-26 18:56:32 -08001453 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 if ("true".equals(SystemProperties.get("events.cpu"))) {
1455 int user = mProcessStats.getLastUserTime();
1456 int system = mProcessStats.getLastSystemTime();
1457 int iowait = mProcessStats.getLastIoWaitTime();
1458 int irq = mProcessStats.getLastIrqTime();
1459 int softIrq = mProcessStats.getLastSoftIrqTime();
1460 int idle = mProcessStats.getLastIdleTime();
1461
1462 int total = user + system + iowait + irq + softIrq + idle;
1463 if (total == 0) total = 1;
1464
Doug Zongker2bec3d42009-12-04 12:52:44 -08001465 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 ((user+system+iowait+irq+softIrq) * 100) / total,
1467 (user * 100) / total,
1468 (system * 100) / total,
1469 (iowait * 100) / total,
1470 (irq * 100) / total,
1471 (softIrq * 100) / total);
1472 }
1473 }
1474
Amith Yamasanie43530a2009-08-21 13:11:37 -07001475 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001476 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001477 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 synchronized(mPidsSelfLocked) {
1479 if (haveNewCpuStats) {
1480 if (mBatteryStatsService.isOnBattery()) {
1481 final int N = mProcessStats.countWorkingStats();
1482 for (int i=0; i<N; i++) {
1483 ProcessStats.Stats st
1484 = mProcessStats.getWorkingStats(i);
1485 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
1486 if (pr != null) {
1487 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
1488 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001489 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001490 } else {
1491 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001492 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001493 if (ps != null) {
1494 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001495 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
1498 }
1499 }
1500 }
1501 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1504 mLastWriteTime = now;
1505 mBatteryStatsService.getActiveStatistics().writeLocked();
1506 }
1507 }
1508 }
1509 }
1510
1511 /**
1512 * Initialize the application bind args. These are passed to each
1513 * process when the bindApplication() IPC is sent to the process. They're
1514 * lazily setup to make sure the services are running when they're asked for.
1515 */
1516 private HashMap<String, IBinder> getCommonServicesLocked() {
1517 if (mAppBindArgs == null) {
1518 mAppBindArgs = new HashMap<String, IBinder>();
1519
1520 // Setup the application init args
1521 mAppBindArgs.put("package", ServiceManager.getService("package"));
1522 mAppBindArgs.put("window", ServiceManager.getService("window"));
1523 mAppBindArgs.put(Context.ALARM_SERVICE,
1524 ServiceManager.getService(Context.ALARM_SERVICE));
1525 }
1526 return mAppBindArgs;
1527 }
1528
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001529 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 if (mFocusedActivity != r) {
1531 mFocusedActivity = r;
1532 mWindowManager.setFocusedApp(r, true);
1533 }
1534 }
1535
Dianne Hackborn906497c2010-05-10 15:57:38 -07001536 private final void updateLruProcessInternalLocked(ProcessRecord app,
1537 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001539 int lrui = mLruProcesses.indexOf(app);
1540 if (lrui >= 0) mLruProcesses.remove(lrui);
1541
1542 int i = mLruProcesses.size()-1;
1543 int skipTop = 0;
1544
Dianne Hackborn906497c2010-05-10 15:57:38 -07001545 app.lruSeq = mLruSeq;
1546
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001547 // compute the new weight for this process.
1548 if (updateActivityTime) {
1549 app.lastActivityTime = SystemClock.uptimeMillis();
1550 }
1551 if (app.activities.size() > 0) {
1552 // If this process has activities, we more strongly want to keep
1553 // it around.
1554 app.lruWeight = app.lastActivityTime;
1555 } else if (app.pubProviders.size() > 0) {
1556 // If this process contains content providers, we want to keep
1557 // it a little more strongly.
1558 app.lruWeight = app.lastActivityTime - CONTENT_APP_IDLE_OFFSET;
1559 // Also don't let it kick out the first few "real" hidden processes.
1560 skipTop = MIN_HIDDEN_APPS;
1561 } else {
1562 // If this process doesn't have activities, we less strongly
1563 // want to keep it around, and generally want to avoid getting
1564 // in front of any very recently used activities.
1565 app.lruWeight = app.lastActivityTime - EMPTY_APP_IDLE_OFFSET;
1566 // Also don't let it kick out the first few "real" hidden processes.
1567 skipTop = MIN_HIDDEN_APPS;
1568 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001569
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001570 while (i >= 0) {
1571 ProcessRecord p = mLruProcesses.get(i);
1572 // If this app shouldn't be in front of the first N background
1573 // apps, then skip over that many that are currently hidden.
1574 if (skipTop > 0 && p.setAdj >= HIDDEN_APP_MIN_ADJ) {
1575 skipTop--;
1576 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001577 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001578 mLruProcesses.add(i+1, app);
1579 break;
1580 }
1581 i--;
1582 }
1583 if (i < 0) {
1584 mLruProcesses.add(0, app);
1585 }
1586
Dianne Hackborn906497c2010-05-10 15:57:38 -07001587 // If the app is currently using a content provider or service,
1588 // bump those processes as well.
1589 if (app.connections.size() > 0) {
1590 for (ConnectionRecord cr : app.connections) {
1591 if (cr.binding != null && cr.binding.service != null
1592 && cr.binding.service.app != null
1593 && cr.binding.service.app.lruSeq != mLruSeq) {
1594 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1595 updateActivityTime, i+1);
1596 }
1597 }
1598 }
1599 if (app.conProviders.size() > 0) {
1600 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
1601 if (cpr.app != null && cpr.app.lruSeq != mLruSeq) {
1602 updateLruProcessInternalLocked(cpr.app, oomAdj,
1603 updateActivityTime, i+1);
1604 }
1605 }
1606 }
1607
Joe Onorato8a9b2202010-02-26 18:56:32 -08001608 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 if (oomAdj) {
1610 updateOomAdjLocked();
1611 }
1612 }
1613
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001614 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001615 boolean oomAdj, boolean updateActivityTime) {
1616 mLruSeq++;
1617 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1618 }
1619
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001620 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 String processName, int uid) {
1622 if (uid == Process.SYSTEM_UID) {
1623 // The system gets to run in any process. If there are multiple
1624 // processes with the same uid, just pick the first (this
1625 // should never happen).
1626 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1627 processName);
1628 return procs != null ? procs.valueAt(0) : null;
1629 }
1630 ProcessRecord proc = mProcessNames.get(processName, uid);
1631 return proc;
1632 }
1633
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001634 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001635 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001636 try {
1637 if (pm.performDexOpt(packageName)) {
1638 mDidDexOpt = true;
1639 }
1640 } catch (RemoteException e) {
1641 }
1642 }
1643
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001644 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 int transit = mWindowManager.getPendingAppTransition();
1646 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1647 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1648 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1649 }
1650
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001651 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001653 String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 ProcessRecord app = getProcessRecordLocked(processName, info.uid);
1655 // We don't have to do anything more if:
1656 // (1) There is an existing application record; and
1657 // (2) The caller doesn't think it is dead, OR there is no thread
1658 // object attached to it so we know it couldn't have crashed; and
1659 // (3) There is a pid assigned to it, so it is either starting or
1660 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001661 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 + " app=" + app + " knownToBeDead=" + knownToBeDead
1663 + " thread=" + (app != null ? app.thread : null)
1664 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001665 if (app != null && app.pid > 0) {
1666 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001667 // We already have the app running, or are waiting for it to
1668 // come up (we have a pid but not yet its thread), so keep it.
Magnus Edlund7bb25812010-02-24 15:45:06 +01001669 return app;
1670 } else {
1671 // An application record is attached to a previous process,
1672 // clean it up now.
1673 handleAppDiedLocked(app, true);
1674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 String hostingNameStr = hostingName != null
1678 ? hostingName.flattenToShortString() : null;
1679
1680 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1681 // If we are in the background, then check to see if this process
1682 // is bad. If so, we will just silently fail.
1683 if (mBadProcesses.get(info.processName, info.uid) != null) {
1684 return null;
1685 }
1686 } else {
1687 // When the user is explicitly starting a process, then clear its
1688 // crash count so that we won't make it bad until they see at
1689 // least one crash dialog again, and make the process good again
1690 // if it had been bad.
1691 mProcessCrashTimes.remove(info.processName, info.uid);
1692 if (mBadProcesses.get(info.processName, info.uid) != null) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08001693 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 info.processName);
1695 mBadProcesses.remove(info.processName, info.uid);
1696 if (app != null) {
1697 app.bad = false;
1698 }
1699 }
1700 }
1701
1702 if (app == null) {
1703 app = newProcessRecordLocked(null, info, processName);
1704 mProcessNames.put(processName, info.uid, app);
1705 } else {
1706 // If this is a new package in the process, add the package to the list
1707 app.addPackage(info.packageName);
1708 }
1709
1710 // If the system is not ready yet, then hold off on starting this
1711 // process until it is.
1712 if (!mSystemReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001713 && !isAllowedWhileBooting(info)
1714 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 if (!mProcessesOnHold.contains(app)) {
1716 mProcessesOnHold.add(app);
1717 }
1718 return app;
1719 }
1720
1721 startProcessLocked(app, hostingType, hostingNameStr);
1722 return (app.pid != 0) ? app : null;
1723 }
1724
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001725 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1726 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1727 }
1728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 private final void startProcessLocked(ProcessRecord app,
1730 String hostingType, String hostingNameStr) {
1731 if (app.pid > 0 && app.pid != MY_PID) {
1732 synchronized (mPidsSelfLocked) {
1733 mPidsSelfLocked.remove(app.pid);
1734 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1735 }
1736 app.pid = 0;
1737 }
1738
1739 mProcessesOnHold.remove(app);
1740
1741 updateCpuStats();
1742
1743 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1744 mProcDeaths[0] = 0;
1745
1746 try {
1747 int uid = app.info.uid;
1748 int[] gids = null;
1749 try {
1750 gids = mContext.getPackageManager().getPackageGids(
1751 app.info.packageName);
1752 } catch (PackageManager.NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001753 Slog.w(TAG, "Unable to retrieve gids", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
1755 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1756 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1757 && mTopComponent != null
1758 && app.processName.equals(mTopComponent.getPackageName())) {
1759 uid = 0;
1760 }
1761 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1762 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1763 uid = 0;
1764 }
1765 }
1766 int debugFlags = 0;
1767 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1768 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
1769 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001770 // Run the app in safe mode if its manifest requests so or the
1771 // system is booted in safe mode.
1772 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1773 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001774 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1777 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1778 }
1779 if ("1".equals(SystemProperties.get("debug.assert"))) {
1780 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1781 }
1782 int pid = Process.start("android.app.ActivityThread",
1783 mSimpleProcessManagement ? app.processName : null, uid, uid,
1784 gids, debugFlags, null);
1785 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1786 synchronized (bs) {
1787 if (bs.isOnBattery()) {
1788 app.batteryStats.incStartsLocked();
1789 }
1790 }
1791
Doug Zongker2bec3d42009-12-04 12:52:44 -08001792 EventLog.writeEvent(EventLogTags.AM_PROC_START, pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 app.processName, hostingType,
1794 hostingNameStr != null ? hostingNameStr : "");
1795
1796 if (app.persistent) {
Christopher Tatec27181c2010-06-30 14:41:09 -07001797 Watchdog.getInstance().processStarted(app.processName, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 }
1799
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07001800 StringBuilder buf = mStringBuilder;
1801 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 buf.append("Start proc ");
1803 buf.append(app.processName);
1804 buf.append(" for ");
1805 buf.append(hostingType);
1806 if (hostingNameStr != null) {
1807 buf.append(" ");
1808 buf.append(hostingNameStr);
1809 }
1810 buf.append(": pid=");
1811 buf.append(pid);
1812 buf.append(" uid=");
1813 buf.append(uid);
1814 buf.append(" gids={");
1815 if (gids != null) {
1816 for (int gi=0; gi<gids.length; gi++) {
1817 if (gi != 0) buf.append(", ");
1818 buf.append(gids[gi]);
1819
1820 }
1821 }
1822 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001823 Slog.i(TAG, buf.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 if (pid == 0 || pid == MY_PID) {
1825 // Processes are being emulated with threads.
1826 app.pid = MY_PID;
1827 app.removed = false;
1828 mStartingProcesses.add(app);
1829 } else if (pid > 0) {
1830 app.pid = pid;
1831 app.removed = false;
1832 synchronized (mPidsSelfLocked) {
1833 this.mPidsSelfLocked.put(pid, app);
1834 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1835 msg.obj = app;
1836 mHandler.sendMessageDelayed(msg, PROC_START_TIMEOUT);
1837 }
1838 } else {
1839 app.pid = 0;
1840 RuntimeException e = new RuntimeException(
1841 "Failure starting process " + app.processName
1842 + ": returned pid=" + pid);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001843 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 }
1845 } catch (RuntimeException e) {
1846 // XXX do better error recovery.
1847 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001848 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 }
1850 }
1851
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001852 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 if (resumed) {
1854 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
1855 } else {
1856 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
1857 }
1858 }
1859
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001860 boolean startHomeActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001861 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1862 && mTopAction == null) {
1863 // We are running in factory test mode, but unable to find
1864 // the factory test app, so just sit around displaying the
1865 // error message and don't try to start anything.
1866 return false;
1867 }
1868 Intent intent = new Intent(
1869 mTopAction,
1870 mTopData != null ? Uri.parse(mTopData) : null);
1871 intent.setComponent(mTopComponent);
1872 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
1873 intent.addCategory(Intent.CATEGORY_HOME);
1874 }
1875 ActivityInfo aInfo =
1876 intent.resolveActivityInfo(mContext.getPackageManager(),
1877 STOCK_PM_FLAGS);
1878 if (aInfo != null) {
1879 intent.setComponent(new ComponentName(
1880 aInfo.applicationInfo.packageName, aInfo.name));
1881 // Don't do this if the home app is currently being
1882 // instrumented.
1883 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
1884 aInfo.applicationInfo.uid);
1885 if (app == null || app.instrumentationClass == null) {
1886 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001887 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001888 null, null, 0, 0, 0, false, false);
1889 }
1890 }
1891
1892
1893 return true;
1894 }
1895
1896 /**
1897 * Starts the "new version setup screen" if appropriate.
1898 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001899 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001900 // Only do this once per boot.
1901 if (mCheckedForSetup) {
1902 return;
1903 }
1904
1905 // We will show this screen if the current one is a different
1906 // version than the last one shown, and we are not running in
1907 // low-level factory test mode.
1908 final ContentResolver resolver = mContext.getContentResolver();
1909 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
1910 Settings.Secure.getInt(resolver,
1911 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
1912 mCheckedForSetup = true;
1913
1914 // See if we should be showing the platform update setup UI.
1915 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
1916 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
1917 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
1918
1919 // We don't allow third party apps to replace this.
1920 ResolveInfo ri = null;
1921 for (int i=0; ris != null && i<ris.size(); i++) {
1922 if ((ris.get(i).activityInfo.applicationInfo.flags
1923 & ApplicationInfo.FLAG_SYSTEM) != 0) {
1924 ri = ris.get(i);
1925 break;
1926 }
1927 }
1928
1929 if (ri != null) {
1930 String vers = ri.activityInfo.metaData != null
1931 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
1932 : null;
1933 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
1934 vers = ri.activityInfo.applicationInfo.metaData.getString(
1935 Intent.METADATA_SETUP_VERSION);
1936 }
1937 String lastVers = Settings.Secure.getString(
1938 resolver, Settings.Secure.LAST_SETUP_SHOWN);
1939 if (vers != null && !vers.equals(lastVers)) {
1940 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1941 intent.setComponent(new ComponentName(
1942 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001943 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001944 null, null, 0, 0, 0, false, false);
1945 }
1946 }
1947 }
1948 }
1949
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001950 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001951 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001952
1953 final int identHash = System.identityHashCode(r);
1954 updateUsageStats(r, true);
1955
1956 int i = mWatchers.beginBroadcast();
1957 while (i > 0) {
1958 i--;
1959 IActivityWatcher w = mWatchers.getBroadcastItem(i);
1960 if (w != null) {
1961 try {
1962 w.activityResuming(identHash);
1963 } catch (RemoteException e) {
1964 }
1965 }
1966 }
1967 mWatchers.finishBroadcast();
1968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001970 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001971 final int N = mPendingActivityLaunches.size();
1972 if (N <= 0) {
1973 return;
1974 }
1975 for (int i=0; i<N; i++) {
1976 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001977 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001978 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
1979 doResume && i == (N-1));
1980 }
1981 mPendingActivityLaunches.clear();
1982 }
1983
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08001984 public final int startActivity(IApplicationThread caller,
1985 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
1986 int grantedMode, IBinder resultTo,
1987 String resultWho, int requestCode, boolean onlyIfNeeded,
1988 boolean debug) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001989 return mMainStack.startActivityMayWait(caller, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07001990 grantedUriPermissions, grantedMode, resultTo, resultWho,
1991 requestCode, onlyIfNeeded, debug, null, null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08001992 }
1993
1994 public final WaitResult startActivityAndWait(IApplicationThread caller,
1995 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
1996 int grantedMode, IBinder resultTo,
1997 String resultWho, int requestCode, boolean onlyIfNeeded,
1998 boolean debug) {
1999 WaitResult res = new WaitResult();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002000 mMainStack.startActivityMayWait(caller, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002001 grantedUriPermissions, grantedMode, resultTo, resultWho,
2002 requestCode, onlyIfNeeded, debug, res, null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002003 return res;
2004 }
2005
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002006 public final int startActivityWithConfig(IApplicationThread caller,
2007 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2008 int grantedMode, IBinder resultTo,
2009 String resultWho, int requestCode, boolean onlyIfNeeded,
2010 boolean debug, Configuration config) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002011 return mMainStack.startActivityMayWait(caller, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002012 grantedUriPermissions, grantedMode, resultTo, resultWho,
2013 requestCode, onlyIfNeeded, debug, null, config);
2014 }
2015
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002016 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002017 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002018 IBinder resultTo, String resultWho, int requestCode,
2019 int flagsMask, int flagsValues) {
2020 // Refuse possible leaked file descriptors
2021 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2022 throw new IllegalArgumentException("File descriptors passed in Intent");
2023 }
2024
2025 IIntentSender sender = intent.getTarget();
2026 if (!(sender instanceof PendingIntentRecord)) {
2027 throw new IllegalArgumentException("Bad PendingIntent object");
2028 }
2029
2030 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002031
2032 synchronized (this) {
2033 // If this is coming from the currently resumed activity, it is
2034 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002035 if (mMainStack.mResumedActivity != null
2036 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002037 Binder.getCallingUid()) {
2038 mAppSwitchesAllowedTime = 0;
2039 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002040 }
2041
2042 return pir.sendInner(0, fillInIntent, resolvedType,
2043 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
2044 }
2045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 public boolean startNextMatchingActivity(IBinder callingActivity,
2047 Intent intent) {
2048 // Refuse possible leaked file descriptors
2049 if (intent != null && intent.hasFileDescriptors() == true) {
2050 throw new IllegalArgumentException("File descriptors passed in Intent");
2051 }
2052
2053 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002054 int index = mMainStack.indexOfTokenLocked(callingActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 if (index < 0) {
2056 return false;
2057 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002058 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 if (r.app == null || r.app.thread == null) {
2060 // The caller is not running... d'oh!
2061 return false;
2062 }
2063 intent = new Intent(intent);
2064 // The caller is not allowed to change the data.
2065 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2066 // And we are resetting to find the next component...
2067 intent.setComponent(null);
2068
2069 ActivityInfo aInfo = null;
2070 try {
2071 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002072 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002074 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075
2076 // Look for the original activity in the list...
2077 final int N = resolves != null ? resolves.size() : 0;
2078 for (int i=0; i<N; i++) {
2079 ResolveInfo rInfo = resolves.get(i);
2080 if (rInfo.activityInfo.packageName.equals(r.packageName)
2081 && rInfo.activityInfo.name.equals(r.info.name)) {
2082 // We found the current one... the next matching is
2083 // after it.
2084 i++;
2085 if (i<N) {
2086 aInfo = resolves.get(i).activityInfo;
2087 }
2088 break;
2089 }
2090 }
2091 } catch (RemoteException e) {
2092 }
2093
2094 if (aInfo == null) {
2095 // Nobody who is next!
2096 return false;
2097 }
2098
2099 intent.setComponent(new ComponentName(
2100 aInfo.applicationInfo.packageName, aInfo.name));
2101 intent.setFlags(intent.getFlags()&~(
2102 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2103 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2104 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2105 Intent.FLAG_ACTIVITY_NEW_TASK));
2106
2107 // Okay now we need to start the new activity, replacing the
2108 // currently running activity. This is a little tricky because
2109 // we want to start the new one as if the current one is finished,
2110 // but not finish the current one first so that there is no flicker.
2111 // And thus...
2112 final boolean wasFinishing = r.finishing;
2113 r.finishing = true;
2114
2115 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002116 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 final String resultWho = r.resultWho;
2118 final int requestCode = r.requestCode;
2119 r.resultTo = null;
2120 if (resultTo != null) {
2121 resultTo.removeResultsLocked(r, resultWho, requestCode);
2122 }
2123
2124 final long origId = Binder.clearCallingIdentity();
2125 // XXX we are not dealing with propagating grantedUriPermissions...
2126 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002127 int res = mMainStack.startActivityLocked(r.app.thread, intent,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 r.resolvedType, null, 0, aInfo, resultTo, resultWho,
The Android Open Source Project4df24232009-03-05 14:34:35 -08002129 requestCode, -1, r.launchedFromUid, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 Binder.restoreCallingIdentity(origId);
2131
2132 r.finishing = wasFinishing;
2133 if (res != START_SUCCESS) {
2134 return false;
2135 }
2136 return true;
2137 }
2138 }
2139
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002140 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 Intent intent, String resolvedType, IBinder resultTo,
2142 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002143
2144 // This is so super not safe, that only the system (or okay root)
2145 // can do it.
2146 final int callingUid = Binder.getCallingUid();
2147 if (callingUid != 0 && callingUid != Process.myUid()) {
2148 throw new SecurityException(
2149 "startActivityInPackage only available to the system");
2150 }
2151
The Android Open Source Project4df24232009-03-05 14:34:35 -08002152 final boolean componentSpecified = intent.getComponent() != null;
2153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 // Don't modify the client's object!
2155 intent = new Intent(intent);
2156
2157 // Collect information about the target of the Intent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 ActivityInfo aInfo;
2159 try {
2160 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002161 AppGlobals.getPackageManager().resolveIntent(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 intent, resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002163 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 aInfo = rInfo != null ? rInfo.activityInfo : null;
2165 } catch (RemoteException e) {
2166 aInfo = null;
2167 }
2168
2169 if (aInfo != null) {
2170 // Store the found target back into the intent, because now that
2171 // we have it we never want to do this again. For example, if the
2172 // user navigates back to this point in the history, we should
2173 // always restart the exact same activity.
2174 intent.setComponent(new ComponentName(
2175 aInfo.applicationInfo.packageName, aInfo.name));
2176 }
2177
2178 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002179 return mMainStack.startActivityLocked(null, intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 null, 0, aInfo, resultTo, resultWho, requestCode, -1, uid,
The Android Open Source Project4df24232009-03-05 14:34:35 -08002181 onlyIfNeeded, componentSpecified);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 }
2183 }
2184
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002185 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 // Remove any existing entries that are the same kind of task.
2187 int N = mRecentTasks.size();
2188 for (int i=0; i<N; i++) {
2189 TaskRecord tr = mRecentTasks.get(i);
2190 if ((task.affinity != null && task.affinity.equals(tr.affinity))
2191 || (task.intent != null && task.intent.filterEquals(tr.intent))) {
2192 mRecentTasks.remove(i);
2193 i--;
2194 N--;
2195 if (task.intent == null) {
2196 // If the new recent task we are adding is not fully
2197 // specified, then replace it with the existing recent task.
2198 task = tr;
2199 }
2200 }
2201 }
2202 if (N >= MAX_RECENT_TASKS) {
2203 mRecentTasks.remove(N-1);
2204 }
2205 mRecentTasks.add(0, task);
2206 }
2207
2208 public void setRequestedOrientation(IBinder token,
2209 int requestedOrientation) {
2210 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002211 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 if (index < 0) {
2213 return;
2214 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002215 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 final long origId = Binder.clearCallingIdentity();
2217 mWindowManager.setAppOrientation(r, requestedOrientation);
2218 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002219 mConfiguration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 r.mayFreezeScreenLocked(r.app) ? r : null);
2221 if (config != null) {
2222 r.frozenBeforeDestroy = true;
2223 if (!updateConfigurationLocked(config, r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002224 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 }
2226 }
2227 Binder.restoreCallingIdentity(origId);
2228 }
2229 }
2230
2231 public int getRequestedOrientation(IBinder token) {
2232 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002233 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 if (index < 0) {
2235 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2236 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002237 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 return mWindowManager.getAppOrientation(r);
2239 }
2240 }
2241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 /**
2243 * This is the internal entry point for handling Activity.finish().
2244 *
2245 * @param token The Binder token referencing the Activity we want to finish.
2246 * @param resultCode Result code, if any, from this Activity.
2247 * @param resultData Result data (Intent), if any, from this Activity.
2248 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002249 * @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 -08002250 */
2251 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2252 // Refuse possible leaked file descriptors
2253 if (resultData != null && resultData.hasFileDescriptors() == true) {
2254 throw new IllegalArgumentException("File descriptors passed in Intent");
2255 }
2256
2257 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002258 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002260 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 if (next != null) {
2262 // ask watcher if this is allowed
2263 boolean resumeOK = true;
2264 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002265 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002267 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 }
2269
2270 if (!resumeOK) {
2271 return false;
2272 }
2273 }
2274 }
2275 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002276 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002277 resultData, "app-request");
2278 Binder.restoreCallingIdentity(origId);
2279 return res;
2280 }
2281 }
2282
Dianne Hackborn860755f2010-06-03 18:47:52 -07002283 public final void finishHeavyWeightApp() {
2284 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2285 != PackageManager.PERMISSION_GRANTED) {
2286 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2287 + Binder.getCallingPid()
2288 + ", uid=" + Binder.getCallingUid()
2289 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2290 Slog.w(TAG, msg);
2291 throw new SecurityException(msg);
2292 }
2293
2294 synchronized(this) {
2295 if (mHeavyWeightProcess == null) {
2296 return;
2297 }
2298
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002299 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002300 mHeavyWeightProcess.activities);
2301 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002302 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002303 if (!r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002304 int index = mMainStack.indexOfTokenLocked(r);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002305 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002306 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002307 null, "finish-heavy");
2308 }
2309 }
2310 }
2311
2312 mHeavyWeightProcess = null;
2313 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2314 }
2315 }
2316
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002317 public void crashApplication(int uid, int initialPid, String packageName,
2318 String message) {
2319 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2320 != PackageManager.PERMISSION_GRANTED) {
2321 String msg = "Permission Denial: crashApplication() from pid="
2322 + Binder.getCallingPid()
2323 + ", uid=" + Binder.getCallingUid()
2324 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2325 Slog.w(TAG, msg);
2326 throw new SecurityException(msg);
2327 }
2328
2329 synchronized(this) {
2330 ProcessRecord proc = null;
2331
2332 // Figure out which process to kill. We don't trust that initialPid
2333 // still has any relation to current pids, so must scan through the
2334 // list.
2335 synchronized (mPidsSelfLocked) {
2336 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2337 ProcessRecord p = mPidsSelfLocked.valueAt(i);
2338 if (p.info.uid != uid) {
2339 continue;
2340 }
2341 if (p.pid == initialPid) {
2342 proc = p;
2343 break;
2344 }
2345 for (String str : p.pkgList) {
2346 if (str.equals(packageName)) {
2347 proc = p;
2348 }
2349 }
2350 }
2351 }
2352
2353 if (proc == null) {
2354 Log.w(TAG, "crashApplication: nothing for uid=" + uid
2355 + " initialPid=" + initialPid
2356 + " packageName=" + packageName);
2357 return;
2358 }
2359
2360 if (proc.thread != null) {
2361 long ident = Binder.clearCallingIdentity();
2362 try {
2363 proc.thread.scheduleCrash(message);
2364 } catch (RemoteException e) {
2365 }
2366 Binder.restoreCallingIdentity(ident);
2367 }
2368 }
2369 }
2370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 public final void finishSubActivity(IBinder token, String resultWho,
2372 int requestCode) {
2373 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002374 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 if (index < 0) {
2376 return;
2377 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002378 ActivityRecord self = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379
2380 final long origId = Binder.clearCallingIdentity();
2381
2382 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002383 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2384 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 if (r.resultTo == self && r.requestCode == requestCode) {
2386 if ((r.resultWho == null && resultWho == null) ||
2387 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002388 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 Activity.RESULT_CANCELED, null, "request-sub");
2390 }
2391 }
2392 }
2393
2394 Binder.restoreCallingIdentity(origId);
2395 }
2396 }
2397
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002398 public boolean willActivityBeVisible(IBinder token) {
2399 synchronized(this) {
2400 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002401 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2402 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002403 if (r == token) {
2404 return true;
2405 }
2406 if (r.fullscreen && !r.finishing) {
2407 return false;
2408 }
2409 }
2410 return true;
2411 }
2412 }
2413
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002414 public void overridePendingTransition(IBinder token, String packageName,
2415 int enterAnim, int exitAnim) {
2416 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002417 int index = mMainStack.indexOfTokenLocked(token);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002418 if (index < 0) {
2419 return;
2420 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002421 ActivityRecord self = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002422
2423 final long origId = Binder.clearCallingIdentity();
2424
2425 if (self.state == ActivityState.RESUMED
2426 || self.state == ActivityState.PAUSING) {
2427 mWindowManager.overridePendingAppTransition(packageName,
2428 enterAnim, exitAnim);
2429 }
2430
2431 Binder.restoreCallingIdentity(origId);
2432 }
2433 }
2434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 * Main function for removing an existing process from the activity manager
2437 * as a result of that process going away. Clears out all connections
2438 * to the process.
2439 */
2440 private final void handleAppDiedLocked(ProcessRecord app,
2441 boolean restarting) {
2442 cleanUpApplicationRecordLocked(app, restarting, -1);
2443 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002444 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 }
2446
2447 // Just in case...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002448 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2449 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2450 mMainStack.mPausingActivity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002452 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2453 mMainStack.mLastPausedActivity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 }
2455
2456 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002457 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458
2459 boolean atTop = true;
2460 boolean hasVisibleActivities = false;
2461
2462 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002463 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002464 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 TAG, "Removing app " + app + " from history with " + i + " entries");
2466 while (i > 0) {
2467 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002468 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002469 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2471 if (r.app == app) {
2472 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002473 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 TAG, "Removing this entry! frozen=" + r.haveState
2475 + " finishing=" + r.finishing);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002476 mMainStack.mHistory.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477
2478 r.inHistory = false;
2479 mWindowManager.removeAppToken(r);
2480 if (VALIDATE_TOKENS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002481 mWindowManager.validateAppTokens(mMainStack.mHistory);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002483 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484
2485 } else {
2486 // We have the current state for this activity, so
2487 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002488 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 TAG, "Keeping entry, setting app to null");
2490 if (r.visible) {
2491 hasVisibleActivities = true;
2492 }
2493 r.app = null;
2494 r.nowVisible = false;
2495 if (!r.haveState) {
2496 r.icicle = null;
2497 }
2498 }
2499
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002500 r.stack.cleanUpActivityLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 r.state = ActivityState.STOPPED;
2502 }
2503 atTop = false;
2504 }
2505
2506 app.activities.clear();
2507
2508 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002509 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 + " running instrumentation " + app.instrumentationClass);
2511 Bundle info = new Bundle();
2512 info.putString("shortMsg", "Process crashed.");
2513 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2514 }
2515
2516 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002517 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 // If there was nothing to resume, and we are not already
2519 // restarting this process, but there is a visible activity that
2520 // is hosted by the process... then make sure all visible
2521 // activities are running, taking care of restarting this
2522 // process.
2523 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002524 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 }
2526 }
2527 }
2528 }
2529
2530 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2531 IBinder threadBinder = thread.asBinder();
2532
2533 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002534 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2535 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2537 return i;
2538 }
2539 }
2540 return -1;
2541 }
2542
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002543 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 IApplicationThread thread) {
2545 if (thread == null) {
2546 return null;
2547 }
2548
2549 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002550 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 }
2552
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002553 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 IApplicationThread thread) {
2555
2556 mProcDeaths[0]++;
2557
Magnus Edlund7bb25812010-02-24 15:45:06 +01002558 // Clean up already done if the process has been re-started.
2559 if (app.pid == pid && app.thread != null &&
2560 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002561 if (!app.killedBackground) {
2562 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2563 + ") has died.");
2564 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002565 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002566 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 TAG, "Dying app: " + app + ", pid: " + pid
2568 + ", thread: " + thread.asBinder());
2569 boolean doLowMem = app.instrumentationClass == null;
2570 handleAppDiedLocked(app, false);
2571
2572 if (doLowMem) {
2573 // If there are no longer any background processes running,
2574 // and the app that died was not running instrumentation,
2575 // then tell everyone we are now low on memory.
2576 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002577 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2578 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 if (rec.thread != null && rec.setAdj >= HIDDEN_APP_MIN_ADJ) {
2580 haveBg = true;
2581 break;
2582 }
2583 }
2584
2585 if (!haveBg) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002586 Slog.i(TAG, "Low Memory: No more background processes.");
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002587 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002588 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002589 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2590 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002591 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002592 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2593 // The low memory report is overriding any current
2594 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002595 // heavy/important/visible/foreground processes first.
2596 if (rec.setAdj <= HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002597 rec.lastRequestedGc = 0;
2598 } else {
2599 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002601 rec.reportLowMemory = true;
2602 rec.lastLowMemory = now;
2603 mProcessesToGc.remove(rec);
2604 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 }
2606 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002607 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 }
2609 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002610 } else if (app.pid != pid) {
2611 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002612 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002613 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002614 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002615 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002616 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 + thread.asBinder());
2618 }
2619 }
2620
Dan Egnor42471dd2010-01-07 17:25:22 -08002621 /**
2622 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002623 * @param clearTraces causes the dump file to be erased prior to the new
2624 * traces being written, if true; when false, the new traces will be
2625 * appended to any existing file content.
Dan Egnor42471dd2010-01-07 17:25:22 -08002626 * @param pids of dalvik VM processes to dump stack traces for
2627 * @return file containing stack traces, or null if no dump file is configured
2628 */
Christopher Tate6ee412d2010-05-28 12:01:56 -07002629 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> pids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002630 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2631 if (tracesPath == null || tracesPath.length() == 0) {
2632 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002634
2635 File tracesFile = new File(tracesPath);
2636 try {
2637 File tracesDir = tracesFile.getParentFile();
2638 if (!tracesDir.exists()) tracesFile.mkdirs();
2639 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2640
Christopher Tate6ee412d2010-05-28 12:01:56 -07002641 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002642 tracesFile.createNewFile();
2643 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2644 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002645 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002646 return null;
2647 }
2648
2649 // Use a FileObserver to detect when traces finish writing.
2650 // The order of traces is considered important to maintain for legibility.
2651 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2652 public synchronized void onEvent(int event, String path) { notify(); }
2653 };
2654
2655 try {
2656 observer.startWatching();
2657 int num = pids.size();
2658 for (int i = 0; i < num; i++) {
2659 synchronized (observer) {
2660 Process.sendSignal(pids.get(i), Process.SIGNAL_QUIT);
2661 observer.wait(200); // Wait for write-close, give up after 200msec
2662 }
2663 }
2664 } catch (InterruptedException e) {
Joe Onorato5d3bea62010-03-01 13:44:29 -08002665 Log.wtf(TAG, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002666 } finally {
2667 observer.stopWatching();
2668 }
2669
2670 return tracesFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 }
2672
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002673 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
2674 ActivityRecord parent, final String annotation) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002675 ArrayList<Integer> pids = new ArrayList<Integer>(20);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002676
2677 synchronized (this) {
2678 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
2679 if (mShuttingDown) {
2680 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
2681 return;
2682 } else if (app.notResponding) {
2683 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
2684 return;
2685 } else if (app.crashing) {
2686 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
2687 return;
2688 }
2689
2690 // In case we come through here for the same app before completing
2691 // this one, mark as anring now so we will bail out.
2692 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08002693
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002694 // Log the ANR to the event log.
2695 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
2696 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08002697
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002698 // Dump thread traces as quickly as we can, starting with "interesting" processes.
2699 pids.add(app.pid);
2700
2701 int parentPid = app.pid;
2702 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
2703 if (parentPid != app.pid) pids.add(parentPid);
2704
2705 if (MY_PID != app.pid && MY_PID != parentPid) pids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08002706
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002707 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
2708 ProcessRecord r = mLruProcesses.get(i);
2709 if (r != null && r.thread != null) {
2710 int pid = r.pid;
2711 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) pids.add(pid);
2712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 }
2714 }
2715
Christopher Tate6ee412d2010-05-28 12:01:56 -07002716 File tracesFile = dumpStackTraces(true, pids);
Dan Egnor42471dd2010-01-07 17:25:22 -08002717
2718 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002719 StringBuilder info = mStringBuilder;
2720 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08002721 info.append("ANR in ").append(app.processName);
2722 if (activity != null && activity.shortComponentName != null) {
2723 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07002724 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08002725 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08002727 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002729 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08002730 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732
Dan Egnor42471dd2010-01-07 17:25:22 -08002733 String cpuInfo = null;
2734 if (MONITOR_CPU_USAGE) {
2735 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002736 synchronized (mProcessStatsThread) {
2737 cpuInfo = mProcessStats.printCurrentState();
2738 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002739 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 }
2741
Joe Onorato8a9b2202010-02-26 18:56:32 -08002742 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08002743 if (tracesFile == null) {
2744 // There is no trace file, so dump (only) the alleged culprit's threads to the log
2745 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
2746 }
2747
2748 addErrorToDropBox("anr", app, activity, parent, annotation, cpuInfo, tracesFile, null);
2749
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002750 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08002752 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
2753 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002755 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
2756 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 }
2758 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002759 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 }
2761 }
2762
Dan Egnor42471dd2010-01-07 17:25:22 -08002763 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
2764 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
2765 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07002766
2767 synchronized (this) {
2768 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
2769 Process.killProcess(app.pid);
2770 return;
2771 }
2772
2773 // Set the app's notResponding state, and look up the errorReportReceiver
2774 makeAppNotRespondingLocked(app,
2775 activity != null ? activity.shortComponentName : null,
2776 annotation != null ? "ANR " + annotation : "ANR",
2777 info.toString());
2778
2779 // Bring up the infamous App Not Responding dialog
2780 Message msg = Message.obtain();
2781 HashMap map = new HashMap();
2782 msg.what = SHOW_NOT_RESPONDING_MSG;
2783 msg.obj = map;
2784 map.put("app", app);
2785 if (activity != null) {
2786 map.put("activity", activity);
2787 }
2788
2789 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08002790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 }
2792
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002793 final void decPersistentCountLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 app.persistentActivities--;
2795 if (app.persistentActivities > 0) {
2796 // Still more of 'em...
2797 return;
2798 }
2799 if (app.persistent) {
2800 // Ah, but the application itself is persistent. Whatever!
2801 return;
2802 }
2803
2804 // App is no longer persistent... make sure it and the ones
2805 // following it in the LRU list have the correc oom_adj.
2806 updateOomAdjLocked();
2807 }
2808
2809 public void setPersistent(IBinder token, boolean isPersistent) {
2810 if (checkCallingPermission(android.Manifest.permission.PERSISTENT_ACTIVITY)
2811 != PackageManager.PERMISSION_GRANTED) {
2812 String msg = "Permission Denial: setPersistent() from pid="
2813 + Binder.getCallingPid()
2814 + ", uid=" + Binder.getCallingUid()
2815 + " requires " + android.Manifest.permission.PERSISTENT_ACTIVITY;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002816 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 throw new SecurityException(msg);
2818 }
2819
2820 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002821 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 if (index < 0) {
2823 return;
2824 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002825 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 ProcessRecord app = r.app;
2827
Joe Onorato8a9b2202010-02-26 18:56:32 -08002828 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 TAG, "Setting persistence " + isPersistent + ": " + r);
2830
2831 if (isPersistent) {
2832 if (r.persistent) {
2833 // Okay okay, I heard you already!
Joe Onorato8a9b2202010-02-26 18:56:32 -08002834 if (localLOGV) Slog.v(TAG, "Already persistent!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 return;
2836 }
2837 r.persistent = true;
2838 app.persistentActivities++;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002839 if (localLOGV) Slog.v(TAG, "Num persistent now: " + app.persistentActivities);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 if (app.persistentActivities > 1) {
2841 // We aren't the first...
Joe Onorato8a9b2202010-02-26 18:56:32 -08002842 if (localLOGV) Slog.v(TAG, "Not the first!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 return;
2844 }
2845 if (app.persistent) {
2846 // This would be redundant.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002847 if (localLOGV) Slog.v(TAG, "App is persistent!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 return;
2849 }
2850
2851 // App is now persistent... make sure it and the ones
2852 // following it now have the correct oom_adj.
2853 final long origId = Binder.clearCallingIdentity();
2854 updateOomAdjLocked();
2855 Binder.restoreCallingIdentity(origId);
2856
2857 } else {
2858 if (!r.persistent) {
2859 // Okay okay, I heard you already!
2860 return;
2861 }
2862 r.persistent = false;
2863 final long origId = Binder.clearCallingIdentity();
2864 decPersistentCountLocked(app);
2865 Binder.restoreCallingIdentity(origId);
2866
2867 }
2868 }
2869 }
2870
2871 public boolean clearApplicationUserData(final String packageName,
2872 final IPackageDataObserver observer) {
2873 int uid = Binder.getCallingUid();
2874 int pid = Binder.getCallingPid();
2875 long callingId = Binder.clearCallingIdentity();
2876 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002877 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 int pkgUid = -1;
2879 synchronized(this) {
2880 try {
2881 pkgUid = pm.getPackageUid(packageName);
2882 } catch (RemoteException e) {
2883 }
2884 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002885 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 return false;
2887 }
2888 if (uid == pkgUid || checkComponentPermission(
2889 android.Manifest.permission.CLEAR_APP_USER_DATA,
2890 pid, uid, -1)
2891 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08002892 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 } else {
2894 throw new SecurityException(pid+" does not have permission:"+
2895 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
2896 "for process:"+packageName);
2897 }
2898 }
2899
2900 try {
2901 //clear application user data
2902 pm.clearApplicationUserData(packageName, observer);
2903 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
2904 Uri.fromParts("package", packageName, null));
2905 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Josh Bartel2ecce342010-02-25 10:55:48 -06002906 synchronized (this) {
2907 broadcastIntentLocked(null, null, intent,
2908 null, null, 0, null, null, null,
2909 false, false, MY_PID, Process.SYSTEM_UID);
2910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 } catch (RemoteException e) {
2912 }
2913 } finally {
2914 Binder.restoreCallingIdentity(callingId);
2915 }
2916 return true;
2917 }
2918
Dianne Hackborn03abb812010-01-04 18:43:19 -08002919 public void killBackgroundProcesses(final String packageName) {
2920 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
2921 != PackageManager.PERMISSION_GRANTED &&
2922 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
2923 != PackageManager.PERMISSION_GRANTED) {
2924 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 + Binder.getCallingPid()
2926 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08002927 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002928 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 throw new SecurityException(msg);
2930 }
2931
2932 long callingId = Binder.clearCallingIdentity();
2933 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002934 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 int pkgUid = -1;
2936 synchronized(this) {
2937 try {
2938 pkgUid = pm.getPackageUid(packageName);
2939 } catch (RemoteException e) {
2940 }
2941 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002942 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 return;
2944 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08002945 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002946 SECONDARY_SERVER_ADJ, false, true);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002947 }
2948 } finally {
2949 Binder.restoreCallingIdentity(callingId);
2950 }
2951 }
2952
2953 public void forceStopPackage(final String packageName) {
2954 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2955 != PackageManager.PERMISSION_GRANTED) {
2956 String msg = "Permission Denial: forceStopPackage() from pid="
2957 + Binder.getCallingPid()
2958 + ", uid=" + Binder.getCallingUid()
2959 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002960 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002961 throw new SecurityException(msg);
2962 }
2963
2964 long callingId = Binder.clearCallingIdentity();
2965 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002966 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08002967 int pkgUid = -1;
2968 synchronized(this) {
2969 try {
2970 pkgUid = pm.getPackageUid(packageName);
2971 } catch (RemoteException e) {
2972 }
2973 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002974 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002975 return;
2976 }
2977 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 }
2979 } finally {
2980 Binder.restoreCallingIdentity(callingId);
2981 }
2982 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002983
2984 /*
2985 * The pkg name and uid have to be specified.
2986 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
2987 */
2988 public void killApplicationWithUid(String pkg, int uid) {
2989 if (pkg == null) {
2990 return;
2991 }
2992 // Make sure the uid is valid.
2993 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002994 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002995 return;
2996 }
2997 int callerUid = Binder.getCallingUid();
2998 // Only the system server can kill an application
2999 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003000 // Post an aysnc message to kill the application
3001 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3002 msg.arg1 = uid;
3003 msg.arg2 = 0;
3004 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003005 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003006 } else {
3007 throw new SecurityException(callerUid + " cannot kill pkg: " +
3008 pkg);
3009 }
3010 }
3011
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003012 public void closeSystemDialogs(String reason) {
3013 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
3014 if (reason != null) {
3015 intent.putExtra("reason", reason);
3016 }
3017
3018 final int uid = Binder.getCallingUid();
3019 final long origId = Binder.clearCallingIdentity();
3020 synchronized (this) {
3021 int i = mWatchers.beginBroadcast();
3022 while (i > 0) {
3023 i--;
3024 IActivityWatcher w = mWatchers.getBroadcastItem(i);
3025 if (w != null) {
3026 try {
3027 w.closingSystemDialogs(reason);
3028 } catch (RemoteException e) {
3029 }
3030 }
3031 }
3032 mWatchers.finishBroadcast();
3033
Dianne Hackbornffa42482009-09-23 22:20:11 -07003034 mWindowManager.closeSystemDialogs(reason);
3035
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003036 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3037 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003038 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003039 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003040 Activity.RESULT_CANCELED, null, "close-sys");
3041 }
3042 }
3043
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003044 broadcastIntentLocked(null, null, intent, null,
3045 null, 0, null, null, null, false, false, -1, uid);
3046 }
3047 Binder.restoreCallingIdentity(origId);
3048 }
3049
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003050 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003051 throws RemoteException {
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003052 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3053 for (int i=pids.length-1; i>=0; i--) {
3054 infos[i] = new Debug.MemoryInfo();
3055 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003056 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003057 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003058 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003059
3060 public void killApplicationProcess(String processName, int uid) {
3061 if (processName == null) {
3062 return;
3063 }
3064
3065 int callerUid = Binder.getCallingUid();
3066 // Only the system server can kill an application
3067 if (callerUid == Process.SYSTEM_UID) {
3068 synchronized (this) {
3069 ProcessRecord app = getProcessRecordLocked(processName, uid);
3070 if (app != null) {
3071 try {
3072 app.thread.scheduleSuicide();
3073 } catch (RemoteException e) {
3074 // If the other end already died, then our work here is done.
3075 }
3076 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003077 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003078 + processName + " / " + uid);
3079 }
3080 }
3081 } else {
3082 throw new SecurityException(callerUid + " cannot kill app process: " +
3083 processName);
3084 }
3085 }
3086
Dianne Hackborn03abb812010-01-04 18:43:19 -08003087 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003088 forceStopPackageLocked(packageName, uid, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3090 Uri.fromParts("package", packageName, null));
3091 intent.putExtra(Intent.EXTRA_UID, uid);
3092 broadcastIntentLocked(null, null, intent,
3093 null, null, 0, null, null, null,
3094 false, false, MY_PID, Process.SYSTEM_UID);
3095 }
3096
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003097 private final boolean killPackageProcessesLocked(String packageName, int uid,
3098 int minOomAdj, boolean callerWillRestart, boolean doit) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003099 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100
Dianne Hackborn03abb812010-01-04 18:43:19 -08003101 // Remove all processes this package may have touched: all with the
3102 // same UID (except for the system or root user), and all whose name
3103 // matches the package name.
3104 final String procNamePrefix = packageName + ":";
3105 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3106 final int NA = apps.size();
3107 for (int ia=0; ia<NA; ia++) {
3108 ProcessRecord app = apps.valueAt(ia);
3109 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003110 if (doit) {
3111 procs.add(app);
3112 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003113 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3114 || app.processName.equals(packageName)
3115 || app.processName.startsWith(procNamePrefix)) {
3116 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003117 if (!doit) {
3118 return true;
3119 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003120 app.removed = true;
3121 procs.add(app);
3122 }
3123 }
3124 }
3125 }
3126
3127 int N = procs.size();
3128 for (int i=0; i<N; i++) {
3129 removeProcessLocked(procs.get(i), callerWillRestart);
3130 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003131 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003132 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003133
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003134 private final boolean forceStopPackageLocked(String name, int uid,
3135 boolean callerWillRestart, boolean purgeCache, boolean doit) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 int i, N;
3137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 if (uid < 0) {
3139 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003140 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 } catch (RemoteException e) {
3142 }
3143 }
3144
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003145 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003146 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003147
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003148 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3149 while (badApps.hasNext()) {
3150 SparseArray<Long> ba = badApps.next();
3151 if (ba.get(uid) != null) {
3152 badApps.remove();
3153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 }
3155 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003156
3157 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
3158 callerWillRestart, doit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003160 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
3161 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 if (r.packageName.equals(name)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003163 if (!doit) {
3164 return true;
3165 }
3166 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003167 Slog.i(TAG, " Force finishing activity " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 if (r.app != null) {
3169 r.app.removed = true;
3170 }
3171 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003172 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "uninstall");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 }
3174 }
3175
3176 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3177 for (ServiceRecord service : mServices.values()) {
3178 if (service.packageName.equals(name)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003179 if (!doit) {
3180 return true;
3181 }
3182 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003183 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 if (service.app != null) {
3185 service.app.removed = true;
3186 }
3187 service.app = null;
3188 services.add(service);
3189 }
3190 }
3191
3192 N = services.size();
3193 for (i=0; i<N; i++) {
3194 bringDownServiceLocked(services.get(i), true);
3195 }
3196
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003197 if (doit) {
3198 if (purgeCache) {
3199 AttributeCache ac = AttributeCache.instance();
3200 if (ac != null) {
3201 ac.removePackage(name);
3202 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003203 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003204 mMainStack.resumeTopActivityLocked(null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003205 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003206
3207 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 }
3209
3210 private final boolean removeProcessLocked(ProcessRecord app, boolean callerWillRestart) {
3211 final String name = app.processName;
3212 final int uid = app.info.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003213 if (DEBUG_PROCESSES) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 TAG, "Force removing process " + app + " (" + name
3215 + "/" + uid + ")");
3216
3217 mProcessNames.remove(name, uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003218 if (mHeavyWeightProcess == app) {
3219 mHeavyWeightProcess = null;
3220 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 boolean needRestart = false;
3223 if (app.pid > 0 && app.pid != MY_PID) {
3224 int pid = app.pid;
3225 synchronized (mPidsSelfLocked) {
3226 mPidsSelfLocked.remove(pid);
3227 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3228 }
3229 handleAppDiedLocked(app, true);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003230 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 Process.killProcess(pid);
3232
3233 if (app.persistent) {
3234 if (!callerWillRestart) {
3235 addAppLocked(app.info);
3236 } else {
3237 needRestart = true;
3238 }
3239 }
3240 } else {
3241 mRemovedProcesses.add(app);
3242 }
3243
3244 return needRestart;
3245 }
3246
3247 private final void processStartTimedOutLocked(ProcessRecord app) {
3248 final int pid = app.pid;
3249 boolean gone = false;
3250 synchronized (mPidsSelfLocked) {
3251 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3252 if (knownApp != null && knownApp.thread == null) {
3253 mPidsSelfLocked.remove(pid);
3254 gone = true;
3255 }
3256 }
3257
3258 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003259 Slog.w(TAG, "Process " + app + " failed to attach");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003260 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.info.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003261 app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003263 if (mHeavyWeightProcess == app) {
3264 mHeavyWeightProcess = null;
3265 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3266 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003267 // Take care of any launching providers waiting for this process.
3268 checkAppInLaunchingProvidersLocked(app, true);
3269 // Take care of any services that are waiting for the process.
3270 for (int i=0; i<mPendingServices.size(); i++) {
3271 ServiceRecord sr = mPendingServices.get(i);
3272 if (app.info.uid == sr.appInfo.uid
3273 && app.processName.equals(sr.processName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003274 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003275 mPendingServices.remove(i);
3276 i--;
3277 bringDownServiceLocked(sr, true);
3278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003280 Process.killProcess(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003281 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003282 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003283 try {
3284 IBackupManager bm = IBackupManager.Stub.asInterface(
3285 ServiceManager.getService(Context.BACKUP_SERVICE));
3286 bm.agentDisconnected(app.info.packageName);
3287 } catch (RemoteException e) {
3288 // Can't happen; the backup manager is local
3289 }
3290 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003291 if (mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003292 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003293 mPendingBroadcast = null;
3294 scheduleBroadcastsLocked();
3295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003297 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 }
3299 }
3300
3301 private final boolean attachApplicationLocked(IApplicationThread thread,
3302 int pid) {
3303
3304 // Find the application record that is being attached... either via
3305 // the pid if we are running in multiple processes, or just pull the
3306 // next app record if we are emulating process with anonymous threads.
3307 ProcessRecord app;
3308 if (pid != MY_PID && pid >= 0) {
3309 synchronized (mPidsSelfLocked) {
3310 app = mPidsSelfLocked.get(pid);
3311 }
3312 } else if (mStartingProcesses.size() > 0) {
3313 app = mStartingProcesses.remove(0);
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003314 app.setPid(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 } else {
3316 app = null;
3317 }
3318
3319 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003320 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003322 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 if (pid > 0 && pid != MY_PID) {
3324 Process.killProcess(pid);
3325 } else {
3326 try {
3327 thread.scheduleExit();
3328 } catch (Exception e) {
3329 // Ignore exceptions.
3330 }
3331 }
3332 return false;
3333 }
3334
3335 // If this application record is still attached to a previous
3336 // process, clean it up now.
3337 if (app.thread != null) {
3338 handleAppDiedLocked(app, true);
3339 }
3340
3341 // Tell the process all about itself.
3342
Joe Onorato8a9b2202010-02-26 18:56:32 -08003343 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 TAG, "Binding process pid " + pid + " to record " + app);
3345
3346 String processName = app.processName;
3347 try {
3348 thread.asBinder().linkToDeath(new AppDeathRecipient(
3349 app, pid, thread), 0);
3350 } catch (RemoteException e) {
3351 app.resetPackageList();
3352 startProcessLocked(app, "link fail", processName);
3353 return false;
3354 }
3355
Doug Zongker2bec3d42009-12-04 12:52:44 -08003356 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357
3358 app.thread = thread;
3359 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003360 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3361 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003362 app.forcingToForeground = null;
3363 app.foregroundServices = false;
3364 app.debugging = false;
3365
3366 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3367
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003368 boolean normalMode = mSystemReady || isAllowedWhileBooting(app.info);
3369 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003371 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003372 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003373 }
3374
Joe Onorato8a9b2202010-02-26 18:56:32 -08003375 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 TAG, "New app record " + app
3377 + " thread=" + thread.asBinder() + " pid=" + pid);
3378 try {
3379 int testMode = IApplicationThread.DEBUG_OFF;
3380 if (mDebugApp != null && mDebugApp.equals(processName)) {
3381 testMode = mWaitForDebugger
3382 ? IApplicationThread.DEBUG_WAIT
3383 : IApplicationThread.DEBUG_ON;
3384 app.debugging = true;
3385 if (mDebugTransient) {
3386 mDebugApp = mOrigDebugApp;
3387 mWaitForDebugger = mOrigWaitForDebugger;
3388 }
3389 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003390
Christopher Tate181fafa2009-05-14 11:12:14 -07003391 // If the app is being launched for restore or full backup, set it up specially
3392 boolean isRestrictedBackupMode = false;
3393 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3394 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
3395 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3396 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003397
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003398 ensurePackageDexOpt(app.instrumentationInfo != null
3399 ? app.instrumentationInfo.packageName
3400 : app.info.packageName);
3401 if (app.instrumentationClass != null) {
3402 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003403 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003404 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003405 + processName + " with config " + mConfiguration);
Dianne Hackborn1655be42009-05-08 14:29:01 -07003406 thread.bindApplication(processName, app.instrumentationInfo != null
3407 ? app.instrumentationInfo : app.info, providers,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 app.instrumentationClass, app.instrumentationProfileFile,
3409 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003410 isRestrictedBackupMode || !normalMode,
3411 mConfiguration, getCommonServicesLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003412 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003413 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 } catch (Exception e) {
3415 // todo: Yikes! What should we do? For now we will try to
3416 // start another process, but that could easily get us in
3417 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003418 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419
3420 app.resetPackageList();
3421 startProcessLocked(app, "bind fail", processName);
3422 return false;
3423 }
3424
3425 // Remove this record from the list of starting applications.
3426 mPersistentStartingProcesses.remove(app);
3427 mProcessesOnHold.remove(app);
3428
3429 boolean badApp = false;
3430 boolean didSomething = false;
3431
3432 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003433 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003434 if (hr != null && normalMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
3436 && processName.equals(hr.processName)) {
3437 try {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003438 if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 didSomething = true;
3440 }
3441 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003442 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 + hr.intent.getComponent().flattenToShortString(), e);
3444 badApp = true;
3445 }
3446 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003447 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 }
3449 }
3450
3451 // Find any services that should be running in this process...
3452 if (!badApp && mPendingServices.size() > 0) {
3453 ServiceRecord sr = null;
3454 try {
3455 for (int i=0; i<mPendingServices.size(); i++) {
3456 sr = mPendingServices.get(i);
3457 if (app.info.uid != sr.appInfo.uid
3458 || !processName.equals(sr.processName)) {
3459 continue;
3460 }
3461
3462 mPendingServices.remove(i);
3463 i--;
3464 realStartServiceLocked(sr, app);
3465 didSomething = true;
3466 }
3467 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003468 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 + sr.shortName, e);
3470 badApp = true;
3471 }
3472 }
3473
3474 // Check if the next broadcast receiver is in this process...
3475 BroadcastRecord br = mPendingBroadcast;
3476 if (!badApp && br != null && br.curApp == app) {
3477 try {
3478 mPendingBroadcast = null;
3479 processCurBroadcastLocked(br, app);
3480 didSomething = true;
3481 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003482 Slog.w(TAG, "Exception in new application when starting receiver "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 + br.curComponent.flattenToShortString(), e);
3484 badApp = true;
3485 logBroadcastReceiverDiscard(br);
3486 finishReceiverLocked(br.receiver, br.resultCode, br.resultData,
3487 br.resultExtras, br.resultAbort, true);
3488 scheduleBroadcastsLocked();
Magnus Edlund7bb25812010-02-24 15:45:06 +01003489 // We need to reset the state if we fails to start the receiver.
3490 br.state = BroadcastRecord.IDLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 }
3492 }
3493
Christopher Tate181fafa2009-05-14 11:12:14 -07003494 // Check whether the next backup agent is in this process...
3495 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.info.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003496 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003497 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003498 try {
3499 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, mBackupTarget.backupMode);
3500 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003501 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003502 e.printStackTrace();
3503 }
3504 }
3505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 if (badApp) {
3507 // todo: Also need to kill application to deal with all
3508 // kinds of exceptions.
3509 handleAppDiedLocked(app, false);
3510 return false;
3511 }
3512
3513 if (!didSomething) {
3514 updateOomAdjLocked();
3515 }
3516
3517 return true;
3518 }
3519
3520 public final void attachApplication(IApplicationThread thread) {
3521 synchronized (this) {
3522 int callingPid = Binder.getCallingPid();
3523 final long origId = Binder.clearCallingIdentity();
3524 attachApplicationLocked(thread, callingPid);
3525 Binder.restoreCallingIdentity(origId);
3526 }
3527 }
3528
Dianne Hackborne88846e2009-09-30 21:34:25 -07003529 public final void activityIdle(IBinder token, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003531 mMainStack.activityIdleInternal(token, false, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 Binder.restoreCallingIdentity(origId);
3533 }
3534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003536 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003537 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 mWindowManager.enableScreenAfterBoot();
3539 }
3540
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003541 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003542 IntentFilter pkgFilter = new IntentFilter();
3543 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
3544 pkgFilter.addDataScheme("package");
3545 mContext.registerReceiver(new BroadcastReceiver() {
3546 @Override
3547 public void onReceive(Context context, Intent intent) {
3548 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3549 if (pkgs != null) {
3550 for (String pkg : pkgs) {
3551 if (forceStopPackageLocked(pkg, -1, false, false, false)) {
3552 setResultCode(Activity.RESULT_OK);
3553 return;
3554 }
3555 }
3556 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003557 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003558 }, pkgFilter);
3559
3560 synchronized (this) {
3561 // Ensure that any processes we had put on hold are now started
3562 // up.
3563 final int NP = mProcessesOnHold.size();
3564 if (NP > 0) {
3565 ArrayList<ProcessRecord> procs =
3566 new ArrayList<ProcessRecord>(mProcessesOnHold);
3567 for (int ip=0; ip<NP; ip++) {
3568 this.startProcessLocked(procs.get(ip), "on-hold", null);
3569 }
3570 }
3571
3572 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
3573 // Tell anyone interested that we are done booting!
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003574 broadcastIntentLocked(null, null,
3575 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
3576 null, null, 0, null, null,
3577 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
3578 false, false, MY_PID, Process.SYSTEM_UID);
3579 }
3580 }
3581 }
3582
3583 final void ensureBootCompleted() {
3584 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003585 boolean enableScreen;
3586 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003587 booting = mBooting;
3588 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003589 enableScreen = !mBooted;
3590 mBooted = true;
3591 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003592
3593 if (booting) {
3594 finishBooting();
3595 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003596
3597 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003598 enableScreenAfterBoot();
3599 }
3600 }
3601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 public final void activityPaused(IBinder token, Bundle icicle) {
3603 // Refuse possible leaked file descriptors
3604 if (icicle != null && icicle.hasFileDescriptors()) {
3605 throw new IllegalArgumentException("File descriptors passed in Bundle");
3606 }
3607
3608 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003609 mMainStack.activityPaused(token, icicle, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 Binder.restoreCallingIdentity(origId);
3611 }
3612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 public final void activityStopped(IBinder token, Bitmap thumbnail,
3614 CharSequence description) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003615 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 TAG, "Activity stopped: token=" + token);
3617
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003618 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003619
3620 final long origId = Binder.clearCallingIdentity();
3621
3622 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003623 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003625 r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 r.thumbnail = thumbnail;
3627 r.description = description;
3628 r.stopped = true;
3629 r.state = ActivityState.STOPPED;
3630 if (!r.finishing) {
3631 if (r.configDestroy) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003632 r.stack.destroyActivityLocked(r, true);
3633 r.stack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 }
3635 }
3636 }
3637 }
3638
3639 if (r != null) {
3640 sendPendingThumbnail(r, null, null, null, false);
3641 }
3642
3643 trimApplications();
3644
3645 Binder.restoreCallingIdentity(origId);
3646 }
3647
3648 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003649 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003650 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 }
3652
3653 public String getCallingPackage(IBinder token) {
3654 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003655 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07003656 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 }
3658 }
3659
3660 public ComponentName getCallingActivity(IBinder token) {
3661 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003662 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 return r != null ? r.intent.getComponent() : null;
3664 }
3665 }
3666
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003667 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003668 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003670 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 if (r != null) {
3672 return r.resultTo;
3673 }
3674 }
3675 return null;
3676 }
3677
3678 public ComponentName getActivityClassForToken(IBinder token) {
3679 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003680 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003682 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 return r.intent.getComponent();
3684 }
3685 return null;
3686 }
3687 }
3688
3689 public String getPackageForToken(IBinder token) {
3690 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003691 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003693 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 return r.packageName;
3695 }
3696 return null;
3697 }
3698 }
3699
3700 public IIntentSender getIntentSender(int type,
3701 String packageName, IBinder token, String resultWho,
3702 int requestCode, Intent intent, String resolvedType, int flags) {
3703 // Refuse possible leaked file descriptors
3704 if (intent != null && intent.hasFileDescriptors() == true) {
3705 throw new IllegalArgumentException("File descriptors passed in Intent");
3706 }
3707
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003708 if (type == INTENT_SENDER_BROADCAST) {
3709 if ((intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
3710 throw new IllegalArgumentException(
3711 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
3712 }
3713 }
3714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 synchronized(this) {
3716 int callingUid = Binder.getCallingUid();
3717 try {
3718 if (callingUid != 0 && callingUid != Process.SYSTEM_UID &&
3719 Process.supportsProcesses()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003720 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 .getPackageUid(packageName);
3722 if (uid != Binder.getCallingUid()) {
3723 String msg = "Permission Denial: getIntentSender() from pid="
3724 + Binder.getCallingPid()
3725 + ", uid=" + Binder.getCallingUid()
3726 + ", (need uid=" + uid + ")"
3727 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003728 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 throw new SecurityException(msg);
3730 }
3731 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003732
3733 return getIntentSenderLocked(type, packageName, callingUid,
3734 token, resultWho, requestCode, intent, resolvedType, flags);
3735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 } catch (RemoteException e) {
3737 throw new SecurityException(e);
3738 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003739 }
3740 }
3741
3742 IIntentSender getIntentSenderLocked(int type,
3743 String packageName, int callingUid, IBinder token, String resultWho,
3744 int requestCode, Intent intent, String resolvedType, int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003745 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003746 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003747 int index = mMainStack.indexOfTokenLocked(token);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003748 if (index < 0) {
3749 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003751 activity = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003752 if (activity.finishing) {
3753 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003755 }
3756
3757 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
3758 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
3759 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
3760 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
3761 |PendingIntent.FLAG_UPDATE_CURRENT);
3762
3763 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
3764 type, packageName, activity, resultWho,
3765 requestCode, intent, resolvedType, flags);
3766 WeakReference<PendingIntentRecord> ref;
3767 ref = mIntentSenderRecords.get(key);
3768 PendingIntentRecord rec = ref != null ? ref.get() : null;
3769 if (rec != null) {
3770 if (!cancelCurrent) {
3771 if (updateCurrent) {
3772 rec.key.requestIntent.replaceExtras(intent);
3773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003774 return rec;
3775 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003776 rec.canceled = true;
3777 mIntentSenderRecords.remove(key);
3778 }
3779 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780 return rec;
3781 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07003782 rec = new PendingIntentRecord(this, key, callingUid);
3783 mIntentSenderRecords.put(key, rec.ref);
3784 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
3785 if (activity.pendingResults == null) {
3786 activity.pendingResults
3787 = new HashSet<WeakReference<PendingIntentRecord>>();
3788 }
3789 activity.pendingResults.add(rec.ref);
3790 }
3791 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 }
3793
3794 public void cancelIntentSender(IIntentSender sender) {
3795 if (!(sender instanceof PendingIntentRecord)) {
3796 return;
3797 }
3798 synchronized(this) {
3799 PendingIntentRecord rec = (PendingIntentRecord)sender;
3800 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003801 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 .getPackageUid(rec.key.packageName);
3803 if (uid != Binder.getCallingUid()) {
3804 String msg = "Permission Denial: cancelIntentSender() from pid="
3805 + Binder.getCallingPid()
3806 + ", uid=" + Binder.getCallingUid()
3807 + " is not allowed to cancel packges "
3808 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003809 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 throw new SecurityException(msg);
3811 }
3812 } catch (RemoteException e) {
3813 throw new SecurityException(e);
3814 }
3815 cancelIntentSenderLocked(rec, true);
3816 }
3817 }
3818
3819 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
3820 rec.canceled = true;
3821 mIntentSenderRecords.remove(rec.key);
3822 if (cleanActivity && rec.key.activity != null) {
3823 rec.key.activity.pendingResults.remove(rec.ref);
3824 }
3825 }
3826
3827 public String getPackageForIntentSender(IIntentSender pendingResult) {
3828 if (!(pendingResult instanceof PendingIntentRecord)) {
3829 return null;
3830 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07003831 try {
3832 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
3833 return res.key.packageName;
3834 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 }
3836 return null;
3837 }
3838
3839 public void setProcessLimit(int max) {
3840 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
3841 "setProcessLimit()");
3842 mProcessLimit = max;
3843 }
3844
3845 public int getProcessLimit() {
3846 return mProcessLimit;
3847 }
3848
3849 void foregroundTokenDied(ForegroundToken token) {
3850 synchronized (ActivityManagerService.this) {
3851 synchronized (mPidsSelfLocked) {
3852 ForegroundToken cur
3853 = mForegroundProcesses.get(token.pid);
3854 if (cur != token) {
3855 return;
3856 }
3857 mForegroundProcesses.remove(token.pid);
3858 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
3859 if (pr == null) {
3860 return;
3861 }
3862 pr.forcingToForeground = null;
3863 pr.foregroundServices = false;
3864 }
3865 updateOomAdjLocked();
3866 }
3867 }
3868
3869 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
3870 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
3871 "setProcessForeground()");
3872 synchronized(this) {
3873 boolean changed = false;
3874
3875 synchronized (mPidsSelfLocked) {
3876 ProcessRecord pr = mPidsSelfLocked.get(pid);
3877 if (pr == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003878 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 return;
3880 }
3881 ForegroundToken oldToken = mForegroundProcesses.get(pid);
3882 if (oldToken != null) {
3883 oldToken.token.unlinkToDeath(oldToken, 0);
3884 mForegroundProcesses.remove(pid);
3885 pr.forcingToForeground = null;
3886 changed = true;
3887 }
3888 if (isForeground && token != null) {
3889 ForegroundToken newToken = new ForegroundToken() {
3890 public void binderDied() {
3891 foregroundTokenDied(this);
3892 }
3893 };
3894 newToken.pid = pid;
3895 newToken.token = token;
3896 try {
3897 token.linkToDeath(newToken, 0);
3898 mForegroundProcesses.put(pid, newToken);
3899 pr.forcingToForeground = token;
3900 changed = true;
3901 } catch (RemoteException e) {
3902 // If the process died while doing this, we will later
3903 // do the cleanup with the process death link.
3904 }
3905 }
3906 }
3907
3908 if (changed) {
3909 updateOomAdjLocked();
3910 }
3911 }
3912 }
3913
3914 // =========================================================
3915 // PERMISSIONS
3916 // =========================================================
3917
3918 static class PermissionController extends IPermissionController.Stub {
3919 ActivityManagerService mActivityManagerService;
3920 PermissionController(ActivityManagerService activityManagerService) {
3921 mActivityManagerService = activityManagerService;
3922 }
3923
3924 public boolean checkPermission(String permission, int pid, int uid) {
3925 return mActivityManagerService.checkPermission(permission, pid,
3926 uid) == PackageManager.PERMISSION_GRANTED;
3927 }
3928 }
3929
3930 /**
3931 * This can be called with or without the global lock held.
3932 */
3933 int checkComponentPermission(String permission, int pid, int uid,
3934 int reqUid) {
3935 // We might be performing an operation on behalf of an indirect binder
3936 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
3937 // client identity accordingly before proceeding.
3938 Identity tlsIdentity = sCallerIdentity.get();
3939 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003940 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
3942 uid = tlsIdentity.uid;
3943 pid = tlsIdentity.pid;
3944 }
3945
3946 // Root, system server and our own process get to do everything.
3947 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID ||
3948 !Process.supportsProcesses()) {
3949 return PackageManager.PERMISSION_GRANTED;
3950 }
3951 // If the target requires a specific UID, always fail for others.
3952 if (reqUid >= 0 && uid != reqUid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003953 Slog.w(TAG, "Permission denied: checkComponentPermission() reqUid=" + reqUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 return PackageManager.PERMISSION_DENIED;
3955 }
3956 if (permission == null) {
3957 return PackageManager.PERMISSION_GRANTED;
3958 }
3959 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003960 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 .checkUidPermission(permission, uid);
3962 } catch (RemoteException e) {
3963 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08003964 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965 }
3966 return PackageManager.PERMISSION_DENIED;
3967 }
3968
3969 /**
3970 * As the only public entry point for permissions checking, this method
3971 * can enforce the semantic that requesting a check on a null global
3972 * permission is automatically denied. (Internally a null permission
3973 * string is used when calling {@link #checkComponentPermission} in cases
3974 * when only uid-based security is needed.)
3975 *
3976 * This can be called with or without the global lock held.
3977 */
3978 public int checkPermission(String permission, int pid, int uid) {
3979 if (permission == null) {
3980 return PackageManager.PERMISSION_DENIED;
3981 }
3982 return checkComponentPermission(permission, pid, uid, -1);
3983 }
3984
3985 /**
3986 * Binder IPC calls go through the public entry point.
3987 * This can be called with or without the global lock held.
3988 */
3989 int checkCallingPermission(String permission) {
3990 return checkPermission(permission,
3991 Binder.getCallingPid(),
3992 Binder.getCallingUid());
3993 }
3994
3995 /**
3996 * This can be called with or without the global lock held.
3997 */
3998 void enforceCallingPermission(String permission, String func) {
3999 if (checkCallingPermission(permission)
4000 == PackageManager.PERMISSION_GRANTED) {
4001 return;
4002 }
4003
4004 String msg = "Permission Denial: " + func + " from pid="
4005 + Binder.getCallingPid()
4006 + ", uid=" + Binder.getCallingUid()
4007 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004008 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 throw new SecurityException(msg);
4010 }
4011
4012 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
4013 ProviderInfo pi, int uid, int modeFlags) {
4014 try {
4015 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4016 if ((pi.readPermission != null) &&
4017 (pm.checkUidPermission(pi.readPermission, uid)
4018 != PackageManager.PERMISSION_GRANTED)) {
4019 return false;
4020 }
4021 }
4022 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4023 if ((pi.writePermission != null) &&
4024 (pm.checkUidPermission(pi.writePermission, uid)
4025 != PackageManager.PERMISSION_GRANTED)) {
4026 return false;
4027 }
4028 }
4029 return true;
4030 } catch (RemoteException e) {
4031 return false;
4032 }
4033 }
4034
4035 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4036 int modeFlags) {
4037 // Root gets to do everything.
4038 if (uid == 0 || !Process.supportsProcesses()) {
4039 return true;
4040 }
4041 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4042 if (perms == null) return false;
4043 UriPermission perm = perms.get(uri);
4044 if (perm == null) return false;
4045 return (modeFlags&perm.modeFlags) == modeFlags;
4046 }
4047
4048 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
4049 // Another redirected-binder-call permissions check as in
4050 // {@link checkComponentPermission}.
4051 Identity tlsIdentity = sCallerIdentity.get();
4052 if (tlsIdentity != null) {
4053 uid = tlsIdentity.uid;
4054 pid = tlsIdentity.pid;
4055 }
4056
4057 // Our own process gets to do everything.
4058 if (pid == MY_PID) {
4059 return PackageManager.PERMISSION_GRANTED;
4060 }
4061 synchronized(this) {
4062 return checkUriPermissionLocked(uri, uid, modeFlags)
4063 ? PackageManager.PERMISSION_GRANTED
4064 : PackageManager.PERMISSION_DENIED;
4065 }
4066 }
4067
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004068 void grantUriPermissionLocked(int callingUid,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004069 String targetPkg, Uri uri, int modeFlags, ActivityRecord activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4071 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4072 if (modeFlags == 0) {
4073 return;
4074 }
4075
Joe Onorato8a9b2202010-02-26 18:56:32 -08004076 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004077 "Requested grant " + targetPkg + " permission to " + uri);
4078
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004079 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080
4081 // If this is not a content: uri, we can't do anything with it.
4082 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004083 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004084 "Can't grant URI permission for non-content URI: " + uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 return;
4086 }
4087
4088 String name = uri.getAuthority();
4089 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004090 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 if (cpr != null) {
4092 pi = cpr.info;
4093 } else {
4094 try {
4095 pi = pm.resolveContentProvider(name,
4096 PackageManager.GET_URI_PERMISSION_PATTERNS);
4097 } catch (RemoteException ex) {
4098 }
4099 }
4100 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004101 Slog.w(TAG, "No content provider found for: " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 return;
4103 }
4104
4105 int targetUid;
4106 try {
4107 targetUid = pm.getPackageUid(targetPkg);
4108 if (targetUid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004109 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004110 "Can't grant URI permission no uid for: " + targetPkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 return;
4112 }
4113 } catch (RemoteException ex) {
4114 return;
4115 }
4116
4117 // First... does the target actually need this permission?
4118 if (checkHoldingPermissionsLocked(pm, pi, targetUid, modeFlags)) {
4119 // No need to grant the target this permission.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004120 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004121 "Target " + targetPkg + " already has full permission to " + uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 return;
4123 }
4124
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004125 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 if (!pi.grantUriPermissions) {
4127 throw new SecurityException("Provider " + pi.packageName
4128 + "/" + pi.name
4129 + " does not allow granting of Uri permissions (uri "
4130 + uri + ")");
4131 }
4132 if (pi.uriPermissionPatterns != null) {
4133 final int N = pi.uriPermissionPatterns.length;
4134 boolean allowed = false;
4135 for (int i=0; i<N; i++) {
4136 if (pi.uriPermissionPatterns[i] != null
4137 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4138 allowed = true;
4139 break;
4140 }
4141 }
4142 if (!allowed) {
4143 throw new SecurityException("Provider " + pi.packageName
4144 + "/" + pi.name
4145 + " does not allow granting of permission to path of Uri "
4146 + uri);
4147 }
4148 }
4149
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004150 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 // this uri?
4152 if (!checkHoldingPermissionsLocked(pm, pi, callingUid, modeFlags)) {
4153 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4154 throw new SecurityException("Uid " + callingUid
4155 + " does not have permission to uri " + uri);
4156 }
4157 }
4158
4159 // Okay! So here we are: the caller has the assumed permission
4160 // to the uri, and the target doesn't. Let's now give this to
4161 // the target.
4162
Joe Onorato8a9b2202010-02-26 18:56:32 -08004163 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004164 "Granting " + targetPkg + " permission to " + uri);
4165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 HashMap<Uri, UriPermission> targetUris
4167 = mGrantedUriPermissions.get(targetUid);
4168 if (targetUris == null) {
4169 targetUris = new HashMap<Uri, UriPermission>();
4170 mGrantedUriPermissions.put(targetUid, targetUris);
4171 }
4172
4173 UriPermission perm = targetUris.get(uri);
4174 if (perm == null) {
4175 perm = new UriPermission(targetUid, uri);
4176 targetUris.put(uri, perm);
4177
4178 }
4179 perm.modeFlags |= modeFlags;
4180 if (activity == null) {
4181 perm.globalModeFlags |= modeFlags;
4182 } else if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4183 perm.readActivities.add(activity);
4184 if (activity.readUriPermissions == null) {
4185 activity.readUriPermissions = new HashSet<UriPermission>();
4186 }
4187 activity.readUriPermissions.add(perm);
4188 } else if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4189 perm.writeActivities.add(activity);
4190 if (activity.writeUriPermissions == null) {
4191 activity.writeUriPermissions = new HashSet<UriPermission>();
4192 }
4193 activity.writeUriPermissions.add(perm);
4194 }
4195 }
4196
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004197 void grantUriPermissionFromIntentLocked(int callingUid,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004198 String targetPkg, Intent intent, ActivityRecord activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 if (intent == null) {
4200 return;
4201 }
4202 Uri data = intent.getData();
4203 if (data == null) {
4204 return;
4205 }
4206 grantUriPermissionLocked(callingUid, targetPkg, data,
4207 intent.getFlags(), activity);
4208 }
4209
4210 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4211 Uri uri, int modeFlags) {
4212 synchronized(this) {
4213 final ProcessRecord r = getRecordForAppLocked(caller);
4214 if (r == null) {
4215 throw new SecurityException("Unable to find app for caller "
4216 + caller
4217 + " when granting permission to uri " + uri);
4218 }
4219 if (targetPkg == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004220 Slog.w(TAG, "grantUriPermission: null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 return;
4222 }
4223 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004224 Slog.w(TAG, "grantUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 return;
4226 }
4227
4228 grantUriPermissionLocked(r.info.uid, targetPkg, uri, modeFlags,
4229 null);
4230 }
4231 }
4232
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004233 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4235 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4236 HashMap<Uri, UriPermission> perms
4237 = mGrantedUriPermissions.get(perm.uid);
4238 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004239 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004240 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 perms.remove(perm.uri);
4242 if (perms.size() == 0) {
4243 mGrantedUriPermissions.remove(perm.uid);
4244 }
4245 }
4246 }
4247 }
4248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 private void revokeUriPermissionLocked(int callingUid, Uri uri,
4250 int modeFlags) {
4251 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4252 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4253 if (modeFlags == 0) {
4254 return;
4255 }
4256
Joe Onorato8a9b2202010-02-26 18:56:32 -08004257 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004258 "Revoking all granted permissions to " + uri);
4259
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004260 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261
4262 final String authority = uri.getAuthority();
4263 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004264 ContentProviderRecord cpr = mProvidersByName.get(authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004265 if (cpr != null) {
4266 pi = cpr.info;
4267 } else {
4268 try {
4269 pi = pm.resolveContentProvider(authority,
4270 PackageManager.GET_URI_PERMISSION_PATTERNS);
4271 } catch (RemoteException ex) {
4272 }
4273 }
4274 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004275 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 return;
4277 }
4278
4279 // Does the caller have this permission on the URI?
4280 if (!checkHoldingPermissionsLocked(pm, pi, callingUid, modeFlags)) {
4281 // Right now, if you are not the original owner of the permission,
4282 // you are not allowed to revoke it.
4283 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4284 throw new SecurityException("Uid " + callingUid
4285 + " does not have permission to uri " + uri);
4286 //}
4287 }
4288
4289 // Go through all of the permissions and remove any that match.
4290 final List<String> SEGMENTS = uri.getPathSegments();
4291 if (SEGMENTS != null) {
4292 final int NS = SEGMENTS.size();
4293 int N = mGrantedUriPermissions.size();
4294 for (int i=0; i<N; i++) {
4295 HashMap<Uri, UriPermission> perms
4296 = mGrantedUriPermissions.valueAt(i);
4297 Iterator<UriPermission> it = perms.values().iterator();
4298 toploop:
4299 while (it.hasNext()) {
4300 UriPermission perm = it.next();
4301 Uri targetUri = perm.uri;
4302 if (!authority.equals(targetUri.getAuthority())) {
4303 continue;
4304 }
4305 List<String> targetSegments = targetUri.getPathSegments();
4306 if (targetSegments == null) {
4307 continue;
4308 }
4309 if (targetSegments.size() < NS) {
4310 continue;
4311 }
4312 for (int j=0; j<NS; j++) {
4313 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
4314 continue toploop;
4315 }
4316 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004317 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004318 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 perm.clearModes(modeFlags);
4320 if (perm.modeFlags == 0) {
4321 it.remove();
4322 }
4323 }
4324 if (perms.size() == 0) {
4325 mGrantedUriPermissions.remove(
4326 mGrantedUriPermissions.keyAt(i));
4327 N--;
4328 i--;
4329 }
4330 }
4331 }
4332 }
4333
4334 public void revokeUriPermission(IApplicationThread caller, Uri uri,
4335 int modeFlags) {
4336 synchronized(this) {
4337 final ProcessRecord r = getRecordForAppLocked(caller);
4338 if (r == null) {
4339 throw new SecurityException("Unable to find app for caller "
4340 + caller
4341 + " when revoking permission to uri " + uri);
4342 }
4343 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004344 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 return;
4346 }
4347
4348 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4349 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4350 if (modeFlags == 0) {
4351 return;
4352 }
4353
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004354 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004355
4356 final String authority = uri.getAuthority();
4357 ProviderInfo pi = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004358 ContentProviderRecord cpr = mProvidersByName.get(authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 if (cpr != null) {
4360 pi = cpr.info;
4361 } else {
4362 try {
4363 pi = pm.resolveContentProvider(authority,
4364 PackageManager.GET_URI_PERMISSION_PATTERNS);
4365 } catch (RemoteException ex) {
4366 }
4367 }
4368 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004369 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004370 return;
4371 }
4372
4373 revokeUriPermissionLocked(r.info.uid, uri, modeFlags);
4374 }
4375 }
4376
4377 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
4378 synchronized (this) {
4379 ProcessRecord app =
4380 who != null ? getRecordForAppLocked(who) : null;
4381 if (app == null) return;
4382
4383 Message msg = Message.obtain();
4384 msg.what = WAIT_FOR_DEBUGGER_MSG;
4385 msg.obj = app;
4386 msg.arg1 = waiting ? 1 : 0;
4387 mHandler.sendMessage(msg);
4388 }
4389 }
4390
4391 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
4392 outInfo.availMem = Process.getFreeMemory();
The Android Open Source Project4df24232009-03-05 14:34:35 -08004393 outInfo.threshold = HOME_APP_MEM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 outInfo.lowMemory = outInfo.availMem <
The Android Open Source Project4df24232009-03-05 14:34:35 -08004395 (HOME_APP_MEM + ((HIDDEN_APP_MEM-HOME_APP_MEM)/2));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396 }
4397
4398 // =========================================================
4399 // TASK MANAGEMENT
4400 // =========================================================
4401
4402 public List getTasks(int maxNum, int flags,
4403 IThumbnailReceiver receiver) {
4404 ArrayList list = new ArrayList();
4405
4406 PendingThumbnailsRecord pending = null;
4407 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004408 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409
4410 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004411 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
4413 + ", receiver=" + receiver);
4414
4415 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
4416 != PackageManager.PERMISSION_GRANTED) {
4417 if (receiver != null) {
4418 // If the caller wants to wait for pending thumbnails,
4419 // it ain't gonna get them.
4420 try {
4421 receiver.finished();
4422 } catch (RemoteException ex) {
4423 }
4424 }
4425 String msg = "Permission Denial: getTasks() from pid="
4426 + Binder.getCallingPid()
4427 + ", uid=" + Binder.getCallingUid()
4428 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004429 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004430 throw new SecurityException(msg);
4431 }
4432
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004433 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004434 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004435 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004436 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004437 CharSequence topDescription = null;
4438 TaskRecord curTask = null;
4439 int numActivities = 0;
4440 int numRunning = 0;
4441 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004442 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004443 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004444 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445
4446 // Initialize state for next task if needed.
4447 if (top == null ||
4448 (top.state == ActivityState.INITIALIZING
4449 && top.task == r.task)) {
4450 top = r;
4451 topDescription = r.description;
4452 curTask = r.task;
4453 numActivities = numRunning = 0;
4454 }
4455
4456 // Add 'r' into the current task.
4457 numActivities++;
4458 if (r.app != null && r.app.thread != null) {
4459 numRunning++;
4460 }
4461 if (topDescription == null) {
4462 topDescription = r.description;
4463 }
4464
Joe Onorato8a9b2202010-02-26 18:56:32 -08004465 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 TAG, r.intent.getComponent().flattenToShortString()
4467 + ": task=" + r.task);
4468
4469 // If the next one is a different task, generate a new
4470 // TaskInfo entry for what we have.
4471 if (next == null || next.task != curTask) {
4472 ActivityManager.RunningTaskInfo ci
4473 = new ActivityManager.RunningTaskInfo();
4474 ci.id = curTask.taskId;
4475 ci.baseActivity = r.intent.getComponent();
4476 ci.topActivity = top.intent.getComponent();
4477 ci.thumbnail = top.thumbnail;
4478 ci.description = topDescription;
4479 ci.numActivities = numActivities;
4480 ci.numRunning = numRunning;
4481 //System.out.println(
4482 // "#" + maxNum + ": " + " descr=" + ci.description);
4483 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004484 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 TAG, "State=" + top.state + "Idle=" + top.idle
4486 + " app=" + top.app
4487 + " thr=" + (top.app != null ? top.app.thread : null));
4488 if (top.state == ActivityState.RESUMED
4489 || top.state == ActivityState.PAUSING) {
4490 if (top.idle && top.app != null
4491 && top.app.thread != null) {
4492 topRecord = top;
4493 topThumbnail = top.app.thread;
4494 } else {
4495 top.thumbnailNeeded = true;
4496 }
4497 }
4498 if (pending == null) {
4499 pending = new PendingThumbnailsRecord(receiver);
4500 }
4501 pending.pendingRecords.add(top);
4502 }
4503 list.add(ci);
4504 maxNum--;
4505 top = null;
4506 }
4507 }
4508
4509 if (pending != null) {
4510 mPendingThumbnails.add(pending);
4511 }
4512 }
4513
Joe Onorato8a9b2202010-02-26 18:56:32 -08004514 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004515
4516 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004517 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004518 try {
4519 topThumbnail.requestThumbnail(topRecord);
4520 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004521 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004522 sendPendingThumbnail(null, topRecord, null, null, true);
4523 }
4524 }
4525
4526 if (pending == null && receiver != null) {
4527 // In this case all thumbnails were available and the client
4528 // is being asked to be told when the remaining ones come in...
4529 // which is unusually, since the top-most currently running
4530 // activity should never have a canned thumbnail! Oh well.
4531 try {
4532 receiver.finished();
4533 } catch (RemoteException ex) {
4534 }
4535 }
4536
4537 return list;
4538 }
4539
4540 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
4541 int flags) {
4542 synchronized (this) {
4543 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
4544 "getRecentTasks()");
4545
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004546 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07004547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004548 final int N = mRecentTasks.size();
4549 ArrayList<ActivityManager.RecentTaskInfo> res
4550 = new ArrayList<ActivityManager.RecentTaskInfo>(
4551 maxNum < N ? maxNum : N);
4552 for (int i=0; i<N && maxNum > 0; i++) {
4553 TaskRecord tr = mRecentTasks.get(i);
4554 if (((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
4555 || (tr.intent == null)
4556 || ((tr.intent.getFlags()
4557 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
4558 ActivityManager.RecentTaskInfo rti
4559 = new ActivityManager.RecentTaskInfo();
4560 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
4561 rti.baseIntent = new Intent(
4562 tr.intent != null ? tr.intent : tr.affinityIntent);
4563 rti.origActivity = tr.origActivity;
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07004564
4565 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
4566 // Check whether this activity is currently available.
4567 try {
4568 if (rti.origActivity != null) {
4569 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
4570 continue;
4571 }
4572 } else if (rti.baseIntent != null) {
4573 if (pm.queryIntentActivities(rti.baseIntent,
4574 null, 0) == null) {
4575 continue;
4576 }
4577 }
4578 } catch (RemoteException e) {
4579 // Will never happen.
4580 }
4581 }
4582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 res.add(rti);
4584 maxNum--;
4585 }
4586 }
4587 return res;
4588 }
4589 }
4590
4591 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
4592 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004593 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 TaskRecord jt = startTask;
4595
4596 // First look backwards
4597 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004598 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 if (r.task != jt) {
4600 jt = r.task;
4601 if (affinity.equals(jt.affinity)) {
4602 return j;
4603 }
4604 }
4605 }
4606
4607 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004608 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 jt = startTask;
4610 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004611 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 if (r.task != jt) {
4613 if (affinity.equals(jt.affinity)) {
4614 return j;
4615 }
4616 jt = r.task;
4617 }
4618 }
4619
4620 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004621 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 return N-1;
4623 }
4624
4625 return -1;
4626 }
4627
4628 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004629 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630 */
4631 public void moveTaskToFront(int task) {
4632 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
4633 "moveTaskToFront()");
4634
4635 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004636 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
4637 Binder.getCallingUid(), "Task to front")) {
4638 return;
4639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004640 final long origId = Binder.clearCallingIdentity();
4641 try {
4642 int N = mRecentTasks.size();
4643 for (int i=0; i<N; i++) {
4644 TaskRecord tr = mRecentTasks.get(i);
4645 if (tr.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004646 mMainStack.moveTaskToFrontLocked(tr, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647 return;
4648 }
4649 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004650 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
4651 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004652 if (hr.task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004653 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 return;
4655 }
4656 }
4657 } finally {
4658 Binder.restoreCallingIdentity(origId);
4659 }
4660 }
4661 }
4662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004663 public void moveTaskToBack(int task) {
4664 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
4665 "moveTaskToBack()");
4666
4667 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004668 if (mMainStack.mResumedActivity != null
4669 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004670 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
4671 Binder.getCallingUid(), "Task to back")) {
4672 return;
4673 }
4674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004676 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 Binder.restoreCallingIdentity(origId);
4678 }
4679 }
4680
4681 /**
4682 * Moves an activity, and all of the other activities within the same task, to the bottom
4683 * of the history stack. The activity's order within the task is unchanged.
4684 *
4685 * @param token A reference to the activity we wish to move
4686 * @param nonRoot If false then this only works if the activity is the root
4687 * of a task; if true it will work for any activity in a task.
4688 * @return Returns true if the move completed, false if not.
4689 */
4690 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
4691 synchronized(this) {
4692 final long origId = Binder.clearCallingIdentity();
4693 int taskId = getTaskForActivityLocked(token, !nonRoot);
4694 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004695 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004696 }
4697 Binder.restoreCallingIdentity(origId);
4698 }
4699 return false;
4700 }
4701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004702 public void moveTaskBackwards(int task) {
4703 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
4704 "moveTaskBackwards()");
4705
4706 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004707 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
4708 Binder.getCallingUid(), "Task backwards")) {
4709 return;
4710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004711 final long origId = Binder.clearCallingIdentity();
4712 moveTaskBackwardsLocked(task);
4713 Binder.restoreCallingIdentity(origId);
4714 }
4715 }
4716
4717 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004718 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004719 }
4720
4721 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
4722 synchronized(this) {
4723 return getTaskForActivityLocked(token, onlyRoot);
4724 }
4725 }
4726
4727 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004728 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 TaskRecord lastTask = null;
4730 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004731 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004732 if (r == token) {
4733 if (!onlyRoot || lastTask != r.task) {
4734 return r.task.taskId;
4735 }
4736 return -1;
4737 }
4738 lastTask = r.task;
4739 }
4740
4741 return -1;
4742 }
4743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004744 public void finishOtherInstances(IBinder token, ComponentName className) {
4745 synchronized(this) {
4746 final long origId = Binder.clearCallingIdentity();
4747
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004748 int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004749 TaskRecord lastTask = null;
4750 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004751 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004752 if (r.realActivity.equals(className)
4753 && r != token && lastTask != r.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004754 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004755 null, "others")) {
4756 i--;
4757 N--;
4758 }
4759 }
4760 lastTask = r.task;
4761 }
4762
4763 Binder.restoreCallingIdentity(origId);
4764 }
4765 }
4766
4767 // =========================================================
4768 // THUMBNAILS
4769 // =========================================================
4770
4771 public void reportThumbnail(IBinder token,
4772 Bitmap thumbnail, CharSequence description) {
4773 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
4774 final long origId = Binder.clearCallingIdentity();
4775 sendPendingThumbnail(null, token, thumbnail, description, true);
4776 Binder.restoreCallingIdentity(origId);
4777 }
4778
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004779 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004780 Bitmap thumbnail, CharSequence description, boolean always) {
4781 TaskRecord task = null;
4782 ArrayList receivers = null;
4783
4784 //System.out.println("Send pending thumbnail: " + r);
4785
4786 synchronized(this) {
4787 if (r == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004788 int index = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004789 if (index < 0) {
4790 return;
4791 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004792 r = (ActivityRecord)mMainStack.mHistory.get(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004793 }
4794 if (thumbnail == null) {
4795 thumbnail = r.thumbnail;
4796 description = r.description;
4797 }
4798 if (thumbnail == null && !always) {
4799 // If there is no thumbnail, and this entry is not actually
4800 // going away, then abort for now and pick up the next
4801 // thumbnail we get.
4802 return;
4803 }
4804 task = r.task;
4805
4806 int N = mPendingThumbnails.size();
4807 int i=0;
4808 while (i<N) {
4809 PendingThumbnailsRecord pr =
4810 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
4811 //System.out.println("Looking in " + pr.pendingRecords);
4812 if (pr.pendingRecords.remove(r)) {
4813 if (receivers == null) {
4814 receivers = new ArrayList();
4815 }
4816 receivers.add(pr);
4817 if (pr.pendingRecords.size() == 0) {
4818 pr.finished = true;
4819 mPendingThumbnails.remove(i);
4820 N--;
4821 continue;
4822 }
4823 }
4824 i++;
4825 }
4826 }
4827
4828 if (receivers != null) {
4829 final int N = receivers.size();
4830 for (int i=0; i<N; i++) {
4831 try {
4832 PendingThumbnailsRecord pr =
4833 (PendingThumbnailsRecord)receivers.get(i);
4834 pr.receiver.newThumbnail(
4835 task != null ? task.taskId : -1, thumbnail, description);
4836 if (pr.finished) {
4837 pr.receiver.finished();
4838 }
4839 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004840 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004841 }
4842 }
4843 }
4844 }
4845
4846 // =========================================================
4847 // CONTENT PROVIDERS
4848 // =========================================================
4849
4850 private final List generateApplicationProvidersLocked(ProcessRecord app) {
4851 List providers = null;
4852 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004853 providers = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004854 queryContentProviders(app.processName, app.info.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07004855 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004856 } catch (RemoteException ex) {
4857 }
4858 if (providers != null) {
4859 final int N = providers.size();
4860 for (int i=0; i<N; i++) {
4861 ProviderInfo cpi =
4862 (ProviderInfo)providers.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004863 ContentProviderRecord cpr = mProvidersByClass.get(cpi.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004864 if (cpr == null) {
4865 cpr = new ContentProviderRecord(cpi, app.info);
4866 mProvidersByClass.put(cpi.name, cpr);
4867 }
4868 app.pubProviders.put(cpi.name, cpr);
4869 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004870 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004871 }
4872 }
4873 return providers;
4874 }
4875
4876 private final String checkContentProviderPermissionLocked(
4877 ProviderInfo cpi, ProcessRecord r, int mode) {
4878 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
4879 final int callingUid = (r != null) ? r.info.uid : Binder.getCallingUid();
4880 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
4881 cpi.exported ? -1 : cpi.applicationInfo.uid)
4882 == PackageManager.PERMISSION_GRANTED
4883 && mode == ParcelFileDescriptor.MODE_READ_ONLY || mode == -1) {
4884 return null;
4885 }
4886 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
4887 cpi.exported ? -1 : cpi.applicationInfo.uid)
4888 == PackageManager.PERMISSION_GRANTED) {
4889 return null;
4890 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07004891
4892 PathPermission[] pps = cpi.pathPermissions;
4893 if (pps != null) {
4894 int i = pps.length;
4895 while (i > 0) {
4896 i--;
4897 PathPermission pp = pps[i];
4898 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
4899 cpi.exported ? -1 : cpi.applicationInfo.uid)
4900 == PackageManager.PERMISSION_GRANTED
4901 && mode == ParcelFileDescriptor.MODE_READ_ONLY || mode == -1) {
4902 return null;
4903 }
4904 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
4905 cpi.exported ? -1 : cpi.applicationInfo.uid)
4906 == PackageManager.PERMISSION_GRANTED) {
4907 return null;
4908 }
4909 }
4910 }
4911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004912 String msg = "Permission Denial: opening provider " + cpi.name
4913 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
4914 + ", uid=" + callingUid + ") requires "
4915 + cpi.readPermission + " or " + cpi.writePermission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004916 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004917 return msg;
4918 }
4919
4920 private final ContentProviderHolder getContentProviderImpl(
4921 IApplicationThread caller, String name) {
4922 ContentProviderRecord cpr;
4923 ProviderInfo cpi = null;
4924
4925 synchronized(this) {
4926 ProcessRecord r = null;
4927 if (caller != null) {
4928 r = getRecordForAppLocked(caller);
4929 if (r == null) {
4930 throw new SecurityException(
4931 "Unable to find app for caller " + caller
4932 + " (pid=" + Binder.getCallingPid()
4933 + ") when getting content provider " + name);
4934 }
4935 }
4936
4937 // First check if this content provider has been published...
Dianne Hackborn860755f2010-06-03 18:47:52 -07004938 cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 if (cpr != null) {
4940 cpi = cpr.info;
4941 if (checkContentProviderPermissionLocked(cpi, r, -1) != null) {
4942 return new ContentProviderHolder(cpi,
4943 cpi.readPermission != null
4944 ? cpi.readPermission : cpi.writePermission);
4945 }
4946
4947 if (r != null && cpr.canRunHere(r)) {
4948 // This provider has been published or is in the process
4949 // of being published... but it is also allowed to run
4950 // in the caller's process, so don't make a connection
4951 // and just let the caller instantiate its own instance.
4952 if (cpr.provider != null) {
4953 // don't give caller the provider object, it needs
4954 // to make its own.
4955 cpr = new ContentProviderRecord(cpr);
4956 }
4957 return cpr;
4958 }
4959
4960 final long origId = Binder.clearCallingIdentity();
4961
Dianne Hackborna1e989b2009-09-01 19:54:29 -07004962 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963 // return it right away.
4964 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004965 if (DEBUG_PROVIDER) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07004966 "Adding provider requested by "
4967 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004968 + cpr.info.processName);
4969 Integer cnt = r.conProviders.get(cpr);
4970 if (cnt == null) {
4971 r.conProviders.put(cpr, new Integer(1));
4972 } else {
4973 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
4974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004975 cpr.clients.add(r);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004976 if (cpr.app != null && r.setAdj <= PERCEPTIBLE_APP_ADJ) {
4977 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07004978 // make sure to count it as being accessed and thus
4979 // back up on the LRU list. This is good because
4980 // content providers are often expensive to start.
4981 updateLruProcessLocked(cpr.app, false, true);
4982 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07004983 } else {
4984 cpr.externals++;
4985 }
4986
4987 if (cpr.app != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004988 updateOomAdjLocked(cpr.app);
4989 }
4990
4991 Binder.restoreCallingIdentity(origId);
4992
4993 } else {
4994 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004995 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07004996 resolveContentProvider(name,
4997 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998 } catch (RemoteException ex) {
4999 }
5000 if (cpi == null) {
5001 return null;
5002 }
5003
5004 if (checkContentProviderPermissionLocked(cpi, r, -1) != null) {
5005 return new ContentProviderHolder(cpi,
5006 cpi.readPermission != null
5007 ? cpi.readPermission : cpi.writePermission);
5008 }
5009
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005010 if (!mSystemReady && !mDidUpdate && !mWaitingUpdate
5011 && !cpi.processName.equals("system")) {
5012 // If this content provider does not run in the system
5013 // process, and the system is not yet ready to run other
5014 // processes, then fail fast instead of hanging.
5015 throw new IllegalArgumentException(
5016 "Attempt to launch content provider before system ready");
5017 }
5018
Dianne Hackborn860755f2010-06-03 18:47:52 -07005019 cpr = mProvidersByClass.get(cpi.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005020 final boolean firstClass = cpr == null;
5021 if (firstClass) {
5022 try {
5023 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005024 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005025 getApplicationInfo(
5026 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005027 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005028 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005029 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005030 + cpi.name);
5031 return null;
5032 }
5033 cpr = new ContentProviderRecord(cpi, ai);
5034 } catch (RemoteException ex) {
5035 // pm is in same process, this will never happen.
5036 }
5037 }
5038
5039 if (r != null && cpr.canRunHere(r)) {
5040 // If this is a multiprocess provider, then just return its
5041 // info and allow the caller to instantiate it. Only do
5042 // this if the provider is the same user as the caller's
5043 // process, or can run as root (so can be in any process).
5044 return cpr;
5045 }
5046
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005047 if (DEBUG_PROVIDER) {
5048 RuntimeException e = new RuntimeException("here");
Joe Onorato8a9b2202010-02-26 18:56:32 -08005049 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.info.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005050 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005051 }
5052
5053 // This is single process, and our app is now connecting to it.
5054 // See if we are already in the process of launching this
5055 // provider.
5056 final int N = mLaunchingProviders.size();
5057 int i;
5058 for (i=0; i<N; i++) {
5059 if (mLaunchingProviders.get(i) == cpr) {
5060 break;
5061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 }
5063
5064 // If the provider is not already being launched, then get it
5065 // started.
5066 if (i >= N) {
5067 final long origId = Binder.clearCallingIdentity();
5068 ProcessRecord proc = startProcessLocked(cpi.processName,
5069 cpr.appInfo, false, 0, "content provider",
5070 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005071 cpi.name), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005073 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 + cpi.applicationInfo.packageName + "/"
5075 + cpi.applicationInfo.uid + " for provider "
5076 + name + ": process is bad");
5077 return null;
5078 }
5079 cpr.launchingApp = proc;
5080 mLaunchingProviders.add(cpr);
5081 Binder.restoreCallingIdentity(origId);
5082 }
5083
5084 // Make sure the provider is published (the same provider class
5085 // may be published under multiple names).
5086 if (firstClass) {
5087 mProvidersByClass.put(cpi.name, cpr);
5088 }
5089 mProvidersByName.put(name, cpr);
5090
5091 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005092 if (DEBUG_PROVIDER) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005093 "Adding provider requested by "
5094 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005095 + cpr.info.processName);
5096 Integer cnt = r.conProviders.get(cpr);
5097 if (cnt == null) {
5098 r.conProviders.put(cpr, new Integer(1));
5099 } else {
5100 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005102 cpr.clients.add(r);
5103 } else {
5104 cpr.externals++;
5105 }
5106 }
5107 }
5108
5109 // Wait for the provider to be published...
5110 synchronized (cpr) {
5111 while (cpr.provider == null) {
5112 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005113 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005114 + cpi.applicationInfo.packageName + "/"
5115 + cpi.applicationInfo.uid + " for provider "
5116 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08005117 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118 cpi.applicationInfo.packageName,
5119 cpi.applicationInfo.uid, name);
5120 return null;
5121 }
5122 try {
5123 cpr.wait();
5124 } catch (InterruptedException ex) {
5125 }
5126 }
5127 }
5128 return cpr;
5129 }
5130
5131 public final ContentProviderHolder getContentProvider(
5132 IApplicationThread caller, String name) {
5133 if (caller == null) {
5134 String msg = "null IApplicationThread when getting content provider "
5135 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005136 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 throw new SecurityException(msg);
5138 }
5139
5140 return getContentProviderImpl(caller, name);
5141 }
5142
5143 private ContentProviderHolder getContentProviderExternal(String name) {
5144 return getContentProviderImpl(null, name);
5145 }
5146
5147 /**
5148 * Drop a content provider from a ProcessRecord's bookkeeping
5149 * @param cpr
5150 */
5151 public void removeContentProvider(IApplicationThread caller, String name) {
5152 synchronized (this) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005153 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005154 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005155 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08005156 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005157 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005158 return;
5159 }
5160 final ProcessRecord r = getRecordForAppLocked(caller);
5161 if (r == null) {
5162 throw new SecurityException(
5163 "Unable to find app for caller " + caller +
5164 " when removing content provider " + name);
5165 }
5166 //update content provider record entry info
Dianne Hackborn860755f2010-06-03 18:47:52 -07005167 ContentProviderRecord localCpr = mProvidersByClass.get(cpr.info.name);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005168 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005169 + r.info.processName + " from process "
5170 + localCpr.appInfo.processName);
5171 if (localCpr.app == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005172 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08005173 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005174 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005175 return;
5176 } else {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07005177 Integer cnt = r.conProviders.get(localCpr);
5178 if (cnt == null || cnt.intValue() <= 1) {
5179 localCpr.clients.remove(r);
5180 r.conProviders.remove(localCpr);
5181 } else {
5182 r.conProviders.put(localCpr, new Integer(cnt.intValue()-1));
5183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005184 }
5185 updateOomAdjLocked();
5186 }
5187 }
5188
5189 private void removeContentProviderExternal(String name) {
5190 synchronized (this) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07005191 ContentProviderRecord cpr = mProvidersByName.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005192 if(cpr == null) {
5193 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08005194 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005195 return;
5196 }
5197
5198 //update content provider record entry info
Dianne Hackborn860755f2010-06-03 18:47:52 -07005199 ContentProviderRecord localCpr = mProvidersByClass.get(cpr.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 localCpr.externals--;
5201 if (localCpr.externals < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005202 Slog.e(TAG, "Externals < 0 for content provider " + localCpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 }
5204 updateOomAdjLocked();
5205 }
5206 }
5207
5208 public final void publishContentProviders(IApplicationThread caller,
5209 List<ContentProviderHolder> providers) {
5210 if (providers == null) {
5211 return;
5212 }
5213
5214 synchronized(this) {
5215 final ProcessRecord r = getRecordForAppLocked(caller);
5216 if (r == null) {
5217 throw new SecurityException(
5218 "Unable to find app for caller " + caller
5219 + " (pid=" + Binder.getCallingPid()
5220 + ") when publishing content providers");
5221 }
5222
5223 final long origId = Binder.clearCallingIdentity();
5224
5225 final int N = providers.size();
5226 for (int i=0; i<N; i++) {
5227 ContentProviderHolder src = providers.get(i);
5228 if (src == null || src.info == null || src.provider == null) {
5229 continue;
5230 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07005231 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005232 if (dst != null) {
5233 mProvidersByClass.put(dst.info.name, dst);
5234 String names[] = dst.info.authority.split(";");
5235 for (int j = 0; j < names.length; j++) {
5236 mProvidersByName.put(names[j], dst);
5237 }
5238
5239 int NL = mLaunchingProviders.size();
5240 int j;
5241 for (j=0; j<NL; j++) {
5242 if (mLaunchingProviders.get(j) == dst) {
5243 mLaunchingProviders.remove(j);
5244 j--;
5245 NL--;
5246 }
5247 }
5248 synchronized (dst) {
5249 dst.provider = src.provider;
5250 dst.app = r;
5251 dst.notifyAll();
5252 }
5253 updateOomAdjLocked(r);
5254 }
5255 }
5256
5257 Binder.restoreCallingIdentity(origId);
5258 }
5259 }
5260
5261 public static final void installSystemProviders() {
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08005262 List providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06005263 synchronized (mSelf) {
5264 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
5265 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08005266 if (providers != null) {
5267 for (int i=providers.size()-1; i>=0; i--) {
5268 ProviderInfo pi = (ProviderInfo)providers.get(i);
5269 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5270 Slog.w(TAG, "Not installing system proc provider " + pi.name
5271 + ": not system .apk");
5272 providers.remove(i);
5273 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005274 }
5275 }
5276 }
Josh Bartel2ecce342010-02-25 10:55:48 -06005277 if (providers != null) {
5278 mSystemThread.installSystemProviders(providers);
5279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005280 }
5281
5282 // =========================================================
5283 // GLOBAL MANAGEMENT
5284 // =========================================================
5285
5286 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
5287 ApplicationInfo info, String customProcess) {
5288 String proc = customProcess != null ? customProcess : info.processName;
5289 BatteryStatsImpl.Uid.Proc ps = null;
5290 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
5291 synchronized (stats) {
5292 ps = stats.getProcessStatsLocked(info.uid, proc);
5293 }
5294 return new ProcessRecord(ps, thread, info, proc);
5295 }
5296
5297 final ProcessRecord addAppLocked(ApplicationInfo info) {
5298 ProcessRecord app = getProcessRecordLocked(info.processName, info.uid);
5299
5300 if (app == null) {
5301 app = newProcessRecordLocked(null, info, null);
5302 mProcessNames.put(info.processName, info.uid, app);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08005303 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005304 }
5305
5306 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
5307 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
5308 app.persistent = true;
5309 app.maxAdj = CORE_SERVER_ADJ;
5310 }
5311 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
5312 mPersistentStartingProcesses.add(app);
5313 startProcessLocked(app, "added application", app.processName);
5314 }
5315
5316 return app;
5317 }
5318
5319 public void unhandledBack() {
5320 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
5321 "unhandledBack()");
5322
5323 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005324 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08005325 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005326 TAG, "Performing unhandledBack(): stack size = " + count);
5327 if (count > 1) {
5328 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005329 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005330 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
5331 Binder.restoreCallingIdentity(origId);
5332 }
5333 }
5334 }
5335
5336 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
5337 String name = uri.getAuthority();
5338 ContentProviderHolder cph = getContentProviderExternal(name);
5339 ParcelFileDescriptor pfd = null;
5340 if (cph != null) {
5341 // We record the binder invoker's uid in thread-local storage before
5342 // going to the content provider to open the file. Later, in the code
5343 // that handles all permissions checks, we look for this uid and use
5344 // that rather than the Activity Manager's own uid. The effect is that
5345 // we do the check against the caller's permissions even though it looks
5346 // to the content provider like the Activity Manager itself is making
5347 // the request.
5348 sCallerIdentity.set(new Identity(
5349 Binder.getCallingPid(), Binder.getCallingUid()));
5350 try {
5351 pfd = cph.provider.openFile(uri, "r");
5352 } catch (FileNotFoundException e) {
5353 // do nothing; pfd will be returned null
5354 } finally {
5355 // Ensure that whatever happens, we clean up the identity state
5356 sCallerIdentity.remove();
5357 }
5358
5359 // We've got the fd now, so we're done with the provider.
5360 removeContentProviderExternal(name);
5361 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005362 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363 }
5364 return pfd;
5365 }
5366
5367 public void goingToSleep() {
5368 synchronized(this) {
5369 mSleeping = true;
5370 mWindowManager.setEventDispatching(false);
5371
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005372 if (mMainStack.mResumedActivity != null) {
5373 mMainStack.pauseIfSleepingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005375 Slog.w(TAG, "goingToSleep with no resumed activity!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005376 }
5377 }
5378 }
5379
Dianne Hackborn55280a92009-05-07 15:53:46 -07005380 public boolean shutdown(int timeout) {
5381 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
5382 != PackageManager.PERMISSION_GRANTED) {
5383 throw new SecurityException("Requires permission "
5384 + android.Manifest.permission.SHUTDOWN);
5385 }
5386
5387 boolean timedout = false;
5388
5389 synchronized(this) {
5390 mShuttingDown = true;
5391 mWindowManager.setEventDispatching(false);
5392
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005393 if (mMainStack.mResumedActivity != null) {
5394 mMainStack.pauseIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07005395 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005396 while (mMainStack.mResumedActivity != null
5397 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07005398 long delay = endTime - System.currentTimeMillis();
5399 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005400 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07005401 timedout = true;
5402 break;
5403 }
5404 try {
5405 this.wait();
5406 } catch (InterruptedException e) {
5407 }
5408 }
5409 }
5410 }
5411
5412 mUsageStatsService.shutdown();
5413 mBatteryStatsService.shutdown();
5414
5415 return timedout;
5416 }
5417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005418 public void wakingUp() {
5419 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005420 if (mMainStack.mGoingToSleep.isHeld()) {
5421 mMainStack.mGoingToSleep.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005422 }
5423 mWindowManager.setEventDispatching(true);
5424 mSleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005425 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426 }
5427 }
5428
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005429 public void stopAppSwitches() {
5430 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
5431 != PackageManager.PERMISSION_GRANTED) {
5432 throw new SecurityException("Requires permission "
5433 + android.Manifest.permission.STOP_APP_SWITCHES);
5434 }
5435
5436 synchronized(this) {
5437 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
5438 + APP_SWITCH_DELAY_TIME;
5439 mDidAppSwitch = false;
5440 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
5441 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
5442 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
5443 }
5444 }
5445
5446 public void resumeAppSwitches() {
5447 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
5448 != PackageManager.PERMISSION_GRANTED) {
5449 throw new SecurityException("Requires permission "
5450 + android.Manifest.permission.STOP_APP_SWITCHES);
5451 }
5452
5453 synchronized(this) {
5454 // Note that we don't execute any pending app switches... we will
5455 // let those wait until either the timeout, or the next start
5456 // activity request.
5457 mAppSwitchesAllowedTime = 0;
5458 }
5459 }
5460
5461 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
5462 String name) {
5463 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
5464 return true;
5465 }
5466
5467 final int perm = checkComponentPermission(
5468 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
5469 callingUid, -1);
5470 if (perm == PackageManager.PERMISSION_GRANTED) {
5471 return true;
5472 }
5473
Joe Onorato8a9b2202010-02-26 18:56:32 -08005474 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005475 return false;
5476 }
5477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 public void setDebugApp(String packageName, boolean waitForDebugger,
5479 boolean persistent) {
5480 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
5481 "setDebugApp()");
5482
5483 // Note that this is not really thread safe if there are multiple
5484 // callers into it at the same time, but that's not a situation we
5485 // care about.
5486 if (persistent) {
5487 final ContentResolver resolver = mContext.getContentResolver();
5488 Settings.System.putString(
5489 resolver, Settings.System.DEBUG_APP,
5490 packageName);
5491 Settings.System.putInt(
5492 resolver, Settings.System.WAIT_FOR_DEBUGGER,
5493 waitForDebugger ? 1 : 0);
5494 }
5495
5496 synchronized (this) {
5497 if (!persistent) {
5498 mOrigDebugApp = mDebugApp;
5499 mOrigWaitForDebugger = mWaitForDebugger;
5500 }
5501 mDebugApp = packageName;
5502 mWaitForDebugger = waitForDebugger;
5503 mDebugTransient = !persistent;
5504 if (packageName != null) {
5505 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005506 forceStopPackageLocked(packageName, -1, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 Binder.restoreCallingIdentity(origId);
5508 }
5509 }
5510 }
5511
5512 public void setAlwaysFinish(boolean enabled) {
5513 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
5514 "setAlwaysFinish()");
5515
5516 Settings.System.putInt(
5517 mContext.getContentResolver(),
5518 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
5519
5520 synchronized (this) {
5521 mAlwaysFinishActivities = enabled;
5522 }
5523 }
5524
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005525 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005527 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005529 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 }
5531 }
5532
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08005533 public boolean isUserAMonkey() {
5534 // For now the fact that there is a controller implies
5535 // we have a monkey.
5536 synchronized (this) {
5537 return mController != null;
5538 }
5539 }
5540
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005541 public void registerActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06005542 synchronized (this) {
5543 mWatchers.register(watcher);
5544 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005545 }
5546
5547 public void unregisterActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06005548 synchronized (this) {
5549 mWatchers.unregister(watcher);
5550 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005551 }
5552
Daniel Sandler69a48172010-06-23 16:29:36 -04005553 public void setImmersive(IBinder token, boolean immersive) {
5554 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005555 int index = (token != null) ? mMainStack.indexOfTokenLocked(token) : -1;
Daniel Sandler69a48172010-06-23 16:29:36 -04005556 if (index < 0) {
5557 throw new IllegalArgumentException();
5558 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005559 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
Daniel Sandler69a48172010-06-23 16:29:36 -04005560 r.immersive = immersive;
5561 }
5562 }
5563
5564 public boolean isImmersive(IBinder token) {
5565 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005566 int index = (token != null) ? mMainStack.indexOfTokenLocked(token) : -1;
Daniel Sandler69a48172010-06-23 16:29:36 -04005567 if (index < 0) {
5568 throw new IllegalArgumentException();
5569 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005570 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
Daniel Sandler69a48172010-06-23 16:29:36 -04005571 return r.immersive;
5572 }
5573 }
5574
5575 public boolean isTopActivityImmersive() {
5576 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005577 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04005578 return (r != null) ? r.immersive : false;
5579 }
5580 }
5581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 public final void enterSafeMode() {
5583 synchronized(this) {
5584 // It only makes sense to do this before the system is ready
5585 // and started launching other packages.
5586 if (!mSystemReady) {
5587 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005588 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 } catch (RemoteException e) {
5590 }
5591
5592 View v = LayoutInflater.from(mContext).inflate(
5593 com.android.internal.R.layout.safe_mode, null);
5594 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
5595 lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
5596 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
5597 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
5598 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
5599 lp.format = v.getBackground().getOpacity();
5600 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
5601 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
5602 ((WindowManager)mContext.getSystemService(
5603 Context.WINDOW_SERVICE)).addView(v, lp);
5604 }
5605 }
5606 }
5607
5608 public void noteWakeupAlarm(IIntentSender sender) {
5609 if (!(sender instanceof PendingIntentRecord)) {
5610 return;
5611 }
5612 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
5613 synchronized (stats) {
5614 if (mBatteryStatsService.isOnBattery()) {
5615 mBatteryStatsService.enforceCallingPermission();
5616 PendingIntentRecord rec = (PendingIntentRecord)sender;
5617 int MY_UID = Binder.getCallingUid();
5618 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
5619 BatteryStatsImpl.Uid.Pkg pkg =
5620 stats.getPackageStatsLocked(uid, rec.key.packageName);
5621 pkg.incWakeupsLocked();
5622 }
5623 }
5624 }
5625
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07005626 public boolean killPids(int[] pids, String pReason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07005628 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005629 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07005630 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005631 // XXX Note: don't acquire main activity lock here, because the window
5632 // manager calls in with its locks held.
5633
5634 boolean killed = false;
5635 synchronized (mPidsSelfLocked) {
5636 int[] types = new int[pids.length];
5637 int worstType = 0;
5638 for (int i=0; i<pids.length; i++) {
5639 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
5640 if (proc != null) {
5641 int type = proc.setAdj;
5642 types[i] = type;
5643 if (type > worstType) {
5644 worstType = type;
5645 }
5646 }
5647 }
5648
5649 // If the worse oom_adj is somewhere in the hidden proc LRU range,
5650 // then constrain it so we will kill all hidden procs.
5651 if (worstType < EMPTY_APP_ADJ && worstType > HIDDEN_APP_MIN_ADJ) {
5652 worstType = HIDDEN_APP_MIN_ADJ;
5653 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07005654 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 for (int i=0; i<pids.length; i++) {
5656 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
5657 if (proc == null) {
5658 continue;
5659 }
5660 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07005661 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07005662 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07005663 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
5664 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07005666 proc.killedBackground = true;
5667 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 }
5669 }
5670 }
5671 return killed;
5672 }
5673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 public final void startRunning(String pkg, String cls, String action,
5675 String data) {
5676 synchronized(this) {
5677 if (mStartRunning) {
5678 return;
5679 }
5680 mStartRunning = true;
5681 mTopComponent = pkg != null && cls != null
5682 ? new ComponentName(pkg, cls) : null;
5683 mTopAction = action != null ? action : Intent.ACTION_MAIN;
5684 mTopData = data;
5685 if (!mSystemReady) {
5686 return;
5687 }
5688 }
5689
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07005690 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 }
5692
5693 private void retrieveSettings() {
5694 final ContentResolver resolver = mContext.getContentResolver();
5695 String debugApp = Settings.System.getString(
5696 resolver, Settings.System.DEBUG_APP);
5697 boolean waitForDebugger = Settings.System.getInt(
5698 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
5699 boolean alwaysFinishActivities = Settings.System.getInt(
5700 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
5701
5702 Configuration configuration = new Configuration();
5703 Settings.System.getConfiguration(resolver, configuration);
5704
5705 synchronized (this) {
5706 mDebugApp = mOrigDebugApp = debugApp;
5707 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
5708 mAlwaysFinishActivities = alwaysFinishActivities;
5709 // This happens before any activities are started, so we can
5710 // change mConfiguration in-place.
5711 mConfiguration.updateFrom(configuration);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005712 mConfigurationSeq = mConfiguration.seq = 1;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005713 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005714 }
5715 }
5716
5717 public boolean testIsSystemReady() {
5718 // no need to synchronize(this) just to read & return the value
5719 return mSystemReady;
5720 }
5721
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07005722 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 // In the simulator, startRunning will never have been called, which
5724 // normally sets a few crucial variables. Do it here instead.
5725 if (!Process.supportsProcesses()) {
5726 mStartRunning = true;
5727 mTopAction = Intent.ACTION_MAIN;
5728 }
5729
5730 synchronized(this) {
5731 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07005732 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 return;
5734 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005735
5736 // Check to see if there are any update receivers to run.
5737 if (!mDidUpdate) {
5738 if (mWaitingUpdate) {
5739 return;
5740 }
5741 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5742 List<ResolveInfo> ris = null;
5743 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005744 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005745 intent, null, 0);
5746 } catch (RemoteException e) {
5747 }
5748 if (ris != null) {
5749 for (int i=ris.size()-1; i>=0; i--) {
5750 if ((ris.get(i).activityInfo.applicationInfo.flags
5751 &ApplicationInfo.FLAG_SYSTEM) == 0) {
5752 ris.remove(i);
5753 }
5754 }
5755 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
5756 for (int i=0; i<ris.size(); i++) {
5757 ActivityInfo ai = ris.get(i).activityInfo;
5758 intent.setComponent(new ComponentName(ai.packageName, ai.name));
5759 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08005760 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005761 finisher = new IIntentReceiver.Stub() {
5762 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07005763 String data, Bundle extras, boolean ordered,
5764 boolean sticky)
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005765 throws RemoteException {
5766 synchronized (ActivityManagerService.this) {
5767 mDidUpdate = true;
5768 }
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07005769 systemReady(goingCallback);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005770 }
5771 };
5772 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005773 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005774 broadcastIntentLocked(null, null, intent, null, finisher,
5775 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackbornd6847842010-01-12 18:14:19 -08005776 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005777 mWaitingUpdate = true;
5778 }
5779 }
5780 }
5781 if (mWaitingUpdate) {
5782 return;
5783 }
5784 mDidUpdate = true;
5785 }
5786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 mSystemReady = true;
5788 if (!mStartRunning) {
5789 return;
5790 }
5791 }
5792
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005793 ArrayList<ProcessRecord> procsToKill = null;
5794 synchronized(mPidsSelfLocked) {
5795 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
5796 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
5797 if (!isAllowedWhileBooting(proc.info)){
5798 if (procsToKill == null) {
5799 procsToKill = new ArrayList<ProcessRecord>();
5800 }
5801 procsToKill.add(proc);
5802 }
5803 }
5804 }
5805
5806 if (procsToKill != null) {
5807 synchronized(this) {
5808 for (int i=procsToKill.size()-1; i>=0; i--) {
5809 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005810 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005811 removeProcessLocked(proc, true);
5812 }
5813 }
5814 }
5815
Joe Onorato8a9b2202010-02-26 18:56:32 -08005816 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08005817 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 SystemClock.uptimeMillis());
5819
5820 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005821 // Make sure we have no pre-ready processes sitting around.
5822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
5824 ResolveInfo ri = mContext.getPackageManager()
5825 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07005826 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005827 CharSequence errorMsg = null;
5828 if (ri != null) {
5829 ActivityInfo ai = ri.activityInfo;
5830 ApplicationInfo app = ai.applicationInfo;
5831 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5832 mTopAction = Intent.ACTION_FACTORY_TEST;
5833 mTopData = null;
5834 mTopComponent = new ComponentName(app.packageName,
5835 ai.name);
5836 } else {
5837 errorMsg = mContext.getResources().getText(
5838 com.android.internal.R.string.factorytest_not_system);
5839 }
5840 } else {
5841 errorMsg = mContext.getResources().getText(
5842 com.android.internal.R.string.factorytest_no_action);
5843 }
5844 if (errorMsg != null) {
5845 mTopAction = null;
5846 mTopData = null;
5847 mTopComponent = null;
5848 Message msg = Message.obtain();
5849 msg.what = SHOW_FACTORY_ERROR_MSG;
5850 msg.getData().putCharSequence("msg", errorMsg);
5851 mHandler.sendMessage(msg);
5852 }
5853 }
5854 }
5855
5856 retrieveSettings();
5857
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07005858 if (goingCallback != null) goingCallback.run();
5859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 synchronized (this) {
5861 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
5862 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005863 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07005864 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005865 if (apps != null) {
5866 int N = apps.size();
5867 int i;
5868 for (i=0; i<N; i++) {
5869 ApplicationInfo info
5870 = (ApplicationInfo)apps.get(i);
5871 if (info != null &&
5872 !info.packageName.equals("android")) {
5873 addAppLocked(info);
5874 }
5875 }
5876 }
5877 } catch (RemoteException ex) {
5878 // pm is in same process, this will never happen.
5879 }
5880 }
5881
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005882 // Start up initial activity.
5883 mBooting = true;
5884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005886 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 Message msg = Message.obtain();
5888 msg.what = SHOW_UID_ERROR_MSG;
5889 mHandler.sendMessage(msg);
5890 }
5891 } catch (RemoteException e) {
5892 }
5893
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005894 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005895 }
5896 }
5897
Dan Egnorb7f03672009-12-09 16:22:32 -08005898 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08005899 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08005901 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08005902 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005903 startAppProblemLocked(app);
5904 app.stopFreezingAllLocked();
5905 return handleAppCrashLocked(app);
5906 }
5907
Dan Egnorb7f03672009-12-09 16:22:32 -08005908 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08005909 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08005911 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08005912 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
5913 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005914 startAppProblemLocked(app);
5915 app.stopFreezingAllLocked();
5916 }
5917
5918 /**
5919 * Generate a process error record, suitable for attachment to a ProcessRecord.
5920 *
5921 * @param app The ProcessRecord in which the error occurred.
5922 * @param condition Crashing, Application Not Responding, etc. Values are defined in
5923 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08005924 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 * @param shortMsg Short message describing the crash.
5926 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08005927 * @param stackTrace Full crash stack trace, may be null.
5928 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005929 * @return Returns a fully-formed AppErrorStateInfo record.
5930 */
5931 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08005932 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005933 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08005934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005935 report.condition = condition;
5936 report.processName = app.processName;
5937 report.pid = app.pid;
5938 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08005939 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 report.shortMsg = shortMsg;
5941 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08005942 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943
5944 return report;
5945 }
5946
Dan Egnor42471dd2010-01-07 17:25:22 -08005947 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005948 synchronized (this) {
5949 app.crashing = false;
5950 app.crashingReport = null;
5951 app.notResponding = false;
5952 app.notRespondingReport = null;
5953 if (app.anrDialog == fromDialog) {
5954 app.anrDialog = null;
5955 }
5956 if (app.waitDialog == fromDialog) {
5957 app.waitDialog = null;
5958 }
5959 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08005960 handleAppCrashLocked(app);
Dianne Hackborn8633e682010-04-22 16:03:41 -07005961 Slog.i(ActivityManagerService.TAG, "Killing "
5962 + app.processName + " (pid=" + app.pid + "): user's request");
5963 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
5964 app.processName, app.setAdj, "user's request after error");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005965 Process.killProcess(app.pid);
5966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 }
5968 }
Dan Egnor42471dd2010-01-07 17:25:22 -08005969
Dan Egnorb7f03672009-12-09 16:22:32 -08005970 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005971 long now = SystemClock.uptimeMillis();
5972
5973 Long crashTime = mProcessCrashTimes.get(app.info.processName,
5974 app.info.uid);
5975 if (crashTime != null && now < crashTime+MIN_CRASH_INTERVAL) {
5976 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08005977 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08005979 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980 app.info.processName, app.info.uid);
5981 killServicesLocked(app, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005982 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5983 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005985 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005986 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005987 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 }
5989 }
5990 if (!app.persistent) {
5991 // We don't want to start this process again until the user
5992 // explicitly does so... but for persistent process, we really
5993 // need to keep it running. If a persistent process is actually
5994 // repeatedly crashing, then badness for everyone.
Doug Zongker2bec3d42009-12-04 12:52:44 -08005995 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 app.info.processName);
5997 mBadProcesses.put(app.info.processName, app.info.uid, now);
5998 app.bad = true;
5999 mProcessCrashTimes.remove(app.info.processName, app.info.uid);
6000 app.removed = true;
6001 removeProcessLocked(app, false);
6002 return false;
6003 }
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006004 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006005 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006006 if (r.app == app) {
6007 // If the top running activity is from this crashing
6008 // process, then terminate it to avoid getting in a loop.
6009 Slog.w(TAG, " Force finishing activity "
6010 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006011 int index = mMainStack.indexOfTokenLocked(r);
6012 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006013 Activity.RESULT_CANCELED, null, "crashed");
6014 // Also terminate an activities below it that aren't yet
6015 // stopped, to avoid a situation where one will get
6016 // re-start our crashing activity once it gets resumed again.
6017 index--;
6018 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006019 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006020 if (r.state == ActivityState.RESUMED
6021 || r.state == ActivityState.PAUSING
6022 || r.state == ActivityState.PAUSED) {
6023 if (!r.isHomeActivity) {
6024 Slog.w(TAG, " Force finishing activity "
6025 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006026 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07006027 Activity.RESULT_CANCELED, null, "crashed");
6028 }
6029 }
6030 }
6031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 }
6033
6034 // Bump up the crash count of any services currently running in the proc.
6035 if (app.services.size() != 0) {
6036 // Any services running in the application need to be placed
6037 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07006038 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07006040 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 sr.crashCount++;
6042 }
6043 }
6044
6045 mProcessCrashTimes.put(app.info.processName, app.info.uid, now);
6046 return true;
6047 }
6048
6049 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006050 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
6051 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 skipCurrentReceiverLocked(app);
6053 }
6054
6055 void skipCurrentReceiverLocked(ProcessRecord app) {
6056 boolean reschedule = false;
6057 BroadcastRecord r = app.curReceiver;
6058 if (r != null) {
6059 // The current broadcast is waiting for this app's receiver
6060 // to be finished. Looks like that's not going to happen, so
6061 // let the broadcast continue.
6062 logBroadcastReceiverDiscard(r);
6063 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
6064 r.resultExtras, r.resultAbort, true);
6065 reschedule = true;
6066 }
6067 r = mPendingBroadcast;
6068 if (r != null && r.curApp == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006069 if (DEBUG_BROADCAST) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 "skip & discard pending app " + r);
6071 logBroadcastReceiverDiscard(r);
6072 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
6073 r.resultExtras, r.resultAbort, true);
6074 reschedule = true;
6075 }
6076 if (reschedule) {
6077 scheduleBroadcastsLocked();
6078 }
6079 }
6080
Dan Egnor60d87622009-12-16 16:32:58 -08006081 /**
6082 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
6083 * The application process will exit immediately after this call returns.
6084 * @param app object of the crashing app, null for the system server
6085 * @param crashInfo describing the exception
6086 */
6087 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
6088 ProcessRecord r = findAppProcess(app);
6089
6090 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
6091 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08006092 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08006093 crashInfo.exceptionClassName,
6094 crashInfo.exceptionMessage,
6095 crashInfo.throwFileName,
6096 crashInfo.throwLineNumber);
6097
Dan Egnor42471dd2010-01-07 17:25:22 -08006098 addErrorToDropBox("crash", r, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08006099
6100 crashApplication(r, crashInfo);
6101 }
6102
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006103 public void handleApplicationStrictModeViolation(
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006104 IBinder app, int violationMask, ApplicationErrorReport.CrashInfo crashInfo) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006105 ProcessRecord r = findAppProcess(app);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006106
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006107 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006108 Integer stackFingerprint = crashInfo.stackTrace.hashCode();
6109 boolean logIt = true;
6110 synchronized (mAlreadyLoggedViolatedStacks) {
6111 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
6112 logIt = false;
6113 // TODO: sub-sample into EventLog for these, with
6114 // the crashInfo.durationMillis? Then we'd get
6115 // the relative pain numbers, without logging all
6116 // the stack traces repeatedly. We'd want to do
6117 // likewise in the client code, which also does
6118 // dup suppression, before the Binder call.
6119 } else {
6120 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
6121 mAlreadyLoggedViolatedStacks.clear();
6122 }
6123 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
6124 }
6125 }
6126 if (logIt) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006127 logStrictModeViolationToDropBox(r, crashInfo);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006128 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006129 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006130
6131 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
6132 AppErrorResult result = new AppErrorResult();
6133 synchronized (this) {
6134 final long origId = Binder.clearCallingIdentity();
6135
6136 Message msg = Message.obtain();
6137 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
6138 HashMap<String, Object> data = new HashMap<String, Object>();
6139 data.put("result", result);
6140 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07006141 data.put("violationMask", violationMask);
6142 data.put("crashInfo", crashInfo);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07006143 msg.obj = data;
6144 mHandler.sendMessage(msg);
6145
6146 Binder.restoreCallingIdentity(origId);
6147 }
6148 int res = result.get();
6149 Log.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
6150 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07006151 }
6152
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006153 // Depending on the policy in effect, there could be a bunch of
6154 // these in quick succession so we try to batch these together to
6155 // minimize disk writes, number of dropbox entries, and maximize
6156 // compression, by having more fewer, larger records.
6157 private void logStrictModeViolationToDropBox(ProcessRecord process,
6158 ApplicationErrorReport.CrashInfo crashInfo) {
6159 if (crashInfo == null) {
6160 return;
6161 }
6162 final boolean isSystemApp = process == null ||
6163 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
6164 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
6165 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
6166 final DropBoxManager dbox = (DropBoxManager)
6167 mContext.getSystemService(Context.DROPBOX_SERVICE);
6168
6169 // Exit early if the dropbox isn't configured to accept this report type.
6170 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
6171
6172 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006173 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006174 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
6175 synchronized (sb) {
6176 bufferWasEmpty = sb.length() == 0;
6177 appendDropBoxProcessHeaders(process, sb);
6178 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
6179 sb.append("System-App: ").append(isSystemApp).append("\n");
6180 if (crashInfo != null && crashInfo.durationMillis != -1) {
6181 sb.append("Duration-Millis: ").append(crashInfo.durationMillis).append("\n");
6182 }
6183 sb.append("\n");
6184 if (crashInfo != null && crashInfo.stackTrace != null) {
6185 sb.append(crashInfo.stackTrace);
6186 }
6187 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006188
6189 // Only buffer up to ~64k. Various logging bits truncate
6190 // things at 128k.
6191 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006192 }
6193
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006194 // Flush immediately if the buffer's grown too large, or this
6195 // is a non-system app. Non-system apps are isolated with a
6196 // different tag & policy and not batched.
6197 //
6198 // Batching is useful during internal testing with
6199 // StrictMode settings turned up high. Without batching,
6200 // thousands of separate files could be created on boot.
6201 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006202 new Thread("Error dump: " + dropboxTag) {
6203 @Override
6204 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006205 String report;
6206 synchronized (sb) {
6207 report = sb.toString();
6208 sb.delete(0, sb.length());
6209 sb.trimToSize();
6210 }
6211 if (report.length() != 0) {
6212 dbox.addText(dropboxTag, report);
6213 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006214 }
6215 }.start();
6216 return;
6217 }
6218
6219 // System app batching:
6220 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07006221 // An existing dropbox-writing thread is outstanding, so
6222 // we don't need to start it up. The existing thread will
6223 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006224 return;
6225 }
6226
6227 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
6228 // (After this point, we shouldn't access AMS internal data structures.)
6229 new Thread("Error dump: " + dropboxTag) {
6230 @Override
6231 public void run() {
6232 // 5 second sleep to let stacks arrive and be batched together
6233 try {
6234 Thread.sleep(5000); // 5 seconds
6235 } catch (InterruptedException e) {}
6236
6237 String errorReport;
6238 synchronized (mStrictModeBuffer) {
6239 errorReport = mStrictModeBuffer.toString();
6240 if (errorReport.length() == 0) {
6241 return;
6242 }
6243 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
6244 mStrictModeBuffer.trimToSize();
6245 }
6246 dbox.addText(dropboxTag, errorReport);
6247 }
6248 }.start();
6249 }
6250
Dan Egnor60d87622009-12-16 16:32:58 -08006251 /**
6252 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
6253 * @param app object of the crashing app, null for the system server
6254 * @param tag reported by the caller
6255 * @param crashInfo describing the context of the error
6256 * @return true if the process should exit immediately (WTF is fatal)
6257 */
6258 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08006259 ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnor60d87622009-12-16 16:32:58 -08006260 ProcessRecord r = findAppProcess(app);
6261
6262 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
6263 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08006264 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08006265 tag, crashInfo.exceptionMessage);
6266
Dan Egnor42471dd2010-01-07 17:25:22 -08006267 addErrorToDropBox("wtf", r, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08006268
Doug Zongker43866e02010-01-07 12:09:54 -08006269 if (Settings.Secure.getInt(mContext.getContentResolver(),
6270 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08006271 crashApplication(r, crashInfo);
6272 return true;
6273 } else {
6274 return false;
6275 }
6276 }
6277
6278 /**
6279 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
6280 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
6281 */
6282 private ProcessRecord findAppProcess(IBinder app) {
6283 if (app == null) {
6284 return null;
6285 }
6286
6287 synchronized (this) {
6288 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
6289 final int NA = apps.size();
6290 for (int ia=0; ia<NA; ia++) {
6291 ProcessRecord p = apps.valueAt(ia);
6292 if (p.thread != null && p.thread.asBinder() == app) {
6293 return p;
6294 }
6295 }
6296 }
6297
Joe Onorato8a9b2202010-02-26 18:56:32 -08006298 Slog.w(TAG, "Can't find mystery application: " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08006299 return null;
6300 }
6301 }
6302
6303 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006304 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
6305 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08006306 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006307 private static void appendDropBoxProcessHeaders(ProcessRecord process, StringBuilder sb) {
Dan Egnora455d192010-03-12 08:52:28 -08006308 if (process == null || process.pid == MY_PID) {
6309 sb.append("Process: system_server\n");
6310 } else {
6311 sb.append("Process: ").append(process.processName).append("\n");
6312 }
6313 if (process != null) {
6314 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006315 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08006316 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
6317 for (String pkg : process.pkgList) {
6318 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08006319 try {
Dan Egnora455d192010-03-12 08:52:28 -08006320 PackageInfo pi = pm.getPackageInfo(pkg, 0);
6321 if (pi != null) {
6322 sb.append(" v").append(pi.versionCode);
6323 if (pi.versionName != null) {
6324 sb.append(" (").append(pi.versionName).append(")");
6325 }
6326 }
6327 } catch (RemoteException e) {
6328 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08006329 }
Dan Egnora455d192010-03-12 08:52:28 -08006330 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08006331 }
Dan Egnora455d192010-03-12 08:52:28 -08006332 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07006333 }
6334
6335 private static String processClass(ProcessRecord process) {
6336 if (process == null || process.pid == MY_PID) {
6337 return "system_server";
6338 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6339 return "system_app";
6340 } else {
6341 return "data_app";
6342 }
6343 }
6344
6345 /**
6346 * Write a description of an error (crash, WTF, ANR) to the drop box.
6347 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
6348 * @param process which caused the error, null means the system server
6349 * @param activity which triggered the error, null if unknown
6350 * @param parent activity related to the error, null if unknown
6351 * @param subject line related to the error, null if absent
6352 * @param report in long form describing the error, null if absent
6353 * @param logFile to include in the report, null if none
6354 * @param crashInfo giving an application stack trace, null if absent
6355 */
6356 public void addErrorToDropBox(String eventType,
6357 ProcessRecord process, ActivityRecord activity, ActivityRecord parent, String subject,
6358 final String report, final File logFile,
6359 final ApplicationErrorReport.CrashInfo crashInfo) {
6360 // NOTE -- this must never acquire the ActivityManagerService lock,
6361 // otherwise the watchdog may be prevented from resetting the system.
6362
6363 final String dropboxTag = processClass(process) + "_" + eventType;
6364 final DropBoxManager dbox = (DropBoxManager)
6365 mContext.getSystemService(Context.DROPBOX_SERVICE);
6366
6367 // Exit early if the dropbox isn't configured to accept this report type.
6368 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
6369
6370 final StringBuilder sb = new StringBuilder(1024);
6371 appendDropBoxProcessHeaders(process, sb);
Dan Egnora455d192010-03-12 08:52:28 -08006372 if (activity != null) {
6373 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
6374 }
6375 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
6376 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
6377 }
6378 if (parent != null && parent != activity) {
6379 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
6380 }
6381 if (subject != null) {
6382 sb.append("Subject: ").append(subject).append("\n");
6383 }
6384 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
6385 sb.append("\n");
6386
6387 // Do the rest in a worker thread to avoid blocking the caller on I/O
6388 // (After this point, we shouldn't access AMS internal data structures.)
6389 Thread worker = new Thread("Error dump: " + dropboxTag) {
6390 @Override
6391 public void run() {
6392 if (report != null) {
6393 sb.append(report);
6394 }
6395 if (logFile != null) {
6396 try {
6397 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
6398 } catch (IOException e) {
6399 Slog.e(TAG, "Error reading " + logFile, e);
6400 }
6401 }
6402 if (crashInfo != null && crashInfo.stackTrace != null) {
6403 sb.append(crashInfo.stackTrace);
6404 }
6405
6406 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
6407 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
6408 if (lines > 0) {
6409 sb.append("\n");
6410
6411 // Merge several logcat streams, and take the last N lines
6412 InputStreamReader input = null;
6413 try {
6414 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
6415 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
6416 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
6417
6418 try { logcat.getOutputStream().close(); } catch (IOException e) {}
6419 try { logcat.getErrorStream().close(); } catch (IOException e) {}
6420 input = new InputStreamReader(logcat.getInputStream());
6421
6422 int num;
6423 char[] buf = new char[8192];
6424 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
6425 } catch (IOException e) {
6426 Slog.e(TAG, "Error running logcat", e);
6427 } finally {
6428 if (input != null) try { input.close(); } catch (IOException e) {}
6429 }
6430 }
6431
6432 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08006433 }
Dan Egnora455d192010-03-12 08:52:28 -08006434 };
6435
6436 if (process == null || process.pid == MY_PID) {
6437 worker.run(); // We may be about to die -- need to run this synchronously
6438 } else {
6439 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08006440 }
6441 }
6442
6443 /**
6444 * Bring up the "unexpected error" dialog box for a crashing app.
6445 * Deal with edge cases (intercepts from instrumented applications,
6446 * ActivityController, error intent receivers, that sort of thing).
6447 * @param r the application crashing
6448 * @param crashInfo describing the failure
6449 */
6450 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08006451 long timeMillis = System.currentTimeMillis();
6452 String shortMsg = crashInfo.exceptionClassName;
6453 String longMsg = crashInfo.exceptionMessage;
6454 String stackTrace = crashInfo.stackTrace;
6455 if (shortMsg != null && longMsg != null) {
6456 longMsg = shortMsg + ": " + longMsg;
6457 } else if (shortMsg != null) {
6458 longMsg = shortMsg;
6459 }
6460
Dan Egnor60d87622009-12-16 16:32:58 -08006461 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006463 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 try {
6465 String name = r != null ? r.processName : null;
6466 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08006467 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08006468 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006469 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 + " at watcher's request");
6471 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08006472 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 }
6474 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006475 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006476 }
6477 }
6478
6479 final long origId = Binder.clearCallingIdentity();
6480
6481 // If this process is running instrumentation, finish it.
6482 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006483 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006484 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08006485 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
6486 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 Bundle info = new Bundle();
6488 info.putString("shortMsg", shortMsg);
6489 info.putString("longMsg", longMsg);
6490 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
6491 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08006492 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 }
6494
Dan Egnor60d87622009-12-16 16:32:58 -08006495 // If we can't identify the process or it's already exceeded its crash quota,
6496 // quit right away without showing a crash dialog.
6497 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08006499 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006500 }
6501
6502 Message msg = Message.obtain();
6503 msg.what = SHOW_ERROR_MSG;
6504 HashMap data = new HashMap();
6505 data.put("result", result);
6506 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507 msg.obj = data;
6508 mHandler.sendMessage(msg);
6509
6510 Binder.restoreCallingIdentity(origId);
6511 }
6512
6513 int res = result.get();
6514
Jacek Surazskif5b9c722009-05-18 12:09:59 +02006515 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 synchronized (this) {
6517 if (r != null) {
6518 mProcessCrashTimes.put(r.info.processName, r.info.uid,
6519 SystemClock.uptimeMillis());
6520 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02006521 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08006522 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02006523 }
6524 }
6525
6526 if (appErrorIntent != null) {
6527 try {
6528 mContext.startActivity(appErrorIntent);
6529 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006530 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02006531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 }
Dan Egnorb7f03672009-12-09 16:22:32 -08006534
6535 Intent createAppErrorIntentLocked(ProcessRecord r,
6536 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
6537 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02006538 if (report == null) {
6539 return null;
6540 }
6541 Intent result = new Intent(Intent.ACTION_APP_ERROR);
6542 result.setComponent(r.errorReportReceiver);
6543 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
6544 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
6545 return result;
6546 }
6547
Dan Egnorb7f03672009-12-09 16:22:32 -08006548 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
6549 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02006550 if (r.errorReportReceiver == null) {
6551 return null;
6552 }
6553
6554 if (!r.crashing && !r.notResponding) {
6555 return null;
6556 }
6557
Dan Egnorb7f03672009-12-09 16:22:32 -08006558 ApplicationErrorReport report = new ApplicationErrorReport();
6559 report.packageName = r.info.packageName;
6560 report.installerPackageName = r.errorReportReceiver.getPackageName();
6561 report.processName = r.processName;
6562 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01006563 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02006564
Dan Egnorb7f03672009-12-09 16:22:32 -08006565 if (r.crashing) {
6566 report.type = ApplicationErrorReport.TYPE_CRASH;
6567 report.crashInfo = crashInfo;
6568 } else if (r.notResponding) {
6569 report.type = ApplicationErrorReport.TYPE_ANR;
6570 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02006571
Dan Egnorb7f03672009-12-09 16:22:32 -08006572 report.anrInfo.activity = r.notRespondingReport.tag;
6573 report.anrInfo.cause = r.notRespondingReport.shortMsg;
6574 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02006575 }
6576
Dan Egnorb7f03672009-12-09 16:22:32 -08006577 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02006578 }
6579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
6581 // assume our apps are happy - lazy create the list
6582 List<ActivityManager.ProcessErrorStateInfo> errList = null;
6583
6584 synchronized (this) {
6585
6586 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006587 for (int i=mLruProcesses.size()-1; i>=0; i--) {
6588 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 if ((app.thread != null) && (app.crashing || app.notResponding)) {
6590 // This one's in trouble, so we'll generate a report for it
6591 // crashes are higher priority (in case there's a crash *and* an anr)
6592 ActivityManager.ProcessErrorStateInfo report = null;
6593 if (app.crashing) {
6594 report = app.crashingReport;
6595 } else if (app.notResponding) {
6596 report = app.notRespondingReport;
6597 }
6598
6599 if (report != null) {
6600 if (errList == null) {
6601 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
6602 }
6603 errList.add(report);
6604 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006605 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 " crashing = " + app.crashing +
6607 " notResponding = " + app.notResponding);
6608 }
6609 }
6610 }
6611 }
6612
6613 return errList;
6614 }
6615
6616 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
6617 // Lazy instantiation of list
6618 List<ActivityManager.RunningAppProcessInfo> runList = null;
6619 synchronized (this) {
6620 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006621 for (int i=mLruProcesses.size()-1; i>=0; i--) {
6622 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006623 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
6624 // Generate process state info for running application
6625 ActivityManager.RunningAppProcessInfo currApp =
6626 new ActivityManager.RunningAppProcessInfo(app.processName,
6627 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07006628 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07006629 if (mHeavyWeightProcess == app) {
6630 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HEAVY_WEIGHT;
6631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 int adj = app.curAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006633 if (adj >= EMPTY_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006634 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY;
6635 } else if (adj >= HIDDEN_APP_MIN_ADJ) {
6636 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
The Android Open Source Project4df24232009-03-05 14:34:35 -08006637 currApp.lru = adj - HIDDEN_APP_MIN_ADJ + 1;
6638 } else if (adj >= HOME_APP_ADJ) {
6639 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
6640 currApp.lru = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 } else if (adj >= SECONDARY_SERVER_ADJ) {
6642 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006643 } else if (adj >= HEAVY_WEIGHT_APP_ADJ) {
6644 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_HEAVY_WEIGHT;
6645 } else if (adj >= PERCEPTIBLE_APP_ADJ) {
6646 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006647 } else if (adj >= VISIBLE_APP_ADJ) {
6648 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
6649 } else {
6650 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
6651 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07006652 currApp.importanceReasonCode = app.adjTypeCode;
6653 if (app.adjSource instanceof ProcessRecord) {
6654 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006655 } else if (app.adjSource instanceof ActivityRecord) {
6656 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07006657 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
6658 }
6659 if (app.adjTarget instanceof ComponentName) {
6660 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
6661 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006662 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 // + " lru=" + currApp.lru);
6664 if (runList == null) {
6665 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
6666 }
6667 runList.add(currApp);
6668 }
6669 }
6670 }
6671 return runList;
6672 }
6673
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07006674 public List<ApplicationInfo> getRunningExternalApplications() {
6675 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
6676 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
6677 if (runningApps != null && runningApps.size() > 0) {
6678 Set<String> extList = new HashSet<String>();
6679 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
6680 if (app.pkgList != null) {
6681 for (String pkg : app.pkgList) {
6682 extList.add(pkg);
6683 }
6684 }
6685 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006686 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07006687 for (String pkg : extList) {
6688 try {
6689 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
6690 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
6691 retList.add(info);
6692 }
6693 } catch (RemoteException e) {
6694 }
6695 }
6696 }
6697 return retList;
6698 }
6699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006700 @Override
6701 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006702 if (checkCallingPermission(android.Manifest.permission.DUMP)
6703 != PackageManager.PERMISSION_GRANTED) {
6704 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6705 + Binder.getCallingPid()
6706 + ", uid=" + Binder.getCallingUid()
6707 + " without permission "
6708 + android.Manifest.permission.DUMP);
6709 return;
6710 }
6711
6712 boolean dumpAll = false;
6713
6714 int opti = 0;
6715 while (opti < args.length) {
6716 String opt = args[opti];
6717 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6718 break;
6719 }
6720 opti++;
6721 if ("-a".equals(opt)) {
6722 dumpAll = true;
6723 } else if ("-h".equals(opt)) {
6724 pw.println("Activity manager dump options:");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006725 pw.println(" [-a] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006726 pw.println(" cmd may be one of:");
6727 pw.println(" activities: activity stack state");
6728 pw.println(" broadcasts: broadcast state");
6729 pw.println(" intents: pending intent state");
6730 pw.println(" processes: process state");
6731 pw.println(" providers: content provider state");
6732 pw.println(" services: service state");
6733 pw.println(" service [name]: service client-side state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006735 } else {
6736 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006738 }
6739
6740 // Is the caller requesting to dump a particular piece of data?
6741 if (opti < args.length) {
6742 String cmd = args[opti];
6743 opti++;
6744 if ("activities".equals(cmd) || "a".equals(cmd)) {
6745 synchronized (this) {
6746 dumpActivitiesLocked(fd, pw, args, opti, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006748 return;
6749 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
6750 synchronized (this) {
6751 dumpBroadcastsLocked(fd, pw, args, opti, true);
6752 }
6753 return;
6754 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
6755 synchronized (this) {
6756 dumpPendingIntentsLocked(fd, pw, args, opti, true);
6757 }
6758 return;
6759 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
6760 synchronized (this) {
6761 dumpProcessesLocked(fd, pw, args, opti, true);
6762 }
6763 return;
6764 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
6765 synchronized (this) {
6766 dumpProvidersLocked(fd, pw, args, opti, true);
6767 }
6768 return;
6769 } else if ("service".equals(cmd)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07006770 dumpService(fd, pw, args, opti, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006771 return;
6772 } else if ("services".equals(cmd) || "s".equals(cmd)) {
6773 synchronized (this) {
6774 dumpServicesLocked(fd, pw, args, opti, true);
6775 }
6776 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006778 }
6779
6780 // No piece of data specified, dump everything.
6781 synchronized (this) {
6782 boolean needSep;
6783 if (dumpAll) {
6784 pw.println("Providers in Current Activity Manager State:");
6785 }
6786 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll);
6787 if (needSep) {
6788 pw.println(" ");
6789 }
6790 if (dumpAll) {
6791 pw.println("-------------------------------------------------------------------------------");
6792 pw.println("Broadcasts in Current Activity Manager State:");
6793 }
6794 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll);
6795 if (needSep) {
6796 pw.println(" ");
6797 }
6798 if (dumpAll) {
6799 pw.println("-------------------------------------------------------------------------------");
6800 pw.println("Services in Current Activity Manager State:");
6801 }
6802 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll);
6803 if (needSep) {
6804 pw.println(" ");
6805 }
6806 if (dumpAll) {
6807 pw.println("-------------------------------------------------------------------------------");
6808 pw.println("PendingIntents in Current Activity Manager State:");
6809 }
6810 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll);
6811 if (needSep) {
6812 pw.println(" ");
6813 }
6814 if (dumpAll) {
6815 pw.println("-------------------------------------------------------------------------------");
6816 pw.println("Activities in Current Activity Manager State:");
6817 }
6818 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, !dumpAll);
6819 if (needSep) {
6820 pw.println(" ");
6821 }
6822 if (dumpAll) {
6823 pw.println("-------------------------------------------------------------------------------");
6824 pw.println("Processes in Current Activity Manager State:");
6825 }
6826 dumpProcessesLocked(fd, pw, args, opti, dumpAll);
6827 }
6828 }
6829
6830 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
6831 int opti, boolean dumpAll, boolean needHeader) {
6832 if (needHeader) {
6833 pw.println(" Activity stack:");
6834 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006835 dumpHistoryList(pw, mMainStack.mHistory, " ", "Hist", true);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006836 pw.println(" ");
6837 pw.println(" Running activities (most recent first):");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006838 dumpHistoryList(pw, mMainStack.mLRUActivities, " ", "Run", false);
6839 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006841 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006842 dumpHistoryList(pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006843 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006844 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006846 pw.println(" Activities waiting to stop:");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006847 dumpHistoryList(pw, mMainStack.mStoppingActivities, " ", "Stop", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006848 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006849 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006850 pw.println(" ");
6851 pw.println(" Activities waiting to finish:");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006852 dumpHistoryList(pw, mMainStack.mFinishingActivities, " ", "Fin", false);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006854
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006855 pw.println(" ");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006856 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
6857 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006858 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006859 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006860
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006861 if (dumpAll && mRecentTasks.size() > 0) {
6862 pw.println(" ");
6863 pw.println("Recent tasks in Current Activity Manager State:");
6864
6865 final int N = mRecentTasks.size();
6866 for (int i=0; i<N; i++) {
6867 TaskRecord tr = mRecentTasks.get(i);
6868 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
6869 pw.println(tr);
6870 mRecentTasks.get(i).dump(pw, " ");
6871 }
6872 }
6873
6874 pw.println(" ");
6875 pw.println(" mCurTask: " + mCurTask);
6876
6877 return true;
6878 }
6879
6880 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
6881 int opti, boolean dumpAll) {
6882 boolean needSep = false;
6883 int numPers = 0;
6884
6885 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
6887 final int NA = procs.size();
6888 for (int ia=0; ia<NA; ia++) {
6889 if (!needSep) {
6890 pw.println(" All known processes:");
6891 needSep = true;
6892 }
6893 ProcessRecord r = procs.valueAt(ia);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006894 pw.print(r.persistent ? " *PERS*" : " *APP*");
6895 pw.print(" UID "); pw.print(procs.keyAt(ia));
6896 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006897 r.dump(pw, " ");
6898 if (r.persistent) {
6899 numPers++;
6900 }
6901 }
6902 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006903 }
6904
6905 if (mLruProcesses.size() > 0) {
6906 if (needSep) pw.println(" ");
6907 needSep = true;
6908 pw.println(" Running processes (most recent first):");
6909 dumpProcessList(pw, this, mLruProcesses, " ",
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006910 "Proc", "PERS", true);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006911 needSep = true;
6912 }
6913
6914 synchronized (mPidsSelfLocked) {
6915 if (mPidsSelfLocked.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006916 if (needSep) pw.println(" ");
6917 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006918 pw.println(" PID mappings:");
6919 for (int i=0; i<mPidsSelfLocked.size(); i++) {
6920 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
6921 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006922 }
6923 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006924 }
6925
6926 if (mForegroundProcesses.size() > 0) {
6927 if (needSep) pw.println(" ");
6928 needSep = true;
6929 pw.println(" Foreground Processes:");
6930 for (int i=0; i<mForegroundProcesses.size(); i++) {
6931 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
6932 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006933 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006934 }
6935
6936 if (mPersistentStartingProcesses.size() > 0) {
6937 if (needSep) pw.println(" ");
6938 needSep = true;
6939 pw.println(" Persisent processes that are starting:");
6940 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
6941 "Starting Norm", "Restarting PERS", false);
6942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006944 if (mStartingProcesses.size() > 0) {
6945 if (needSep) pw.println(" ");
6946 needSep = true;
6947 pw.println(" Processes that are starting:");
6948 dumpProcessList(pw, this, mStartingProcesses, " ",
6949 "Starting Norm", "Starting PERS", false);
6950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006952 if (mRemovedProcesses.size() > 0) {
6953 if (needSep) pw.println(" ");
6954 needSep = true;
6955 pw.println(" Processes that are being removed:");
6956 dumpProcessList(pw, this, mRemovedProcesses, " ",
6957 "Removed Norm", "Removed PERS", false);
6958 }
6959
6960 if (mProcessesOnHold.size() > 0) {
6961 if (needSep) pw.println(" ");
6962 needSep = true;
6963 pw.println(" Processes that are on old until the system is ready:");
6964 dumpProcessList(pw, this, mProcessesOnHold, " ",
6965 "OnHold Norm", "OnHold PERS", false);
6966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967
Dianne Hackbornc59411b2009-12-21 20:10:14 -08006968 if (mProcessesToGc.size() > 0) {
6969 if (needSep) pw.println(" ");
6970 needSep = true;
6971 pw.println(" Processes that are waiting to GC:");
6972 long now = SystemClock.uptimeMillis();
6973 for (int i=0; i<mProcessesToGc.size(); i++) {
6974 ProcessRecord proc = mProcessesToGc.get(i);
6975 pw.print(" Process "); pw.println(proc);
6976 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
6977 pw.print(", last gced=");
6978 pw.print(now-proc.lastRequestedGc);
6979 pw.print(" ms ago, last lowMem=");
6980 pw.print(now-proc.lastLowMemory);
6981 pw.println(" ms ago");
6982
6983 }
6984 }
6985
6986 if (mProcessCrashTimes.getMap().size() > 0) {
6987 if (needSep) pw.println(" ");
6988 needSep = true;
6989 pw.println(" Time since processes crashed:");
6990 long now = SystemClock.uptimeMillis();
6991 for (Map.Entry<String, SparseArray<Long>> procs
6992 : mProcessCrashTimes.getMap().entrySet()) {
6993 SparseArray<Long> uids = procs.getValue();
6994 final int N = uids.size();
6995 for (int i=0; i<N; i++) {
6996 pw.print(" Process "); pw.print(procs.getKey());
6997 pw.print(" uid "); pw.print(uids.keyAt(i));
6998 pw.print(": last crashed ");
6999 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07007000 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07007001 }
7002 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007004
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007005 if (mBadProcesses.getMap().size() > 0) {
7006 if (needSep) pw.println(" ");
7007 needSep = true;
7008 pw.println(" Bad processes:");
7009 for (Map.Entry<String, SparseArray<Long>> procs
7010 : mBadProcesses.getMap().entrySet()) {
7011 SparseArray<Long> uids = procs.getValue();
7012 final int N = uids.size();
7013 for (int i=0; i<N; i++) {
7014 pw.print(" Bad process "); pw.print(procs.getKey());
7015 pw.print(" uid "); pw.print(uids.keyAt(i));
7016 pw.print(": crashed at time ");
7017 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007018 }
7019 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007022 pw.println(" ");
7023 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackborn860755f2010-06-03 18:47:52 -07007024 if (mHeavyWeightProcess != null) {
7025 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7026 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007027 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007028 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007029 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
7030 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
7031 || mOrigWaitForDebugger) {
7032 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
7033 + " mDebugTransient=" + mDebugTransient
7034 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
7035 }
7036 if (mAlwaysFinishActivities || mController != null) {
7037 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
7038 + " mController=" + mController);
7039 }
7040 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007042 pw.println(" mStartRunning=" + mStartRunning
7043 + " mSystemReady=" + mSystemReady
7044 + " mBooting=" + mBooting
7045 + " mBooted=" + mBooted
7046 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007047 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
7048 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07007049 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007051
7052 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 }
7054
7055 /**
7056 * There are three ways to call this:
7057 * - no service specified: dump all the services
7058 * - a flattened component name that matched an existing service was specified as the
7059 * first arg: dump that one service
7060 * - the first arg isn't the flattened component name of an existing service:
7061 * dump all services whose component contains the first arg as a substring
7062 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007063 protected void dumpService(FileDescriptor fd, PrintWriter pw, String[] args,
7064 int opti, boolean dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007065 String[] newArgs;
7066 String componentNameString;
7067 ServiceRecord r;
Kenny Root3619b9ab2010-02-13 10:05:42 -08007068 if (opti >= args.length) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007069 componentNameString = null;
7070 newArgs = EMPTY_STRING_ARRAY;
7071 r = null;
7072 } else {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007073 componentNameString = args[opti];
7074 opti++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007075 ComponentName componentName = ComponentName.unflattenFromString(componentNameString);
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007076 synchronized (this) {
7077 r = componentName != null ? mServices.get(componentName) : null;
7078 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007079 newArgs = new String[args.length - opti];
7080 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 }
7082
7083 if (r != null) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007084 dumpService(fd, pw, r, newArgs, dumpAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007085 } else {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007086 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
7087 synchronized (this) {
7088 for (ServiceRecord r1 : mServices.values()) {
7089 if (componentNameString == null
7090 || r1.name.flattenToString().contains(componentNameString)) {
7091 services.add(r1);
7092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007093 }
7094 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007095 for (int i=0; i<services.size(); i++) {
7096 dumpService(fd, pw, services.get(i), newArgs, dumpAll);
7097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007098 }
7099 }
7100
7101 /**
7102 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
7103 * there is a thread associated with the service.
7104 */
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007105 private void dumpService(FileDescriptor fd, PrintWriter pw, ServiceRecord r, String[] args,
7106 boolean dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007107 pw.println(" Service " + r.name.flattenToString());
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007108 if (dumpAll) {
7109 synchronized (this) {
7110 pw.print(" * "); pw.println(r);
7111 r.dump(pw, " ");
7112 }
7113 pw.println("");
7114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007115 if (r.app != null && r.app.thread != null) {
7116 try {
7117 // flush anything that is already in the PrintWriter since the thread is going
7118 // to write to the file descriptor directly
7119 pw.flush();
7120 r.app.thread.dumpService(fd, r, args);
7121 pw.print("\n");
Dianne Hackborn14bfa392010-07-24 19:58:06 -07007122 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007123 } catch (RemoteException e) {
7124 pw.println("got a RemoteException while dumping the service");
7125 }
7126 }
7127 }
7128
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007129 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7130 int opti, boolean dumpAll) {
7131 boolean needSep = false;
7132
7133 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007134 if (mRegisteredReceivers.size() > 0) {
7135 pw.println(" ");
7136 pw.println(" Registered Receivers:");
7137 Iterator it = mRegisteredReceivers.values().iterator();
7138 while (it.hasNext()) {
7139 ReceiverList r = (ReceiverList)it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007140 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007141 r.dump(pw, " ");
7142 }
7143 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007145 pw.println(" ");
7146 pw.println("Receiver Resolver Table:");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007147 mReceiverResolver.dump(pw, null, " ", null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007148 needSep = true;
7149 }
7150
7151 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
7152 || mPendingBroadcast != null) {
7153 if (mParallelBroadcasts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007154 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007155 pw.println(" Active broadcasts:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007156 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007157 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
7158 pw.println(" Broadcast #" + i + ":");
7159 mParallelBroadcasts.get(i).dump(pw, " ");
7160 }
7161 if (mOrderedBroadcasts.size() > 0) {
7162 pw.println(" ");
Dianne Hackborn399cccb2010-04-13 22:57:49 -07007163 pw.println(" Active ordered broadcasts:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007164 }
7165 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
7166 pw.println(" Serialized Broadcast #" + i + ":");
7167 mOrderedBroadcasts.get(i).dump(pw, " ");
7168 }
7169 pw.println(" ");
7170 pw.println(" Pending broadcast:");
7171 if (mPendingBroadcast != null) {
7172 mPendingBroadcast.dump(pw, " ");
7173 } else {
7174 pw.println(" (null)");
7175 }
7176 needSep = true;
7177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007179 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007180 pw.println(" ");
Dianne Hackborn12527f92009-11-11 17:39:50 -08007181 pw.println(" Historical broadcasts:");
7182 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
7183 BroadcastRecord r = mBroadcastHistory[i];
7184 if (r == null) {
7185 break;
7186 }
7187 pw.println(" Historical Broadcast #" + i + ":");
7188 r.dump(pw, " ");
7189 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007190 needSep = true;
7191 }
7192
7193 if (mStickyBroadcasts != null) {
Dianne Hackborn12527f92009-11-11 17:39:50 -08007194 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007195 pw.println(" Sticky broadcasts:");
7196 StringBuilder sb = new StringBuilder(128);
7197 for (Map.Entry<String, ArrayList<Intent>> ent
7198 : mStickyBroadcasts.entrySet()) {
7199 pw.print(" * Sticky action "); pw.print(ent.getKey());
7200 pw.println(":");
7201 ArrayList<Intent> intents = ent.getValue();
7202 final int N = intents.size();
7203 for (int i=0; i<N; i++) {
7204 sb.setLength(0);
7205 sb.append(" Intent: ");
7206 intents.get(i).toShortString(sb, true, false);
7207 pw.println(sb.toString());
7208 Bundle bundle = intents.get(i).getExtras();
7209 if (bundle != null) {
7210 pw.print(" ");
7211 pw.println(bundle.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212 }
7213 }
7214 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007215 needSep = true;
7216 }
7217
7218 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007220 pw.println(" mBroadcastsScheduled=" + mBroadcastsScheduled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007221 pw.println(" mHandler:");
7222 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007223 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007225
7226 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007227 }
7228
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007229 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7230 int opti, boolean dumpAll) {
7231 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007232
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007233 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 if (mServices.size() > 0) {
7235 pw.println(" Active services:");
7236 Iterator<ServiceRecord> it = mServices.values().iterator();
7237 while (it.hasNext()) {
7238 ServiceRecord r = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007239 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007240 r.dump(pw, " ");
7241 }
7242 needSep = true;
7243 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007245
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007246 if (mPendingServices.size() > 0) {
7247 if (needSep) pw.println(" ");
7248 pw.println(" Pending services:");
7249 for (int i=0; i<mPendingServices.size(); i++) {
7250 ServiceRecord r = mPendingServices.get(i);
7251 pw.print(" * Pending "); pw.println(r);
7252 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007253 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007254 needSep = true;
7255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007256
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007257 if (mRestartingServices.size() > 0) {
7258 if (needSep) pw.println(" ");
7259 pw.println(" Restarting services:");
7260 for (int i=0; i<mRestartingServices.size(); i++) {
7261 ServiceRecord r = mRestartingServices.get(i);
7262 pw.print(" * Restarting "); pw.println(r);
7263 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007264 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007265 needSep = true;
7266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007267
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007268 if (mStoppingServices.size() > 0) {
7269 if (needSep) pw.println(" ");
7270 pw.println(" Stopping services:");
7271 for (int i=0; i<mStoppingServices.size(); i++) {
7272 ServiceRecord r = mStoppingServices.get(i);
7273 pw.print(" * Stopping "); pw.println(r);
7274 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007275 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007276 needSep = true;
7277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007278
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007279 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007280 if (mServiceConnections.size() > 0) {
7281 if (needSep) pw.println(" ");
7282 pw.println(" Connection bindings to services:");
7283 Iterator<ConnectionRecord> it
7284 = mServiceConnections.values().iterator();
7285 while (it.hasNext()) {
7286 ConnectionRecord r = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007287 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288 r.dump(pw, " ");
7289 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007290 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007291 }
7292 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007293
7294 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 }
7296
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007297 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7298 int opti, boolean dumpAll) {
7299 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007300
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007301 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007302 if (mProvidersByClass.size() > 0) {
7303 if (needSep) pw.println(" ");
7304 pw.println(" Published content providers (by class):");
Dianne Hackborn860755f2010-06-03 18:47:52 -07007305 Iterator<Map.Entry<String, ContentProviderRecord>> it
7306 = mProvidersByClass.entrySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007307 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007308 Map.Entry<String, ContentProviderRecord> e = it.next();
7309 ContentProviderRecord r = e.getValue();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007310 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007311 r.dump(pw, " ");
7312 }
7313 needSep = true;
7314 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007315
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007316 if (mProvidersByName.size() > 0) {
7317 pw.println(" ");
7318 pw.println(" Authority to provider mappings:");
Dianne Hackborn860755f2010-06-03 18:47:52 -07007319 Iterator<Map.Entry<String, ContentProviderRecord>> it
7320 = mProvidersByName.entrySet().iterator();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007321 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007322 Map.Entry<String, ContentProviderRecord> e = it.next();
7323 ContentProviderRecord r = e.getValue();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007324 pw.print(" "); pw.print(e.getKey()); pw.print(": ");
7325 pw.println(r);
7326 }
7327 needSep = true;
7328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007330
7331 if (mLaunchingProviders.size() > 0) {
7332 if (needSep) pw.println(" ");
7333 pw.println(" Launching content providers:");
7334 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
7335 pw.print(" Launching #"); pw.print(i); pw.print(": ");
7336 pw.println(mLaunchingProviders.get(i));
7337 }
7338 needSep = true;
7339 }
7340
7341 if (mGrantedUriPermissions.size() > 0) {
7342 pw.println();
7343 pw.println("Granted Uri Permissions:");
7344 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
7345 int uid = mGrantedUriPermissions.keyAt(i);
7346 HashMap<Uri, UriPermission> perms
7347 = mGrantedUriPermissions.valueAt(i);
7348 pw.print(" * UID "); pw.print(uid);
7349 pw.println(" holds:");
7350 for (UriPermission perm : perms.values()) {
7351 pw.print(" "); pw.println(perm);
7352 perm.dump(pw, " ");
7353 }
7354 }
7355 needSep = true;
7356 }
7357
7358 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007359 }
7360
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007361 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
7362 int opti, boolean dumpAll) {
7363 boolean needSep = false;
7364
7365 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007366 if (this.mIntentSenderRecords.size() > 0) {
7367 Iterator<WeakReference<PendingIntentRecord>> it
7368 = mIntentSenderRecords.values().iterator();
7369 while (it.hasNext()) {
7370 WeakReference<PendingIntentRecord> ref = it.next();
7371 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007372 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373 if (rec != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007374 pw.print(" * "); pw.println(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007375 rec.dump(pw, " ");
7376 } else {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007377 pw.print(" * "); pw.print(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007378 }
7379 }
7380 }
7381 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08007382
7383 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007384 }
7385
7386 private static final void dumpHistoryList(PrintWriter pw, List list,
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07007387 String prefix, String label, boolean complete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007388 TaskRecord lastTask = null;
7389 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007390 ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007391 final boolean full = complete || !r.inHistory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 if (lastTask != r.task) {
7393 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007394 pw.print(prefix);
7395 pw.print(full ? "* " : " ");
7396 pw.println(lastTask);
7397 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07007398 lastTask.dump(pw, prefix + " ");
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07007399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007400 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007401 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
7402 pw.print(" #"); pw.print(i); pw.print(": ");
7403 pw.println(r);
7404 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07007405 r.dump(pw, prefix + " ");
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07007406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007407 }
7408 }
7409
Dianne Hackborn09c916b2009-12-08 14:50:51 -08007410 private static String buildOomTag(String prefix, String space, int val, int base) {
7411 if (val == base) {
7412 if (space == null) return prefix;
7413 return prefix + " ";
7414 }
7415 return prefix + "+" + Integer.toString(val-base);
7416 }
7417
7418 private static final int dumpProcessList(PrintWriter pw,
7419 ActivityManagerService service, List list,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007420 String prefix, String normalLabel, String persistentLabel,
7421 boolean inclOomAdj) {
7422 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07007423 final int N = list.size()-1;
7424 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007425 ProcessRecord r = (ProcessRecord)list.get(i);
7426 if (false) {
7427 pw.println(prefix + (r.persistent ? persistentLabel : normalLabel)
7428 + " #" + i + ":");
7429 r.dump(pw, prefix + " ");
7430 } else if (inclOomAdj) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -08007431 String oomAdj;
7432 if (r.setAdj >= EMPTY_APP_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007433 oomAdj = buildOomTag("empty", null, r.setAdj, EMPTY_APP_ADJ);
Dianne Hackborn09c916b2009-12-08 14:50:51 -08007434 } else if (r.setAdj >= HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007435 oomAdj = buildOomTag("bak", " ", r.setAdj, HIDDEN_APP_MIN_ADJ);
7436 } else if (r.setAdj >= HOME_APP_ADJ) {
7437 oomAdj = buildOomTag("home ", null, r.setAdj, HOME_APP_ADJ);
7438 } else if (r.setAdj >= SECONDARY_SERVER_ADJ) {
7439 oomAdj = buildOomTag("svc", " ", r.setAdj, SECONDARY_SERVER_ADJ);
7440 } else if (r.setAdj >= BACKUP_APP_ADJ) {
7441 oomAdj = buildOomTag("bckup", null, r.setAdj, BACKUP_APP_ADJ);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07007442 } else if (r.setAdj >= HEAVY_WEIGHT_APP_ADJ) {
7443 oomAdj = buildOomTag("hvy ", null, r.setAdj, HEAVY_WEIGHT_APP_ADJ);
7444 } else if (r.setAdj >= PERCEPTIBLE_APP_ADJ) {
7445 oomAdj = buildOomTag("prcp ", null, r.setAdj, PERCEPTIBLE_APP_ADJ);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007446 } else if (r.setAdj >= VISIBLE_APP_ADJ) {
7447 oomAdj = buildOomTag("vis ", null, r.setAdj, VISIBLE_APP_ADJ);
7448 } else if (r.setAdj >= FOREGROUND_APP_ADJ) {
7449 oomAdj = buildOomTag("fore ", null, r.setAdj, FOREGROUND_APP_ADJ);
Dianne Hackborn09c916b2009-12-08 14:50:51 -08007450 } else if (r.setAdj >= CORE_SERVER_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007451 oomAdj = buildOomTag("core ", null, r.setAdj, CORE_SERVER_ADJ);
Dianne Hackborn09c916b2009-12-08 14:50:51 -08007452 } else if (r.setAdj >= SYSTEM_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007453 oomAdj = buildOomTag("sys ", null, r.setAdj, SYSTEM_ADJ);
Dianne Hackborn09c916b2009-12-08 14:50:51 -08007454 } else {
7455 oomAdj = Integer.toString(r.setAdj);
7456 }
7457 String schedGroup;
7458 switch (r.setSchedGroup) {
7459 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
7460 schedGroup = "B";
7461 break;
7462 case Process.THREAD_GROUP_DEFAULT:
7463 schedGroup = "F";
7464 break;
7465 default:
7466 schedGroup = Integer.toString(r.setSchedGroup);
7467 break;
7468 }
7469 pw.println(String.format("%s%s #%2d: adj=%s/%s %s (%s)",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007470 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackborn32907cf2010-06-10 17:50:20 -07007471 N-i, oomAdj, schedGroup, r.toShortString(), r.adjType));
Dianne Hackbornde42bb62009-08-05 12:26:15 -07007472 if (r.adjSource != null || r.adjTarget != null) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07007473 pw.print(prefix);
7474 pw.print(" ");
7475 if (r.adjTarget instanceof ComponentName) {
7476 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
7477 } else if (r.adjTarget != null) {
7478 pw.print(r.adjTarget.toString());
7479 } else {
7480 pw.print("{null}");
7481 }
7482 pw.print("<=");
7483 if (r.adjSource instanceof ProcessRecord) {
7484 pw.print("Proc{");
7485 pw.print(((ProcessRecord)r.adjSource).toShortString());
7486 pw.println("}");
7487 } else if (r.adjSource != null) {
7488 pw.println(r.adjSource.toString());
7489 } else {
7490 pw.println("{null}");
7491 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -07007492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007493 } else {
7494 pw.println(String.format("%s%s #%2d: %s",
7495 prefix, (r.persistent ? persistentLabel : normalLabel),
7496 i, r.toString()));
7497 }
7498 if (r.persistent) {
7499 numPers++;
7500 }
7501 }
7502 return numPers;
7503 }
7504
Dianne Hackborn472ad872010-04-07 17:31:48 -07007505 static final void dumpApplicationMemoryUsage(FileDescriptor fd,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 PrintWriter pw, List list, String prefix, String[] args) {
Dianne Hackborn6447ca32009-04-07 19:50:08 -07007507 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007508 long uptime = SystemClock.uptimeMillis();
7509 long realtime = SystemClock.elapsedRealtime();
7510
7511 if (isCheckinRequest) {
7512 // short checkin version
7513 pw.println(uptime + "," + realtime);
7514 pw.flush();
7515 } else {
7516 pw.println("Applications Memory Usage (kB):");
7517 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
7518 }
7519 for (int i = list.size() - 1 ; i >= 0 ; i--) {
7520 ProcessRecord r = (ProcessRecord)list.get(i);
7521 if (r.thread != null) {
7522 if (!isCheckinRequest) {
7523 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
7524 pw.flush();
7525 }
7526 try {
7527 r.thread.asBinder().dump(fd, args);
7528 } catch (RemoteException e) {
7529 if (!isCheckinRequest) {
7530 pw.println("Got RemoteException!");
7531 pw.flush();
7532 }
7533 }
7534 }
7535 }
7536 }
7537
7538 /**
7539 * Searches array of arguments for the specified string
7540 * @param args array of argument strings
7541 * @param value value to search for
7542 * @return true if the value is contained in the array
7543 */
7544 private static boolean scanArgs(String[] args, String value) {
7545 if (args != null) {
7546 for (String arg : args) {
7547 if (value.equals(arg)) {
7548 return true;
7549 }
7550 }
7551 }
7552 return false;
7553 }
7554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007555 private final void killServicesLocked(ProcessRecord app,
7556 boolean allowRestart) {
7557 // Report disconnected services.
7558 if (false) {
7559 // XXX we are letting the client link to the service for
7560 // death notifications.
7561 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007562 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007563 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007564 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007565 if (r.connections.size() > 0) {
7566 Iterator<ConnectionRecord> jt
7567 = r.connections.values().iterator();
7568 while (jt.hasNext()) {
7569 ConnectionRecord c = jt.next();
7570 if (c.binding.client != app) {
7571 try {
7572 //c.conn.connected(r.className, null);
7573 } catch (Exception e) {
7574 // todo: this should be asynchronous!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007575 Slog.w(TAG, "Exception thrown disconnected servce "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007576 + r.shortName
7577 + " from app " + app.processName, e);
7578 }
7579 }
7580 }
7581 }
7582 }
7583 }
7584 }
7585
7586 // Clean up any connections this application has to other services.
7587 if (app.connections.size() > 0) {
7588 Iterator<ConnectionRecord> it = app.connections.iterator();
7589 while (it.hasNext()) {
7590 ConnectionRecord r = it.next();
7591 removeConnectionLocked(r, app, null);
7592 }
7593 }
7594 app.connections.clear();
7595
7596 if (app.services.size() != 0) {
7597 // Any services running in the application need to be placed
7598 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007599 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007601 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007602 synchronized (sr.stats.getBatteryStats()) {
7603 sr.stats.stopLaunchedLocked();
7604 }
7605 sr.app = null;
7606 sr.executeNesting = 0;
7607 mStoppingServices.remove(sr);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07007608
7609 boolean hasClients = sr.bindings.size() > 0;
7610 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 Iterator<IntentBindRecord> bindings
7612 = sr.bindings.values().iterator();
7613 while (bindings.hasNext()) {
7614 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007615 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 + ": shouldUnbind=" + b.hasBound);
7617 b.binder = null;
7618 b.requested = b.received = b.hasBound = false;
7619 }
7620 }
7621
7622 if (sr.crashCount >= 2) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007623 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -08007625 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007626 sr.crashCount, sr.shortName, app.pid);
7627 bringDownServiceLocked(sr, true);
7628 } else if (!allowRestart) {
7629 bringDownServiceLocked(sr, true);
7630 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07007631 boolean canceled = scheduleServiceRestartLocked(sr, true);
7632
7633 // Should the service remain running? Note that in the
7634 // extreme case of so many attempts to deliver a command
7635 // that it failed, that we also will stop it here.
7636 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
7637 if (sr.pendingStarts.size() == 0) {
7638 sr.startRequested = false;
7639 if (!hasClients) {
7640 // Whoops, no reason to restart!
7641 bringDownServiceLocked(sr, true);
7642 }
7643 }
7644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 }
7646 }
7647
7648 if (!allowRestart) {
7649 app.services.clear();
7650 }
7651 }
7652
Dianne Hackbornde42bb62009-08-05 12:26:15 -07007653 // Make sure we have no more records on the stopping list.
7654 int i = mStoppingServices.size();
7655 while (i > 0) {
7656 i--;
7657 ServiceRecord sr = mStoppingServices.get(i);
7658 if (sr.app == app) {
7659 mStoppingServices.remove(i);
7660 }
7661 }
7662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007663 app.executingServices.clear();
7664 }
7665
7666 private final void removeDyingProviderLocked(ProcessRecord proc,
7667 ContentProviderRecord cpr) {
7668 synchronized (cpr) {
7669 cpr.launchingApp = null;
7670 cpr.notifyAll();
7671 }
7672
7673 mProvidersByClass.remove(cpr.info.name);
7674 String names[] = cpr.info.authority.split(";");
7675 for (int j = 0; j < names.length; j++) {
7676 mProvidersByName.remove(names[j]);
7677 }
7678
7679 Iterator<ProcessRecord> cit = cpr.clients.iterator();
7680 while (cit.hasNext()) {
7681 ProcessRecord capp = cit.next();
7682 if (!capp.persistent && capp.thread != null
7683 && capp.pid != 0
7684 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007685 Slog.i(TAG, "Kill " + capp.processName
7686 + " (pid " + capp.pid + "): provider " + cpr.info.name
7687 + " in dying process " + proc.processName);
7688 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
7689 capp.processName, capp.setAdj, "dying provider " + proc.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 Process.killProcess(capp.pid);
7691 }
7692 }
7693
7694 mLaunchingProviders.remove(cpr);
7695 }
7696
7697 /**
7698 * Main code for cleaning up a process when it has gone away. This is
7699 * called both as a result of the process dying, or directly when stopping
7700 * a process when running in single process mode.
7701 */
7702 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
7703 boolean restarting, int index) {
7704 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007705 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007706 }
7707
Dianne Hackborn36124872009-10-08 16:22:03 -07007708 mProcessesToGc.remove(app);
7709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 // Dismiss any open dialogs.
7711 if (app.crashDialog != null) {
7712 app.crashDialog.dismiss();
7713 app.crashDialog = null;
7714 }
7715 if (app.anrDialog != null) {
7716 app.anrDialog.dismiss();
7717 app.anrDialog = null;
7718 }
7719 if (app.waitDialog != null) {
7720 app.waitDialog.dismiss();
7721 app.waitDialog = null;
7722 }
7723
7724 app.crashing = false;
7725 app.notResponding = false;
7726
7727 app.resetPackageList();
7728 app.thread = null;
7729 app.forcingToForeground = null;
7730 app.foregroundServices = false;
7731
7732 killServicesLocked(app, true);
7733
7734 boolean restart = false;
7735
7736 int NL = mLaunchingProviders.size();
7737
7738 // Remove published content providers.
7739 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007740 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007742 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743 cpr.provider = null;
7744 cpr.app = null;
7745
7746 // See if someone is waiting for this provider... in which
7747 // case we don't remove it, but just let it restart.
7748 int i = 0;
7749 if (!app.bad) {
7750 for (; i<NL; i++) {
7751 if (mLaunchingProviders.get(i) == cpr) {
7752 restart = true;
7753 break;
7754 }
7755 }
7756 } else {
7757 i = NL;
7758 }
7759
7760 if (i >= NL) {
7761 removeDyingProviderLocked(app, cpr);
7762 NL = mLaunchingProviders.size();
7763 }
7764 }
7765 app.pubProviders.clear();
7766 }
7767
Dianne Hackbornf670ef72009-11-16 13:59:16 -08007768 // Take care of any launching providers waiting for this process.
7769 if (checkAppInLaunchingProvidersLocked(app, false)) {
7770 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08007772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 // Unregister from connected content providers.
7774 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07007775 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 while (it.hasNext()) {
7777 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
7778 cpr.clients.remove(app);
7779 }
7780 app.conProviders.clear();
7781 }
7782
Dianne Hackbornde42bb62009-08-05 12:26:15 -07007783 // At this point there may be remaining entries in mLaunchingProviders
7784 // where we were the only one waiting, so they are no longer of use.
7785 // Look for these and clean up if found.
7786 // XXX Commented out for now. Trying to figure out a way to reproduce
7787 // the actual situation to identify what is actually going on.
7788 if (false) {
7789 for (int i=0; i<NL; i++) {
7790 ContentProviderRecord cpr = (ContentProviderRecord)
7791 mLaunchingProviders.get(i);
7792 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
7793 synchronized (cpr) {
7794 cpr.launchingApp = null;
7795 cpr.notifyAll();
7796 }
7797 }
7798 }
7799 }
7800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 skipCurrentReceiverLocked(app);
7802
7803 // Unregister any receivers.
7804 if (app.receivers.size() > 0) {
7805 Iterator<ReceiverList> it = app.receivers.iterator();
7806 while (it.hasNext()) {
7807 removeReceiverLocked(it.next());
7808 }
7809 app.receivers.clear();
7810 }
7811
Christopher Tate181fafa2009-05-14 11:12:14 -07007812 // If the app is undergoing backup, tell the backup manager about it
7813 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007814 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -07007815 try {
7816 IBackupManager bm = IBackupManager.Stub.asInterface(
7817 ServiceManager.getService(Context.BACKUP_SERVICE));
7818 bm.agentDisconnected(app.info.packageName);
7819 } catch (RemoteException e) {
7820 // can't happen; backup manager is local
7821 }
7822 }
7823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 // If the caller is restarting this app, then leave it in its
7825 // current lists and let the caller take care of it.
7826 if (restarting) {
7827 return;
7828 }
7829
7830 if (!app.persistent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007831 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007832 "Removing non-persistent process during cleanup: " + app);
7833 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07007834 if (mHeavyWeightProcess == app) {
7835 mHeavyWeightProcess = null;
7836 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
7837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007838 } else if (!app.removed) {
7839 // This app is persistent, so we need to keep its record around.
7840 // If it is not already on the pending app list, add it there
7841 // and start a new process for it.
7842 app.thread = null;
7843 app.forcingToForeground = null;
7844 app.foregroundServices = false;
7845 if (mPersistentStartingProcesses.indexOf(app) < 0) {
7846 mPersistentStartingProcesses.add(app);
7847 restart = true;
7848 }
7849 }
7850 mProcessesOnHold.remove(app);
7851
The Android Open Source Project4df24232009-03-05 14:34:35 -08007852 if (app == mHomeProcess) {
7853 mHomeProcess = null;
7854 }
7855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 if (restart) {
7857 // We have components that still need to be running in the
7858 // process, so re-launch it.
7859 mProcessNames.put(app.processName, app.info.uid, app);
7860 startProcessLocked(app, "restart", app.processName);
7861 } else if (app.pid > 0 && app.pid != MY_PID) {
7862 // Goodbye!
7863 synchronized (mPidsSelfLocked) {
7864 mPidsSelfLocked.remove(app.pid);
7865 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
7866 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07007867 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007868 }
7869 }
7870
Dianne Hackbornf670ef72009-11-16 13:59:16 -08007871 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
7872 // Look through the content providers we are waiting to have launched,
7873 // and if any run in this process then either schedule a restart of
7874 // the process or kill the client waiting for it if this process has
7875 // gone bad.
7876 int NL = mLaunchingProviders.size();
7877 boolean restart = false;
7878 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007879 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08007880 if (cpr.launchingApp == app) {
7881 if (!alwaysBad && !app.bad) {
7882 restart = true;
7883 } else {
7884 removeDyingProviderLocked(app, cpr);
7885 NL = mLaunchingProviders.size();
7886 }
7887 }
7888 }
7889 return restart;
7890 }
7891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 // =========================================================
7893 // SERVICES
7894 // =========================================================
7895
7896 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
7897 ActivityManager.RunningServiceInfo info =
7898 new ActivityManager.RunningServiceInfo();
7899 info.service = r.name;
7900 if (r.app != null) {
7901 info.pid = r.app.pid;
7902 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -07007903 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007904 info.process = r.processName;
7905 info.foreground = r.isForeground;
7906 info.activeSince = r.createTime;
7907 info.started = r.startRequested;
7908 info.clientCount = r.connections.size();
7909 info.crashCount = r.crashCount;
7910 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07007911 if (r.isForeground) {
7912 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
7913 }
7914 if (r.startRequested) {
7915 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
7916 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007917 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -07007918 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
7919 }
7920 if (r.app != null && r.app.persistent) {
7921 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
7922 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007923 for (ConnectionRecord conn : r.connections.values()) {
7924 if (conn.clientLabel != 0) {
7925 info.clientPackage = conn.binding.client.info.packageName;
7926 info.clientLabel = conn.clientLabel;
7927 break;
7928 }
7929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007930 return info;
7931 }
7932
7933 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
7934 int flags) {
7935 synchronized (this) {
7936 ArrayList<ActivityManager.RunningServiceInfo> res
7937 = new ArrayList<ActivityManager.RunningServiceInfo>();
7938
7939 if (mServices.size() > 0) {
7940 Iterator<ServiceRecord> it = mServices.values().iterator();
7941 while (it.hasNext() && res.size() < maxNum) {
7942 res.add(makeRunningServiceInfoLocked(it.next()));
7943 }
7944 }
7945
7946 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
7947 ServiceRecord r = mRestartingServices.get(i);
7948 ActivityManager.RunningServiceInfo info =
7949 makeRunningServiceInfoLocked(r);
7950 info.restarting = r.nextRestartTime;
7951 res.add(info);
7952 }
7953
7954 return res;
7955 }
7956 }
7957
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007958 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
7959 synchronized (this) {
7960 ServiceRecord r = mServices.get(name);
7961 if (r != null) {
7962 for (ConnectionRecord conn : r.connections.values()) {
7963 if (conn.clientIntent != null) {
7964 return conn.clientIntent;
7965 }
7966 }
7967 }
7968 }
7969 return null;
7970 }
7971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 private final ServiceRecord findServiceLocked(ComponentName name,
7973 IBinder token) {
7974 ServiceRecord r = mServices.get(name);
7975 return r == token ? r : null;
7976 }
7977
7978 private final class ServiceLookupResult {
7979 final ServiceRecord record;
7980 final String permission;
7981
7982 ServiceLookupResult(ServiceRecord _record, String _permission) {
7983 record = _record;
7984 permission = _permission;
7985 }
7986 };
7987
7988 private ServiceLookupResult findServiceLocked(Intent service,
7989 String resolvedType) {
7990 ServiceRecord r = null;
7991 if (service.getComponent() != null) {
7992 r = mServices.get(service.getComponent());
7993 }
7994 if (r == null) {
7995 Intent.FilterComparison filter = new Intent.FilterComparison(service);
7996 r = mServicesByIntent.get(filter);
7997 }
7998
7999 if (r == null) {
8000 try {
8001 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008002 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008003 service, resolvedType, 0);
8004 ServiceInfo sInfo =
8005 rInfo != null ? rInfo.serviceInfo : null;
8006 if (sInfo == null) {
8007 return null;
8008 }
8009
8010 ComponentName name = new ComponentName(
8011 sInfo.applicationInfo.packageName, sInfo.name);
8012 r = mServices.get(name);
8013 } catch (RemoteException ex) {
8014 // pm is in same process, this will never happen.
8015 }
8016 }
8017 if (r != null) {
8018 int callingPid = Binder.getCallingPid();
8019 int callingUid = Binder.getCallingUid();
8020 if (checkComponentPermission(r.permission,
8021 callingPid, callingUid, r.exported ? -1 : r.appInfo.uid)
8022 != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008023 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 + " from pid=" + callingPid
8025 + ", uid=" + callingUid
8026 + " requires " + r.permission);
8027 return new ServiceLookupResult(null, r.permission);
8028 }
8029 return new ServiceLookupResult(r, null);
8030 }
8031 return null;
8032 }
8033
8034 private class ServiceRestarter implements Runnable {
8035 private ServiceRecord mService;
8036
8037 void setService(ServiceRecord service) {
8038 mService = service;
8039 }
8040
8041 public void run() {
8042 synchronized(ActivityManagerService.this) {
8043 performServiceRestartLocked(mService);
8044 }
8045 }
8046 }
8047
8048 private ServiceLookupResult retrieveServiceLocked(Intent service,
8049 String resolvedType, int callingPid, int callingUid) {
8050 ServiceRecord r = null;
8051 if (service.getComponent() != null) {
8052 r = mServices.get(service.getComponent());
8053 }
8054 Intent.FilterComparison filter = new Intent.FilterComparison(service);
8055 r = mServicesByIntent.get(filter);
8056 if (r == null) {
8057 try {
8058 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008059 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -07008060 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008061 ServiceInfo sInfo =
8062 rInfo != null ? rInfo.serviceInfo : null;
8063 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008064 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008065 ": not found");
8066 return null;
8067 }
8068
8069 ComponentName name = new ComponentName(
8070 sInfo.applicationInfo.packageName, sInfo.name);
8071 r = mServices.get(name);
8072 if (r == null) {
8073 filter = new Intent.FilterComparison(service.cloneFilter());
8074 ServiceRestarter res = new ServiceRestarter();
8075 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
8076 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
8077 synchronized (stats) {
8078 ss = stats.getServiceStatsLocked(
8079 sInfo.applicationInfo.uid, sInfo.packageName,
8080 sInfo.name);
8081 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -08008082 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 res.setService(r);
8084 mServices.put(name, r);
8085 mServicesByIntent.put(filter, r);
8086
8087 // Make sure this component isn't in the pending list.
8088 int N = mPendingServices.size();
8089 for (int i=0; i<N; i++) {
8090 ServiceRecord pr = mPendingServices.get(i);
8091 if (pr.name.equals(name)) {
8092 mPendingServices.remove(i);
8093 i--;
8094 N--;
8095 }
8096 }
8097 }
8098 } catch (RemoteException ex) {
8099 // pm is in same process, this will never happen.
8100 }
8101 }
8102 if (r != null) {
8103 if (checkComponentPermission(r.permission,
8104 callingPid, callingUid, r.exported ? -1 : r.appInfo.uid)
8105 != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008106 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008107 + " from pid=" + Binder.getCallingPid()
8108 + ", uid=" + Binder.getCallingUid()
8109 + " requires " + r.permission);
8110 return new ServiceLookupResult(null, r.permission);
8111 }
8112 return new ServiceLookupResult(r, null);
8113 }
8114 return null;
8115 }
8116
8117 private final void bumpServiceExecutingLocked(ServiceRecord r) {
8118 long now = SystemClock.uptimeMillis();
8119 if (r.executeNesting == 0 && r.app != null) {
8120 if (r.app.executingServices.size() == 0) {
8121 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
8122 msg.obj = r.app;
8123 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
8124 }
8125 r.app.executingServices.add(r);
8126 }
8127 r.executeNesting++;
8128 r.executingStart = now;
8129 }
8130
8131 private final void sendServiceArgsLocked(ServiceRecord r,
8132 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008133 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008134 if (N == 0) {
8135 return;
8136 }
8137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 int i = 0;
8139 while (i < N) {
8140 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008141 ServiceRecord.StartItem si = r.pendingStarts.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08008142 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to service: "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008143 + r.name + " " + r.intent + " args=" + si.intent);
Dianne Hackbornfed534e2009-09-23 00:42:12 -07008144 if (si.intent == null && N > 1) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008145 // If somehow we got a dummy start at the front, then
8146 // just drop it here.
8147 i++;
8148 continue;
8149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 bumpServiceExecutingLocked(r);
8151 if (!oomAdjusted) {
8152 oomAdjusted = true;
8153 updateOomAdjLocked(r.app);
8154 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008155 int flags = 0;
8156 if (si.deliveryCount > 0) {
8157 flags |= Service.START_FLAG_RETRY;
8158 }
8159 if (si.doneExecutingCount > 0) {
8160 flags |= Service.START_FLAG_REDELIVERY;
8161 }
8162 r.app.thread.scheduleServiceArgs(r, si.id, flags, si.intent);
8163 si.deliveredTime = SystemClock.uptimeMillis();
8164 r.deliveredStarts.add(si);
8165 si.deliveryCount++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008166 i++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008167 } catch (RemoteException e) {
8168 // Remote process gone... we'll let the normal cleanup take
8169 // care of this.
8170 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008171 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008172 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 break;
8174 }
8175 }
8176 if (i == N) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008177 r.pendingStarts.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008178 } else {
8179 while (i > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008180 i--;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008181 r.pendingStarts.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008182 }
8183 }
8184 }
8185
8186 private final boolean requestServiceBindingLocked(ServiceRecord r,
8187 IntentBindRecord i, boolean rebind) {
8188 if (r.app == null || r.app.thread == null) {
8189 // If service is not currently running, can't yet bind.
8190 return false;
8191 }
8192 if ((!i.requested || rebind) && i.apps.size() > 0) {
8193 try {
8194 bumpServiceExecutingLocked(r);
Joe Onorato8a9b2202010-02-26 18:56:32 -08008195 if (DEBUG_SERVICE) Slog.v(TAG, "Connecting binding " + i
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008196 + ": shouldUnbind=" + i.hasBound);
8197 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
8198 if (!rebind) {
8199 i.requested = true;
8200 }
8201 i.hasBound = true;
8202 i.doRebind = false;
8203 } catch (RemoteException e) {
8204 return false;
8205 }
8206 }
8207 return true;
8208 }
8209
8210 private final void requestServiceBindingsLocked(ServiceRecord r) {
8211 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
8212 while (bindings.hasNext()) {
8213 IntentBindRecord i = bindings.next();
8214 if (!requestServiceBindingLocked(r, i, false)) {
8215 break;
8216 }
8217 }
8218 }
8219
8220 private final void realStartServiceLocked(ServiceRecord r,
8221 ProcessRecord app) throws RemoteException {
8222 if (app.thread == null) {
8223 throw new RemoteException();
8224 }
8225
8226 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -07008227 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228
8229 app.services.add(r);
8230 bumpServiceExecutingLocked(r);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008231 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008232
8233 boolean created = false;
8234 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008235 if (DEBUG_SERVICE) Slog.v(TAG, "Scheduling start service: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008236 + r.name + " " + r.intent);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008237 mStringBuilder.setLength(0);
8238 r.intent.getIntent().toShortString(mStringBuilder, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -08008239 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008240 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008241 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008242 synchronized (r.stats.getBatteryStats()) {
8243 r.stats.startLaunchedLocked();
8244 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07008245 ensurePackageDexOpt(r.serviceInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008246 app.thread.scheduleCreateService(r, r.serviceInfo);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07008247 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008248 created = true;
8249 } finally {
8250 if (!created) {
8251 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008252 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008253 }
8254 }
8255
8256 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008257
8258 // If the service is in the started state, and there are no
8259 // pending arguments, then fake up one so its onStartCommand() will
8260 // be called.
8261 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
8262 r.lastStartId++;
8263 if (r.lastStartId < 1) {
8264 r.lastStartId = 1;
8265 }
8266 r.pendingStarts.add(new ServiceRecord.StartItem(r.lastStartId, null));
8267 }
8268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008269 sendServiceArgsLocked(r, true);
8270 }
8271
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008272 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
8273 boolean allowCancel) {
8274 boolean canceled = false;
8275
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008276 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008277 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -07008278 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008279
8280 // Any delivered but not yet finished starts should be put back
8281 // on the pending list.
8282 final int N = r.deliveredStarts.size();
8283 if (N > 0) {
8284 for (int i=N-1; i>=0; i--) {
8285 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
8286 if (si.intent == null) {
8287 // We'll generate this again if needed.
8288 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
8289 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
8290 r.pendingStarts.add(0, si);
8291 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
8292 dur *= 2;
8293 if (minDuration < dur) minDuration = dur;
8294 if (resetTime < dur) resetTime = dur;
8295 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008296 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008297 + r.name);
8298 canceled = true;
8299 }
8300 }
8301 r.deliveredStarts.clear();
8302 }
8303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 r.totalRestartCount++;
8305 if (r.restartDelay == 0) {
8306 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008307 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008308 } else {
8309 // If it has been a "reasonably long time" since the service
8310 // was started, then reset our restart duration back to
8311 // the beginning, so we don't infinitely increase the duration
8312 // on a service that just occasionally gets killed (which is
8313 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008314 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008315 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008316 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008317 } else {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008318 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008319 if (r.restartDelay < minDuration) {
8320 r.restartDelay = minDuration;
8321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008322 }
8323 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008324
8325 r.nextRestartTime = now + r.restartDelay;
8326
8327 // Make sure that we don't end up restarting a bunch of services
8328 // all at the same time.
8329 boolean repeat;
8330 do {
8331 repeat = false;
8332 for (int i=mRestartingServices.size()-1; i>=0; i--) {
8333 ServiceRecord r2 = mRestartingServices.get(i);
8334 if (r2 != r && r.nextRestartTime
8335 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
8336 && r.nextRestartTime
8337 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
8338 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
8339 r.restartDelay = r.nextRestartTime - now;
8340 repeat = true;
8341 break;
8342 }
8343 }
8344 } while (repeat);
8345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 if (!mRestartingServices.contains(r)) {
8347 mRestartingServices.add(r);
8348 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008349
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07008350 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008353 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008354 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -08008355 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008356 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008357 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008358 r.shortName, r.restartDelay);
8359
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008360 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008361 }
8362
8363 final void performServiceRestartLocked(ServiceRecord r) {
8364 if (!mRestartingServices.contains(r)) {
8365 return;
8366 }
8367 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
8368 }
8369
8370 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
8371 if (r.restartDelay == 0) {
8372 return false;
8373 }
8374 r.resetRestartCounter();
8375 mRestartingServices.remove(r);
8376 mHandler.removeCallbacks(r.restarter);
8377 return true;
8378 }
8379
8380 private final boolean bringUpServiceLocked(ServiceRecord r,
8381 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008382 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008383 //r.dump(" ");
8384
Dianne Hackborn36124872009-10-08 16:22:03 -07008385 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008386 sendServiceArgsLocked(r, false);
8387 return true;
8388 }
8389
8390 if (!whileRestarting && r.restartDelay > 0) {
8391 // If waiting for a restart, then do nothing.
8392 return true;
8393 }
8394
Joe Onorato8a9b2202010-02-26 18:56:32 -08008395 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008396 + " " + r.intent);
8397
Dianne Hackbornde42bb62009-08-05 12:26:15 -07008398 // We are now bringing the service up, so no longer in the
8399 // restarting state.
8400 mRestartingServices.remove(r);
8401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008402 final String appName = r.processName;
8403 ProcessRecord app = getProcessRecordLocked(appName, r.appInfo.uid);
8404 if (app != null && app.thread != null) {
8405 try {
8406 realStartServiceLocked(r, app);
8407 return true;
8408 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008409 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008410 }
8411
8412 // If a dead object exception was thrown -- fall through to
8413 // restart the application.
8414 }
8415
Dianne Hackborn36124872009-10-08 16:22:03 -07008416 // Not running -- get it started, and enqueue this service record
8417 // to be executed when the app comes up.
8418 if (startProcessLocked(appName, r.appInfo, true, intentFlags,
8419 "service", r.name, false) == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008420 Slog.w(TAG, "Unable to launch app "
Dianne Hackborn36124872009-10-08 16:22:03 -07008421 + r.appInfo.packageName + "/"
8422 + r.appInfo.uid + " for service "
8423 + r.intent.getIntent() + ": process is bad");
8424 bringDownServiceLocked(r, true);
8425 return false;
8426 }
8427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008428 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008429 mPendingServices.add(r);
8430 }
Dianne Hackborn36124872009-10-08 16:22:03 -07008431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008432 return true;
8433 }
8434
8435 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008436 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008437 //r.dump(" ");
8438
8439 // Does it still need to run?
8440 if (!force && r.startRequested) {
8441 return;
8442 }
8443 if (r.connections.size() > 0) {
8444 if (!force) {
8445 // XXX should probably keep a count of the number of auto-create
8446 // connections directly in the service.
8447 Iterator<ConnectionRecord> it = r.connections.values().iterator();
8448 while (it.hasNext()) {
8449 ConnectionRecord cr = it.next();
8450 if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
8451 return;
8452 }
8453 }
8454 }
8455
8456 // Report to all of the connections that the service is no longer
8457 // available.
8458 Iterator<ConnectionRecord> it = r.connections.values().iterator();
8459 while (it.hasNext()) {
8460 ConnectionRecord c = it.next();
8461 try {
8462 // todo: shouldn't be a synchronous call!
8463 c.conn.connected(r.name, null);
8464 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008465 Slog.w(TAG, "Failure disconnecting service " + r.name +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466 " to connection " + c.conn.asBinder() +
8467 " (in " + c.binding.client.processName + ")", e);
8468 }
8469 }
8470 }
8471
8472 // Tell the service that it has been unbound.
8473 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
8474 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
8475 while (it.hasNext()) {
8476 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -08008477 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008478 + ": hasBound=" + ibr.hasBound);
8479 if (r.app != null && r.app.thread != null && ibr.hasBound) {
8480 try {
8481 bumpServiceExecutingLocked(r);
8482 updateOomAdjLocked(r.app);
8483 ibr.hasBound = false;
8484 r.app.thread.scheduleUnbindService(r,
8485 ibr.intent.getIntent());
8486 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008487 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008488 + r.shortName, e);
8489 serviceDoneExecutingLocked(r, true);
8490 }
8491 }
8492 }
8493 }
8494
Joe Onorato8a9b2202010-02-26 18:56:32 -08008495 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008496 + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -08008497 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008498 System.identityHashCode(r), r.shortName,
8499 (r.app != null) ? r.app.pid : -1);
8500
8501 mServices.remove(r.name);
8502 mServicesByIntent.remove(r.intent);
Joe Onorato8a9b2202010-02-26 18:56:32 -08008503 if (localLOGV) Slog.v(TAG, "BRING DOWN SERVICE: " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 r.totalRestartCount = 0;
8505 unscheduleServiceRestartLocked(r);
8506
8507 // Also make sure it is not on the pending list.
8508 int N = mPendingServices.size();
8509 for (int i=0; i<N; i++) {
8510 if (mPendingServices.get(i) == r) {
8511 mPendingServices.remove(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08008512 if (DEBUG_SERVICE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008513 TAG, "Removed pending service: " + r.shortName);
8514 i--;
8515 N--;
8516 }
8517 }
8518
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07008519 r.cancelNotification();
8520 r.isForeground = false;
8521 r.foregroundId = 0;
8522 r.foregroundNoti = null;
8523
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008524 // Clear start entries.
8525 r.deliveredStarts.clear();
8526 r.pendingStarts.clear();
8527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008528 if (r.app != null) {
8529 synchronized (r.stats.getBatteryStats()) {
8530 r.stats.stopLaunchedLocked();
8531 }
8532 r.app.services.remove(r);
8533 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008534 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008535 if (DEBUG_SERVICE) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07008536 "Stopping service: " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008537 bumpServiceExecutingLocked(r);
8538 mStoppingServices.add(r);
8539 updateOomAdjLocked(r.app);
8540 r.app.thread.scheduleStopService(r);
8541 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008542 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008543 + r.shortName, e);
8544 serviceDoneExecutingLocked(r, true);
8545 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07008546 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008548 if (DEBUG_SERVICE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008549 TAG, "Removed service that has no process: " + r.shortName);
8550 }
8551 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008552 if (DEBUG_SERVICE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008553 TAG, "Removed service that is not running: " + r.shortName);
8554 }
8555 }
8556
8557 ComponentName startServiceLocked(IApplicationThread caller,
8558 Intent service, String resolvedType,
8559 int callingPid, int callingUid) {
8560 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008561 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008562 + " type=" + resolvedType + " args=" + service.getExtras());
8563
8564 if (caller != null) {
8565 final ProcessRecord callerApp = getRecordForAppLocked(caller);
8566 if (callerApp == null) {
8567 throw new SecurityException(
8568 "Unable to find app for caller " + caller
8569 + " (pid=" + Binder.getCallingPid()
8570 + ") when starting service " + service);
8571 }
8572 }
8573
8574 ServiceLookupResult res =
8575 retrieveServiceLocked(service, resolvedType,
8576 callingPid, callingUid);
8577 if (res == null) {
8578 return null;
8579 }
8580 if (res.record == null) {
8581 return new ComponentName("!", res.permission != null
8582 ? res.permission : "private to package");
8583 }
8584 ServiceRecord r = res.record;
8585 if (unscheduleServiceRestartLocked(r)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008586 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 + r.shortName);
8588 }
8589 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008590 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 r.lastStartId++;
8592 if (r.lastStartId < 1) {
8593 r.lastStartId = 1;
8594 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008595 r.pendingStarts.add(new ServiceRecord.StartItem(r.lastStartId, service));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 r.lastActivity = SystemClock.uptimeMillis();
8597 synchronized (r.stats.getBatteryStats()) {
8598 r.stats.startRunningLocked();
8599 }
8600 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
8601 return new ComponentName("!", "Service process is bad");
8602 }
8603 return r.name;
8604 }
8605 }
8606
8607 public ComponentName startService(IApplicationThread caller, Intent service,
8608 String resolvedType) {
8609 // Refuse possible leaked file descriptors
8610 if (service != null && service.hasFileDescriptors() == true) {
8611 throw new IllegalArgumentException("File descriptors passed in Intent");
8612 }
8613
8614 synchronized(this) {
8615 final int callingPid = Binder.getCallingPid();
8616 final int callingUid = Binder.getCallingUid();
8617 final long origId = Binder.clearCallingIdentity();
8618 ComponentName res = startServiceLocked(caller, service,
8619 resolvedType, callingPid, callingUid);
8620 Binder.restoreCallingIdentity(origId);
8621 return res;
8622 }
8623 }
8624
8625 ComponentName startServiceInPackage(int uid,
8626 Intent service, String resolvedType) {
8627 synchronized(this) {
8628 final long origId = Binder.clearCallingIdentity();
8629 ComponentName res = startServiceLocked(null, service,
8630 resolvedType, -1, uid);
8631 Binder.restoreCallingIdentity(origId);
8632 return res;
8633 }
8634 }
8635
8636 public int stopService(IApplicationThread caller, Intent service,
8637 String resolvedType) {
8638 // Refuse possible leaked file descriptors
8639 if (service != null && service.hasFileDescriptors() == true) {
8640 throw new IllegalArgumentException("File descriptors passed in Intent");
8641 }
8642
8643 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008644 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008645 + " type=" + resolvedType);
8646
8647 final ProcessRecord callerApp = getRecordForAppLocked(caller);
8648 if (caller != null && callerApp == null) {
8649 throw new SecurityException(
8650 "Unable to find app for caller " + caller
8651 + " (pid=" + Binder.getCallingPid()
8652 + ") when stopping service " + service);
8653 }
8654
8655 // If this service is active, make sure it is stopped.
8656 ServiceLookupResult r = findServiceLocked(service, resolvedType);
8657 if (r != null) {
8658 if (r.record != null) {
8659 synchronized (r.record.stats.getBatteryStats()) {
8660 r.record.stats.stopRunningLocked();
8661 }
8662 r.record.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008663 r.record.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 final long origId = Binder.clearCallingIdentity();
8665 bringDownServiceLocked(r.record, false);
8666 Binder.restoreCallingIdentity(origId);
8667 return 1;
8668 }
8669 return -1;
8670 }
8671 }
8672
8673 return 0;
8674 }
8675
8676 public IBinder peekService(Intent service, String resolvedType) {
8677 // Refuse possible leaked file descriptors
8678 if (service != null && service.hasFileDescriptors() == true) {
8679 throw new IllegalArgumentException("File descriptors passed in Intent");
8680 }
8681
8682 IBinder ret = null;
8683
8684 synchronized(this) {
8685 ServiceLookupResult r = findServiceLocked(service, resolvedType);
8686
8687 if (r != null) {
8688 // r.record is null if findServiceLocked() failed the caller permission check
8689 if (r.record == null) {
8690 throw new SecurityException(
8691 "Permission Denial: Accessing service " + r.record.name
8692 + " from pid=" + Binder.getCallingPid()
8693 + ", uid=" + Binder.getCallingUid()
8694 + " requires " + r.permission);
8695 }
8696 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
8697 if (ib != null) {
8698 ret = ib.binder;
8699 }
8700 }
8701 }
8702
8703 return ret;
8704 }
8705
8706 public boolean stopServiceToken(ComponentName className, IBinder token,
8707 int startId) {
8708 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008709 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710 + " " + token + " startId=" + startId);
8711 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008712 if (r != null) {
8713 if (startId >= 0) {
8714 // Asked to only stop if done with all work. Note that
8715 // to avoid leaks, we will take this as dropping all
8716 // start items up to and including this one.
8717 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
8718 if (si != null) {
8719 while (r.deliveredStarts.size() > 0) {
8720 if (r.deliveredStarts.remove(0) == si) {
8721 break;
8722 }
8723 }
8724 }
8725
8726 if (r.lastStartId != startId) {
8727 return false;
8728 }
8729
8730 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008731 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008732 + " is last, but have " + r.deliveredStarts.size()
8733 + " remaining args");
8734 }
8735 }
8736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 synchronized (r.stats.getBatteryStats()) {
8738 r.stats.stopRunningLocked();
8739 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07008740 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008741 }
8742 final long origId = Binder.clearCallingIdentity();
8743 bringDownServiceLocked(r, false);
8744 Binder.restoreCallingIdentity(origId);
8745 return true;
8746 }
8747 }
8748 return false;
8749 }
8750
8751 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07008752 int id, Notification notification, boolean removeNotification) {
8753 final long origId = Binder.clearCallingIdentity();
8754 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008755 synchronized(this) {
8756 ServiceRecord r = findServiceLocked(className, token);
8757 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07008758 if (id != 0) {
8759 if (notification == null) {
8760 throw new IllegalArgumentException("null notification");
8761 }
8762 if (r.foregroundId != id) {
8763 r.cancelNotification();
8764 r.foregroundId = id;
8765 }
8766 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
8767 r.foregroundNoti = notification;
8768 r.isForeground = true;
8769 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770 if (r.app != null) {
8771 updateServiceForegroundLocked(r.app, true);
8772 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07008773 } else {
8774 if (r.isForeground) {
8775 r.isForeground = false;
8776 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07008777 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07008778 updateServiceForegroundLocked(r.app, true);
8779 }
8780 }
8781 if (removeNotification) {
8782 r.cancelNotification();
8783 r.foregroundId = 0;
8784 r.foregroundNoti = null;
8785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008786 }
8787 }
8788 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07008789 } finally {
8790 Binder.restoreCallingIdentity(origId);
8791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008792 }
8793
8794 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
8795 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -07008796 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008797 if (sr.isForeground) {
8798 anyForeground = true;
8799 break;
8800 }
8801 }
8802 if (anyForeground != proc.foregroundServices) {
8803 proc.foregroundServices = anyForeground;
8804 if (oomAdj) {
8805 updateOomAdjLocked();
8806 }
8807 }
8808 }
8809
8810 public int bindService(IApplicationThread caller, IBinder token,
8811 Intent service, String resolvedType,
8812 IServiceConnection connection, int flags) {
8813 // Refuse possible leaked file descriptors
8814 if (service != null && service.hasFileDescriptors() == true) {
8815 throw new IllegalArgumentException("File descriptors passed in Intent");
8816 }
8817
8818 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008819 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008820 + " type=" + resolvedType + " conn=" + connection.asBinder()
8821 + " flags=0x" + Integer.toHexString(flags));
8822 final ProcessRecord callerApp = getRecordForAppLocked(caller);
8823 if (callerApp == null) {
8824 throw new SecurityException(
8825 "Unable to find app for caller " + caller
8826 + " (pid=" + Binder.getCallingPid()
8827 + ") when binding service " + service);
8828 }
8829
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008830 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831 if (token != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008832 int aindex = mMainStack.indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008833 if (aindex < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008834 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008835 return 0;
8836 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008837 activity = (ActivityRecord)mMainStack.mHistory.get(aindex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008838 }
8839
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008840 int clientLabel = 0;
8841 PendingIntent clientIntent = null;
8842
8843 if (callerApp.info.uid == Process.SYSTEM_UID) {
8844 // Hacky kind of thing -- allow system stuff to tell us
8845 // what they are, so we can report this elsewhere for
8846 // others to know why certain services are running.
8847 try {
8848 clientIntent = (PendingIntent)service.getParcelableExtra(
8849 Intent.EXTRA_CLIENT_INTENT);
8850 } catch (RuntimeException e) {
8851 }
8852 if (clientIntent != null) {
8853 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
8854 if (clientLabel != 0) {
8855 // There are no useful extras in the intent, trash them.
8856 // System code calling with this stuff just needs to know
8857 // this will happen.
8858 service = service.cloneFilter();
8859 }
8860 }
8861 }
8862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008863 ServiceLookupResult res =
8864 retrieveServiceLocked(service, resolvedType,
8865 Binder.getCallingPid(), Binder.getCallingUid());
8866 if (res == null) {
8867 return 0;
8868 }
8869 if (res.record == null) {
8870 return -1;
8871 }
8872 ServiceRecord s = res.record;
8873
8874 final long origId = Binder.clearCallingIdentity();
8875
8876 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008877 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008878 + s.shortName);
8879 }
8880
8881 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
8882 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008883 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884
8885 IBinder binder = connection.asBinder();
8886 s.connections.put(binder, c);
8887 b.connections.add(c);
8888 if (activity != null) {
8889 if (activity.connections == null) {
8890 activity.connections = new HashSet<ConnectionRecord>();
8891 }
8892 activity.connections.add(c);
8893 }
8894 b.client.connections.add(c);
8895 mServiceConnections.put(binder, c);
8896
8897 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
8898 s.lastActivity = SystemClock.uptimeMillis();
8899 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
8900 return 0;
8901 }
8902 }
8903
8904 if (s.app != null) {
8905 // This could have made the service more important.
8906 updateOomAdjLocked(s.app);
8907 }
8908
Joe Onorato8a9b2202010-02-26 18:56:32 -08008909 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 + ": received=" + b.intent.received
8911 + " apps=" + b.intent.apps.size()
8912 + " doRebind=" + b.intent.doRebind);
8913
8914 if (s.app != null && b.intent.received) {
8915 // Service is already running, so we can immediately
8916 // publish the connection.
8917 try {
8918 c.conn.connected(s.name, b.intent.binder);
8919 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008920 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008921 + " to connection " + c.conn.asBinder()
8922 + " (in " + c.binding.client.processName + ")", e);
8923 }
8924
8925 // If this is the first app connected back to this binding,
8926 // and the service had previously asked to be told when
8927 // rebound, then do so.
8928 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
8929 requestServiceBindingLocked(s, b.intent, true);
8930 }
8931 } else if (!b.intent.requested) {
8932 requestServiceBindingLocked(s, b.intent, false);
8933 }
8934
8935 Binder.restoreCallingIdentity(origId);
8936 }
8937
8938 return 1;
8939 }
8940
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008941 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008942 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 IBinder binder = c.conn.asBinder();
8944 AppBindRecord b = c.binding;
8945 ServiceRecord s = b.service;
8946 s.connections.remove(binder);
8947 b.connections.remove(c);
8948 if (c.activity != null && c.activity != skipAct) {
8949 if (c.activity.connections != null) {
8950 c.activity.connections.remove(c);
8951 }
8952 }
8953 if (b.client != skipApp) {
8954 b.client.connections.remove(c);
8955 }
8956 mServiceConnections.remove(binder);
8957
8958 if (b.connections.size() == 0) {
8959 b.intent.apps.remove(b.client);
8960 }
8961
Joe Onorato8a9b2202010-02-26 18:56:32 -08008962 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008963 + ": shouldUnbind=" + b.intent.hasBound);
8964 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
8965 && b.intent.hasBound) {
8966 try {
8967 bumpServiceExecutingLocked(s);
8968 updateOomAdjLocked(s.app);
8969 b.intent.hasBound = false;
8970 // Assume the client doesn't want to know about a rebind;
8971 // we will deal with that later if it asks for one.
8972 b.intent.doRebind = false;
8973 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
8974 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008975 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008976 serviceDoneExecutingLocked(s, true);
8977 }
8978 }
8979
8980 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
8981 bringDownServiceLocked(s, false);
8982 }
8983 }
8984
8985 public boolean unbindService(IServiceConnection connection) {
8986 synchronized (this) {
8987 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -08008988 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989 ConnectionRecord r = mServiceConnections.get(binder);
8990 if (r == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008991 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008992 + connection.asBinder());
8993 return false;
8994 }
8995
8996 final long origId = Binder.clearCallingIdentity();
8997
8998 removeConnectionLocked(r, null, null);
8999
9000 if (r.binding.service.app != null) {
9001 // This could have made the service less important.
9002 updateOomAdjLocked(r.binding.service.app);
9003 }
9004
9005 Binder.restoreCallingIdentity(origId);
9006 }
9007
9008 return true;
9009 }
9010
9011 public void publishService(IBinder token, Intent intent, IBinder service) {
9012 // Refuse possible leaked file descriptors
9013 if (intent != null && intent.hasFileDescriptors() == true) {
9014 throw new IllegalArgumentException("File descriptors passed in Intent");
9015 }
9016
9017 synchronized(this) {
9018 if (!(token instanceof ServiceRecord)) {
9019 throw new IllegalArgumentException("Invalid service token");
9020 }
9021 ServiceRecord r = (ServiceRecord)token;
9022
9023 final long origId = Binder.clearCallingIdentity();
9024
Joe Onorato8a9b2202010-02-26 18:56:32 -08009025 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING SERVICE " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009026 + " " + intent + ": " + service);
9027 if (r != null) {
9028 Intent.FilterComparison filter
9029 = new Intent.FilterComparison(intent);
9030 IntentBindRecord b = r.bindings.get(filter);
9031 if (b != null && !b.received) {
9032 b.binder = service;
9033 b.requested = true;
9034 b.received = true;
9035 if (r.connections.size() > 0) {
9036 Iterator<ConnectionRecord> it
9037 = r.connections.values().iterator();
9038 while (it.hasNext()) {
9039 ConnectionRecord c = it.next();
9040 if (!filter.equals(c.binding.intent.intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009041 if (DEBUG_SERVICE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009042 TAG, "Not publishing to: " + c);
Joe Onorato8a9b2202010-02-26 18:56:32 -08009043 if (DEBUG_SERVICE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009044 TAG, "Bound intent: " + c.binding.intent.intent);
Joe Onorato8a9b2202010-02-26 18:56:32 -08009045 if (DEBUG_SERVICE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009046 TAG, "Published intent: " + intent);
9047 continue;
9048 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08009049 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009050 try {
9051 c.conn.connected(r.name, service);
9052 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009053 Slog.w(TAG, "Failure sending service " + r.name +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009054 " to connection " + c.conn.asBinder() +
9055 " (in " + c.binding.client.processName + ")", e);
9056 }
9057 }
9058 }
9059 }
9060
9061 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
9062
9063 Binder.restoreCallingIdentity(origId);
9064 }
9065 }
9066 }
9067
9068 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
9069 // Refuse possible leaked file descriptors
9070 if (intent != null && intent.hasFileDescriptors() == true) {
9071 throw new IllegalArgumentException("File descriptors passed in Intent");
9072 }
9073
9074 synchronized(this) {
9075 if (!(token instanceof ServiceRecord)) {
9076 throw new IllegalArgumentException("Invalid service token");
9077 }
9078 ServiceRecord r = (ServiceRecord)token;
9079
9080 final long origId = Binder.clearCallingIdentity();
9081
9082 if (r != null) {
9083 Intent.FilterComparison filter
9084 = new Intent.FilterComparison(intent);
9085 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -08009086 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009087 + " at " + b + ": apps="
9088 + (b != null ? b.apps.size() : 0));
9089 if (b != null) {
9090 if (b.apps.size() > 0) {
9091 // Applications have already bound since the last
9092 // unbind, so just rebind right here.
9093 requestServiceBindingLocked(r, b, true);
9094 } else {
9095 // Note to tell the service the next time there is
9096 // a new client.
9097 b.doRebind = true;
9098 }
9099 }
9100
9101 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
9102
9103 Binder.restoreCallingIdentity(origId);
9104 }
9105 }
9106 }
9107
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009108 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 synchronized(this) {
9110 if (!(token instanceof ServiceRecord)) {
9111 throw new IllegalArgumentException("Invalid service token");
9112 }
9113 ServiceRecord r = (ServiceRecord)token;
9114 boolean inStopping = mStoppingServices.contains(token);
9115 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009116 if (DEBUG_SERVICE) Slog.v(TAG, "DONE EXECUTING SERVICE " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009117 + ": nesting=" + r.executeNesting
9118 + ", inStopping=" + inStopping);
9119 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009120 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009121 + " with incorrect token: given " + token
9122 + ", expected " + r);
9123 return;
9124 }
9125
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009126 if (type == 1) {
9127 // This is a call from a service start... take care of
9128 // book-keeping.
9129 r.callStart = true;
9130 switch (res) {
9131 case Service.START_STICKY_COMPATIBILITY:
9132 case Service.START_STICKY: {
9133 // We are done with the associated start arguments.
9134 r.findDeliveredStart(startId, true);
9135 // Don't stop if killed.
9136 r.stopIfKilled = false;
9137 break;
9138 }
9139 case Service.START_NOT_STICKY: {
9140 // We are done with the associated start arguments.
9141 r.findDeliveredStart(startId, true);
9142 if (r.lastStartId == startId) {
9143 // There is no more work, and this service
9144 // doesn't want to hang around if killed.
9145 r.stopIfKilled = true;
9146 }
9147 break;
9148 }
9149 case Service.START_REDELIVER_INTENT: {
9150 // We'll keep this item until they explicitly
9151 // call stop for it, but keep track of the fact
9152 // that it was delivered.
9153 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
9154 if (si != null) {
9155 si.deliveryCount = 0;
9156 si.doneExecutingCount++;
9157 // Don't stop if killed.
9158 r.stopIfKilled = true;
9159 }
9160 break;
9161 }
9162 default:
9163 throw new IllegalArgumentException(
9164 "Unknown service start result: " + res);
9165 }
9166 if (res == Service.START_STICKY_COMPATIBILITY) {
9167 r.callStart = false;
9168 }
9169 }
9170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009171 final long origId = Binder.clearCallingIdentity();
9172 serviceDoneExecutingLocked(r, inStopping);
9173 Binder.restoreCallingIdentity(origId);
9174 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009175 Slog.w(TAG, "Done executing unknown service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009176 + " with token " + token);
9177 }
9178 }
9179 }
9180
9181 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
9182 r.executeNesting--;
9183 if (r.executeNesting <= 0 && r.app != null) {
9184 r.app.executingServices.remove(r);
9185 if (r.app.executingServices.size() == 0) {
9186 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
9187 }
9188 if (inStopping) {
9189 mStoppingServices.remove(r);
9190 }
9191 updateOomAdjLocked(r.app);
9192 }
9193 }
9194
9195 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -07009196 String anrMessage = null;
9197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009198 synchronized(this) {
9199 if (proc.executingServices.size() == 0 || proc.thread == null) {
9200 return;
9201 }
9202 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
9203 Iterator<ServiceRecord> it = proc.executingServices.iterator();
9204 ServiceRecord timeout = null;
9205 long nextTime = 0;
9206 while (it.hasNext()) {
9207 ServiceRecord sr = it.next();
9208 if (sr.executingStart < maxTime) {
9209 timeout = sr;
9210 break;
9211 }
9212 if (sr.executingStart > nextTime) {
9213 nextTime = sr.executingStart;
9214 }
9215 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009216 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009217 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07009218 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009219 } else {
9220 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
9221 msg.obj = proc;
9222 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
9223 }
9224 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07009225
9226 if (anrMessage != null) {
9227 appNotResponding(proc, null, null, anrMessage);
9228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009229 }
9230
9231 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -07009232 // BACKUP AND RESTORE
9233 // =========================================================
9234
9235 // Cause the target app to be launched if necessary and its backup agent
9236 // instantiated. The backup agent will invoke backupAgentCreated() on the
9237 // activity manager to announce its creation.
9238 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009239 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07009240 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
9241
9242 synchronized(this) {
9243 // !!! TODO: currently no check here that we're already bound
9244 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
9245 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
9246 synchronized (stats) {
9247 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
9248 }
9249
9250 BackupRecord r = new BackupRecord(ss, app, backupMode);
9251 ComponentName hostingName = new ComponentName(app.packageName, app.backupAgentName);
9252 // startProcessLocked() returns existing proc's record if it's already running
9253 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07009254 false, 0, "backup", hostingName, false);
Christopher Tate181fafa2009-05-14 11:12:14 -07009255 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009256 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -07009257 return false;
9258 }
9259
9260 r.app = proc;
9261 mBackupTarget = r;
9262 mBackupAppName = app.packageName;
9263
Christopher Tate6fa95972009-06-05 18:43:55 -07009264 // Try not to kill the process during backup
9265 updateOomAdjLocked(proc);
9266
Christopher Tate181fafa2009-05-14 11:12:14 -07009267 // If the process is already attached, schedule the creation of the backup agent now.
9268 // If it is not yet live, this will be done when it attaches to the framework.
9269 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009270 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -07009271 try {
9272 proc.thread.scheduleCreateBackupAgent(app, backupMode);
9273 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -07009274 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -07009275 }
9276 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009277 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -07009278 }
9279 // Invariants: at this point, the target app process exists and the application
9280 // is either already running or in the process of coming up. mBackupTarget and
9281 // mBackupAppName describe the app, so that when it binds back to the AM we
9282 // know that it's scheduled for a backup-agent operation.
9283 }
9284
9285 return true;
9286 }
9287
9288 // A backup agent has just come up
9289 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009290 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -07009291 + " = " + agent);
9292
9293 synchronized(this) {
9294 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009295 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -07009296 return;
9297 }
9298
Christopher Tate043dadc2009-06-02 16:11:00 -07009299 long oldIdent = Binder.clearCallingIdentity();
Christopher Tate181fafa2009-05-14 11:12:14 -07009300 try {
9301 IBackupManager bm = IBackupManager.Stub.asInterface(
9302 ServiceManager.getService(Context.BACKUP_SERVICE));
9303 bm.agentConnected(agentPackageName, agent);
9304 } catch (RemoteException e) {
9305 // can't happen; the backup manager service is local
9306 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009307 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07009308 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -07009309 } finally {
9310 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -07009311 }
9312 }
9313 }
9314
9315 // done with this agent
9316 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009317 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -07009318 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009319 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -07009320 return;
9321 }
Christopher Tate181fafa2009-05-14 11:12:14 -07009322
9323 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -07009324 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009325 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -07009326 return;
9327 }
9328
Christopher Tate181fafa2009-05-14 11:12:14 -07009329 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009330 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -07009331 return;
9332 }
9333
Christopher Tate6fa95972009-06-05 18:43:55 -07009334 ProcessRecord proc = mBackupTarget.app;
9335 mBackupTarget = null;
9336 mBackupAppName = null;
9337
9338 // Not backing this app up any more; reset its OOM adjustment
9339 updateOomAdjLocked(proc);
9340
Christopher Tatec7b31e32009-06-10 15:49:30 -07009341 // If the app crashed during backup, 'thread' will be null here
9342 if (proc.thread != null) {
9343 try {
9344 proc.thread.scheduleDestroyBackupAgent(appInfo);
9345 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009346 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -07009347 e.printStackTrace();
9348 }
Christopher Tate181fafa2009-05-14 11:12:14 -07009349 }
Christopher Tate181fafa2009-05-14 11:12:14 -07009350 }
9351 }
9352 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353 // BROADCASTS
9354 // =========================================================
9355
Josh Bartel7f208742010-02-25 11:01:44 -06009356 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009357 List cur) {
9358 final ContentResolver resolver = mContext.getContentResolver();
9359 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
9360 if (list == null) {
9361 return cur;
9362 }
9363 int N = list.size();
9364 for (int i=0; i<N; i++) {
9365 Intent intent = list.get(i);
9366 if (filter.match(resolver, intent, true, TAG) >= 0) {
9367 if (cur == null) {
9368 cur = new ArrayList<Intent>();
9369 }
9370 cur.add(intent);
9371 }
9372 }
9373 return cur;
9374 }
9375
9376 private final void scheduleBroadcastsLocked() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009377 if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts: current="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009378 + mBroadcastsScheduled);
9379
9380 if (mBroadcastsScheduled) {
9381 return;
9382 }
9383 mHandler.sendEmptyMessage(BROADCAST_INTENT_MSG);
9384 mBroadcastsScheduled = true;
9385 }
9386
9387 public Intent registerReceiver(IApplicationThread caller,
9388 IIntentReceiver receiver, IntentFilter filter, String permission) {
9389 synchronized(this) {
9390 ProcessRecord callerApp = null;
9391 if (caller != null) {
9392 callerApp = getRecordForAppLocked(caller);
9393 if (callerApp == null) {
9394 throw new SecurityException(
9395 "Unable to find app for caller " + caller
9396 + " (pid=" + Binder.getCallingPid()
9397 + ") when registering receiver " + receiver);
9398 }
9399 }
9400
9401 List allSticky = null;
9402
9403 // Look for any matching sticky broadcasts...
9404 Iterator actions = filter.actionsIterator();
9405 if (actions != null) {
9406 while (actions.hasNext()) {
9407 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -06009408 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009409 }
9410 } else {
Josh Bartel7f208742010-02-25 11:01:44 -06009411 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009412 }
9413
9414 // The first sticky in the list is returned directly back to
9415 // the client.
9416 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
9417
Joe Onorato8a9b2202010-02-26 18:56:32 -08009418 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009419 + ": " + sticky);
9420
9421 if (receiver == null) {
9422 return sticky;
9423 }
9424
9425 ReceiverList rl
9426 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
9427 if (rl == null) {
9428 rl = new ReceiverList(this, callerApp,
9429 Binder.getCallingPid(),
9430 Binder.getCallingUid(), receiver);
9431 if (rl.app != null) {
9432 rl.app.receivers.add(rl);
9433 } else {
9434 try {
9435 receiver.asBinder().linkToDeath(rl, 0);
9436 } catch (RemoteException e) {
9437 return sticky;
9438 }
9439 rl.linkedToDeath = true;
9440 }
9441 mRegisteredReceivers.put(receiver.asBinder(), rl);
9442 }
9443 BroadcastFilter bf = new BroadcastFilter(filter, rl, permission);
9444 rl.add(bf);
9445 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009446 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009447 }
9448 mReceiverResolver.addFilter(bf);
9449
9450 // Enqueue broadcasts for all existing stickies that match
9451 // this filter.
9452 if (allSticky != null) {
9453 ArrayList receivers = new ArrayList();
9454 receivers.add(bf);
9455
9456 int N = allSticky.size();
9457 for (int i=0; i<N; i++) {
9458 Intent intent = (Intent)allSticky.get(i);
9459 BroadcastRecord r = new BroadcastRecord(intent, null,
9460 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -08009461 false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009462 if (mParallelBroadcasts.size() == 0) {
9463 scheduleBroadcastsLocked();
9464 }
9465 mParallelBroadcasts.add(r);
9466 }
9467 }
9468
9469 return sticky;
9470 }
9471 }
9472
9473 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009474 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009475
9476 boolean doNext = false;
9477
9478 synchronized(this) {
9479 ReceiverList rl
9480 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
9481 if (rl != null) {
9482 if (rl.curBroadcast != null) {
9483 BroadcastRecord r = rl.curBroadcast;
9484 doNext = finishReceiverLocked(
9485 receiver.asBinder(), r.resultCode, r.resultData,
9486 r.resultExtras, r.resultAbort, true);
9487 }
9488
9489 if (rl.app != null) {
9490 rl.app.receivers.remove(rl);
9491 }
9492 removeReceiverLocked(rl);
9493 if (rl.linkedToDeath) {
9494 rl.linkedToDeath = false;
9495 rl.receiver.asBinder().unlinkToDeath(rl, 0);
9496 }
9497 }
9498 }
9499
9500 if (!doNext) {
9501 return;
9502 }
9503
9504 final long origId = Binder.clearCallingIdentity();
9505 processNextBroadcast(false);
9506 trimApplications();
9507 Binder.restoreCallingIdentity(origId);
9508 }
9509
9510 void removeReceiverLocked(ReceiverList rl) {
9511 mRegisteredReceivers.remove(rl.receiver.asBinder());
9512 int N = rl.size();
9513 for (int i=0; i<N; i++) {
9514 mReceiverResolver.removeFilter(rl.get(i));
9515 }
9516 }
9517
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07009518 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
9519 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
9520 ProcessRecord r = mLruProcesses.get(i);
9521 if (r.thread != null) {
9522 try {
9523 r.thread.dispatchPackageBroadcast(cmd, packages);
9524 } catch (RemoteException ex) {
9525 }
9526 }
9527 }
9528 }
9529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009530 private final int broadcastIntentLocked(ProcessRecord callerApp,
9531 String callerPackage, Intent intent, String resolvedType,
9532 IIntentReceiver resultTo, int resultCode, String resultData,
9533 Bundle map, String requiredPermission,
9534 boolean ordered, boolean sticky, int callingPid, int callingUid) {
9535 intent = new Intent(intent);
9536
Joe Onorato8a9b2202010-02-26 18:56:32 -08009537 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009538 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
9539 + " ordered=" + ordered);
9540 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009541 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009542 }
9543
9544 // Handle special intents: if this broadcast is from the package
9545 // manager about a package being removed, we need to remove all of
9546 // its activities from the history stack.
9547 final boolean uidRemoved = intent.ACTION_UID_REMOVED.equals(
9548 intent.getAction());
9549 if (intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
9550 || intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009551 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009552 || uidRemoved) {
9553 if (checkComponentPermission(
9554 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
9555 callingPid, callingUid, -1)
9556 == PackageManager.PERMISSION_GRANTED) {
9557 if (uidRemoved) {
9558 final Bundle intentExtras = intent.getExtras();
9559 final int uid = intentExtras != null
9560 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
9561 if (uid >= 0) {
9562 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
9563 synchronized (bs) {
9564 bs.removeUidStatsLocked(uid);
9565 }
9566 }
9567 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009568 // If resources are unvailble just force stop all
9569 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009570 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009571 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
9572 if (list != null && (list.length > 0)) {
9573 for (String pkg : list) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08009574 forceStopPackageLocked(pkg, -1, false, true, true);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009575 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07009576 sendPackageBroadcastLocked(
9577 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009578 }
9579 } else {
9580 Uri data = intent.getData();
9581 String ssp;
9582 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
9583 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
9584 forceStopPackageLocked(ssp,
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08009585 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true);
Dianne Hackbornde7faf62009-06-30 13:27:30 -07009586 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07009587 if (intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
9588 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
9589 new String[] {ssp});
9590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009591 }
9592 }
9593 }
9594 } else {
9595 String msg = "Permission Denial: " + intent.getAction()
9596 + " broadcast from " + callerPackage + " (pid=" + callingPid
9597 + ", uid=" + callingUid + ")"
9598 + " requires "
9599 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -08009600 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009601 throw new SecurityException(msg);
9602 }
9603 }
9604
9605 /*
9606 * If this is the time zone changed action, queue up a message that will reset the timezone
9607 * of all currently running processes. This message will get queued up before the broadcast
9608 * happens.
9609 */
9610 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
9611 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
9612 }
9613
Dianne Hackborn854060af2009-07-09 18:14:31 -07009614 /*
9615 * Prevent non-system code (defined here to be non-persistent
9616 * processes) from sending protected broadcasts.
9617 */
9618 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
9619 || callingUid == Process.SHELL_UID || callingUid == 0) {
9620 // Always okay.
9621 } else if (callerApp == null || !callerApp.persistent) {
9622 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009623 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -07009624 intent.getAction())) {
9625 String msg = "Permission Denial: not allowed to send broadcast "
9626 + intent.getAction() + " from pid="
9627 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08009628 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -07009629 throw new SecurityException(msg);
9630 }
9631 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009632 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -07009633 return BROADCAST_SUCCESS;
9634 }
9635 }
9636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009637 // Add to the sticky list if requested.
9638 if (sticky) {
9639 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
9640 callingPid, callingUid)
9641 != PackageManager.PERMISSION_GRANTED) {
9642 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
9643 + callingPid + ", uid=" + callingUid
9644 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -08009645 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009646 throw new SecurityException(msg);
9647 }
9648 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009649 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009650 + " and enforce permission " + requiredPermission);
9651 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
9652 }
9653 if (intent.getComponent() != null) {
9654 throw new SecurityException(
9655 "Sticky broadcasts can't target a specific component");
9656 }
9657 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
9658 if (list == null) {
9659 list = new ArrayList<Intent>();
9660 mStickyBroadcasts.put(intent.getAction(), list);
9661 }
9662 int N = list.size();
9663 int i;
9664 for (i=0; i<N; i++) {
9665 if (intent.filterEquals(list.get(i))) {
9666 // This sticky already exists, replace it.
9667 list.set(i, new Intent(intent));
9668 break;
9669 }
9670 }
9671 if (i >= N) {
9672 list.add(new Intent(intent));
9673 }
9674 }
9675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009676 // Figure out who all will receive this broadcast.
9677 List receivers = null;
9678 List<BroadcastFilter> registeredReceivers = null;
9679 try {
9680 if (intent.getComponent() != null) {
9681 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009682 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07009683 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009684 if (ai != null) {
9685 receivers = new ArrayList();
9686 ResolveInfo ri = new ResolveInfo();
9687 ri.activityInfo = ai;
9688 receivers.add(ri);
9689 }
9690 } else {
9691 // Need to resolve the intent to interested receivers...
9692 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
9693 == 0) {
9694 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009695 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -07009696 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009697 }
Mihai Preda074edef2009-05-18 17:13:31 +02009698 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009699 }
9700 } catch (RemoteException ex) {
9701 // pm is in same process, this will never happen.
9702 }
9703
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08009704 final boolean replacePending =
9705 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
9706
Joe Onorato8a9b2202010-02-26 18:56:32 -08009707 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08009708 + " replacePending=" + replacePending);
9709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009710 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
9711 if (!ordered && NR > 0) {
9712 // If we are not serializing this broadcast, then send the
9713 // registered receivers separately so they don't wait for the
9714 // components to be launched.
9715 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
9716 callerPackage, callingPid, callingUid, requiredPermission,
9717 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -08009718 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -08009719 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009720 TAG, "Enqueueing parallel broadcast " + r
9721 + ": prev had " + mParallelBroadcasts.size());
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08009722 boolean replaced = false;
9723 if (replacePending) {
9724 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
9725 if (intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009726 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08009727 "***** DROPPING PARALLEL: " + intent);
9728 mParallelBroadcasts.set(i, r);
9729 replaced = true;
9730 break;
9731 }
9732 }
9733 }
9734 if (!replaced) {
9735 mParallelBroadcasts.add(r);
9736 scheduleBroadcastsLocked();
9737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009738 registeredReceivers = null;
9739 NR = 0;
9740 }
9741
9742 // Merge into one list.
9743 int ir = 0;
9744 if (receivers != null) {
9745 // A special case for PACKAGE_ADDED: do not allow the package
9746 // being added to see this broadcast. This prevents them from
9747 // using this as a back door to get run as soon as they are
9748 // installed. Maybe in the future we want to have a special install
9749 // broadcast or such for apps, but we'd like to deliberately make
9750 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009751 String skipPackages[] = null;
9752 if (intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
9753 || intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
9754 || intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
9755 Uri data = intent.getData();
9756 if (data != null) {
9757 String pkgName = data.getSchemeSpecificPart();
9758 if (pkgName != null) {
9759 skipPackages = new String[] { pkgName };
9760 }
9761 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009762 } else if (intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009763 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -07009764 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009765 if (skipPackages != null && (skipPackages.length > 0)) {
9766 for (String skipPackage : skipPackages) {
9767 if (skipPackage != null) {
9768 int NT = receivers.size();
9769 for (int it=0; it<NT; it++) {
9770 ResolveInfo curt = (ResolveInfo)receivers.get(it);
9771 if (curt.activityInfo.packageName.equals(skipPackage)) {
9772 receivers.remove(it);
9773 it--;
9774 NT--;
9775 }
9776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009777 }
9778 }
9779 }
9780
9781 int NT = receivers != null ? receivers.size() : 0;
9782 int it = 0;
9783 ResolveInfo curt = null;
9784 BroadcastFilter curr = null;
9785 while (it < NT && ir < NR) {
9786 if (curt == null) {
9787 curt = (ResolveInfo)receivers.get(it);
9788 }
9789 if (curr == null) {
9790 curr = registeredReceivers.get(ir);
9791 }
9792 if (curr.getPriority() >= curt.priority) {
9793 // Insert this broadcast record into the final list.
9794 receivers.add(it, curr);
9795 ir++;
9796 curr = null;
9797 it++;
9798 NT++;
9799 } else {
9800 // Skip to the next ResolveInfo in the final list.
9801 it++;
9802 curt = null;
9803 }
9804 }
9805 }
9806 while (ir < NR) {
9807 if (receivers == null) {
9808 receivers = new ArrayList();
9809 }
9810 receivers.add(registeredReceivers.get(ir));
9811 ir++;
9812 }
9813
9814 if ((receivers != null && receivers.size() > 0)
9815 || resultTo != null) {
9816 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
9817 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -08009818 receivers, resultTo, resultCode, resultData, map, ordered,
9819 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -08009820 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009821 TAG, "Enqueueing ordered broadcast " + r
9822 + ": prev had " + mOrderedBroadcasts.size());
9823 if (DEBUG_BROADCAST) {
9824 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -08009825 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009826 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08009827 boolean replaced = false;
9828 if (replacePending) {
9829 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
9830 if (intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009831 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08009832 "***** DROPPING ORDERED: " + intent);
9833 mOrderedBroadcasts.set(i, r);
9834 replaced = true;
9835 break;
9836 }
9837 }
9838 }
9839 if (!replaced) {
9840 mOrderedBroadcasts.add(r);
9841 scheduleBroadcastsLocked();
9842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009843 }
9844
9845 return BROADCAST_SUCCESS;
9846 }
9847
9848 public final int broadcastIntent(IApplicationThread caller,
9849 Intent intent, String resolvedType, IIntentReceiver resultTo,
9850 int resultCode, String resultData, Bundle map,
9851 String requiredPermission, boolean serialized, boolean sticky) {
9852 // Refuse possible leaked file descriptors
9853 if (intent != null && intent.hasFileDescriptors() == true) {
9854 throw new IllegalArgumentException("File descriptors passed in Intent");
9855 }
9856
9857 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07009858 int flags = intent.getFlags();
9859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009860 if (!mSystemReady) {
9861 // if the caller really truly claims to know what they're doing, go
9862 // ahead and allow the broadcast without launching any receivers
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009863 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
9864 intent = new Intent(intent);
9865 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
9866 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0){
Joe Onorato8a9b2202010-02-26 18:56:32 -08009867 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009868 + " before boot completion");
9869 throw new IllegalStateException("Cannot broadcast before boot completed");
9870 }
9871 }
9872
Dianne Hackborn9acc0302009-08-25 00:27:12 -07009873 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
9874 throw new IllegalArgumentException(
9875 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
9876 }
9877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009878 final ProcessRecord callerApp = getRecordForAppLocked(caller);
9879 final int callingPid = Binder.getCallingPid();
9880 final int callingUid = Binder.getCallingUid();
9881 final long origId = Binder.clearCallingIdentity();
9882 int res = broadcastIntentLocked(callerApp,
9883 callerApp != null ? callerApp.info.packageName : null,
9884 intent, resolvedType, resultTo,
9885 resultCode, resultData, map, requiredPermission, serialized,
9886 sticky, callingPid, callingUid);
9887 Binder.restoreCallingIdentity(origId);
9888 return res;
9889 }
9890 }
9891
9892 int broadcastIntentInPackage(String packageName, int uid,
9893 Intent intent, String resolvedType, IIntentReceiver resultTo,
9894 int resultCode, String resultData, Bundle map,
9895 String requiredPermission, boolean serialized, boolean sticky) {
9896 synchronized(this) {
9897 final long origId = Binder.clearCallingIdentity();
9898 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
9899 resultTo, resultCode, resultData, map, requiredPermission,
9900 serialized, sticky, -1, uid);
9901 Binder.restoreCallingIdentity(origId);
9902 return res;
9903 }
9904 }
9905
9906 public final void unbroadcastIntent(IApplicationThread caller,
9907 Intent intent) {
9908 // Refuse possible leaked file descriptors
9909 if (intent != null && intent.hasFileDescriptors() == true) {
9910 throw new IllegalArgumentException("File descriptors passed in Intent");
9911 }
9912
9913 synchronized(this) {
9914 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
9915 != PackageManager.PERMISSION_GRANTED) {
9916 String msg = "Permission Denial: unbroadcastIntent() from pid="
9917 + Binder.getCallingPid()
9918 + ", uid=" + Binder.getCallingUid()
9919 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -08009920 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009921 throw new SecurityException(msg);
9922 }
9923 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
9924 if (list != null) {
9925 int N = list.size();
9926 int i;
9927 for (i=0; i<N; i++) {
9928 if (intent.filterEquals(list.get(i))) {
9929 list.remove(i);
9930 break;
9931 }
9932 }
9933 }
9934 }
9935 }
9936
9937 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
9938 String resultData, Bundle resultExtras, boolean resultAbort,
9939 boolean explicit) {
9940 if (mOrderedBroadcasts.size() == 0) {
9941 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009942 Slog.w(TAG, "finishReceiver called but no pending broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009943 }
9944 return false;
9945 }
9946 BroadcastRecord r = mOrderedBroadcasts.get(0);
9947 if (r.receiver == null) {
9948 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009949 Slog.w(TAG, "finishReceiver called but none active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009950 }
9951 return false;
9952 }
9953 if (r.receiver != receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009954 Slog.w(TAG, "finishReceiver called but active receiver is different");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009955 return false;
9956 }
9957 int state = r.state;
9958 r.state = r.IDLE;
9959 if (state == r.IDLE) {
9960 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009961 Slog.w(TAG, "finishReceiver called but state is IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009962 }
9963 }
9964 r.receiver = null;
9965 r.intent.setComponent(null);
9966 if (r.curApp != null) {
9967 r.curApp.curReceiver = null;
9968 }
9969 if (r.curFilter != null) {
9970 r.curFilter.receiverList.curBroadcast = null;
9971 }
9972 r.curFilter = null;
9973 r.curApp = null;
9974 r.curComponent = null;
9975 r.curReceiver = null;
9976 mPendingBroadcast = null;
9977
9978 r.resultCode = resultCode;
9979 r.resultData = resultData;
9980 r.resultExtras = resultExtras;
9981 r.resultAbort = resultAbort;
9982
9983 // We will process the next receiver right now if this is finishing
9984 // an app receiver (which is always asynchronous) or after we have
9985 // come back from calling a receiver.
9986 return state == BroadcastRecord.APP_RECEIVE
9987 || state == BroadcastRecord.CALL_DONE_RECEIVE;
9988 }
9989
9990 public void finishReceiver(IBinder who, int resultCode, String resultData,
9991 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009992 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009993
9994 // Refuse possible leaked file descriptors
9995 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
9996 throw new IllegalArgumentException("File descriptors passed in Bundle");
9997 }
9998
9999 boolean doNext;
10000
10001 final long origId = Binder.clearCallingIdentity();
10002
10003 synchronized(this) {
10004 doNext = finishReceiverLocked(
10005 who, resultCode, resultData, resultExtras, resultAbort, true);
10006 }
10007
10008 if (doNext) {
10009 processNextBroadcast(false);
10010 }
10011 trimApplications();
10012
10013 Binder.restoreCallingIdentity(origId);
10014 }
10015
10016 private final void logBroadcastReceiverDiscard(BroadcastRecord r) {
10017 if (r.nextReceiver > 0) {
10018 Object curReceiver = r.receivers.get(r.nextReceiver-1);
10019 if (curReceiver instanceof BroadcastFilter) {
10020 BroadcastFilter bf = (BroadcastFilter) curReceiver;
Doug Zongker2bec3d42009-12-04 12:52:44 -080010021 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010022 System.identityHashCode(r),
10023 r.intent.getAction(),
10024 r.nextReceiver - 1,
10025 System.identityHashCode(bf));
10026 } else {
Doug Zongker2bec3d42009-12-04 12:52:44 -080010027 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010028 System.identityHashCode(r),
10029 r.intent.getAction(),
10030 r.nextReceiver - 1,
10031 ((ResolveInfo)curReceiver).toString());
10032 }
10033 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010034 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010035 + r);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010036 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010037 System.identityHashCode(r),
10038 r.intent.getAction(),
10039 r.nextReceiver,
10040 "NONE");
10041 }
10042 }
10043
10044 private final void broadcastTimeout() {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010045 ProcessRecord app = null;
10046 String anrMessage = null;
10047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010048 synchronized (this) {
10049 if (mOrderedBroadcasts.size() == 0) {
10050 return;
10051 }
10052 long now = SystemClock.uptimeMillis();
10053 BroadcastRecord r = mOrderedBroadcasts.get(0);
Dianne Hackborn12527f92009-11-11 17:39:50 -080010054 if ((r.receiverTime+BROADCAST_TIMEOUT) > now) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010055 if (DEBUG_BROADCAST) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010056 "Premature timeout @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
Dianne Hackborn12527f92009-11-11 17:39:50 -080010057 + (r.receiverTime + BROADCAST_TIMEOUT));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010058 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
Dianne Hackborn12527f92009-11-11 17:39:50 -080010059 mHandler.sendMessageAtTime(msg, r.receiverTime+BROADCAST_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010060 return;
10061 }
10062
Joe Onorato8a9b2202010-02-26 18:56:32 -080010063 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver);
Dianne Hackborn12527f92009-11-11 17:39:50 -080010064 r.receiverTime = now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010065 r.anrCount++;
10066
10067 // Current receiver has passed its expiration date.
10068 if (r.nextReceiver <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010069 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010070 return;
10071 }
10072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010073 Object curReceiver = r.receivers.get(r.nextReceiver-1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010074 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010075 logBroadcastReceiverDiscard(r);
10076 if (curReceiver instanceof BroadcastFilter) {
10077 BroadcastFilter bf = (BroadcastFilter)curReceiver;
10078 if (bf.receiverList.pid != 0
10079 && bf.receiverList.pid != MY_PID) {
10080 synchronized (this.mPidsSelfLocked) {
10081 app = this.mPidsSelfLocked.get(
10082 bf.receiverList.pid);
10083 }
10084 }
10085 } else {
10086 app = r.curApp;
10087 }
10088
10089 if (app != null) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010090 anrMessage = "Broadcast of " + r.intent.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010091 }
10092
10093 if (mPendingBroadcast == r) {
10094 mPendingBroadcast = null;
10095 }
10096
10097 // Move on to the next receiver.
10098 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
10099 r.resultExtras, r.resultAbort, true);
10100 scheduleBroadcastsLocked();
10101 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010102
10103 if (anrMessage != null) {
10104 appNotResponding(app, null, null, anrMessage);
10105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010106 }
10107
10108 private final void processCurBroadcastLocked(BroadcastRecord r,
10109 ProcessRecord app) throws RemoteException {
10110 if (app.thread == null) {
10111 throw new RemoteException();
10112 }
10113 r.receiver = app.thread.asBinder();
10114 r.curApp = app;
10115 app.curReceiver = r;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010116 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010117
10118 // Tell the application to launch this receiver.
10119 r.intent.setComponent(r.curComponent);
10120
10121 boolean started = false;
10122 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010123 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010124 "Delivering to component " + r.curComponent
10125 + ": " + r);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010126 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010127 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
10128 r.resultCode, r.resultData, r.resultExtras, r.ordered);
10129 started = true;
10130 } finally {
10131 if (!started) {
10132 r.receiver = null;
10133 r.curApp = null;
10134 app.curReceiver = null;
10135 }
10136 }
10137
10138 }
10139
10140 static void performReceive(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070010141 Intent intent, int resultCode, String data, Bundle extras,
10142 boolean ordered, boolean sticky) throws RemoteException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010143 if (app != null && app.thread != null) {
10144 // If we have an app thread, do the call through that so it is
10145 // correctly ordered with other one-way calls.
10146 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070010147 data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010148 } else {
Dianne Hackborn68d881c2009-10-05 13:58:17 -070010149 receiver.performReceive(intent, resultCode, data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010150 }
10151 }
10152
10153 private final void deliverToRegisteredReceiver(BroadcastRecord r,
10154 BroadcastFilter filter, boolean ordered) {
10155 boolean skip = false;
10156 if (filter.requiredPermission != null) {
10157 int perm = checkComponentPermission(filter.requiredPermission,
10158 r.callingPid, r.callingUid, -1);
10159 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010160 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010161 + r.intent.toString()
10162 + " from " + r.callerPackage + " (pid="
10163 + r.callingPid + ", uid=" + r.callingUid + ")"
10164 + " requires " + filter.requiredPermission
10165 + " due to registered receiver " + filter);
10166 skip = true;
10167 }
10168 }
10169 if (r.requiredPermission != null) {
10170 int perm = checkComponentPermission(r.requiredPermission,
10171 filter.receiverList.pid, filter.receiverList.uid, -1);
10172 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010173 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010174 + r.intent.toString()
10175 + " to " + filter.receiverList.app
10176 + " (pid=" + filter.receiverList.pid
10177 + ", uid=" + filter.receiverList.uid + ")"
10178 + " requires " + r.requiredPermission
10179 + " due to sender " + r.callerPackage
10180 + " (uid " + r.callingUid + ")");
10181 skip = true;
10182 }
10183 }
10184
10185 if (!skip) {
10186 // If this is not being sent as an ordered broadcast, then we
10187 // don't want to touch the fields that keep track of the current
10188 // state of ordered broadcasts.
10189 if (ordered) {
10190 r.receiver = filter.receiverList.receiver.asBinder();
10191 r.curFilter = filter;
10192 filter.receiverList.curBroadcast = r;
10193 r.state = BroadcastRecord.CALL_IN_RECEIVE;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070010194 if (filter.receiverList.app != null) {
10195 // Bump hosting application to no longer be in background
10196 // scheduling class. Note that we can't do that if there
10197 // isn't an app... but we can only be in that case for
10198 // things that directly call the IActivityManager API, which
10199 // are already core system stuff so don't matter for this.
10200 r.curApp = filter.receiverList.app;
10201 filter.receiverList.app.curReceiver = r;
10202 updateOomAdjLocked();
10203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010204 }
10205 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070010206 if (DEBUG_BROADCAST_LIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010207 int seq = r.intent.getIntExtra("seq", -1);
Dianne Hackborn399cccb2010-04-13 22:57:49 -070010208 Slog.i(TAG, "Delivering to " + filter
Dianne Hackborn82f3f002009-06-16 18:49:05 -070010209 + " (seq=" + seq + "): " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010210 }
10211 performReceive(filter.receiverList.app, filter.receiverList.receiver,
10212 new Intent(r.intent), r.resultCode,
Dianne Hackborn12527f92009-11-11 17:39:50 -080010213 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010214 if (ordered) {
10215 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
10216 }
10217 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010218 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010219 if (ordered) {
10220 r.receiver = null;
10221 r.curFilter = null;
10222 filter.receiverList.curBroadcast = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070010223 if (filter.receiverList.app != null) {
10224 filter.receiverList.app.curReceiver = null;
10225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010226 }
10227 }
10228 }
10229 }
10230
Dianne Hackborn12527f92009-11-11 17:39:50 -080010231 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
10232 if (r.callingUid < 0) {
10233 // This was from a registerReceiver() call; ignore it.
10234 return;
10235 }
10236 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
10237 MAX_BROADCAST_HISTORY-1);
10238 r.finishTime = SystemClock.uptimeMillis();
10239 mBroadcastHistory[0] = r;
10240 }
10241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010242 private final void processNextBroadcast(boolean fromMsg) {
10243 synchronized(this) {
10244 BroadcastRecord r;
10245
Joe Onorato8a9b2202010-02-26 18:56:32 -080010246 if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010247 + mParallelBroadcasts.size() + " broadcasts, "
Dianne Hackborn399cccb2010-04-13 22:57:49 -070010248 + mOrderedBroadcasts.size() + " ordered broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010249
10250 updateCpuStats();
10251
10252 if (fromMsg) {
10253 mBroadcastsScheduled = false;
10254 }
10255
10256 // First, deliver any non-serialized broadcasts right away.
10257 while (mParallelBroadcasts.size() > 0) {
10258 r = mParallelBroadcasts.remove(0);
Dianne Hackborn12527f92009-11-11 17:39:50 -080010259 r.dispatchTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010260 final int N = r.receivers.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010261 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070010262 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010263 for (int i=0; i<N; i++) {
10264 Object target = r.receivers.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010265 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070010266 "Delivering non-ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010267 + target + ": " + r);
10268 deliverToRegisteredReceiver(r, (BroadcastFilter)target, false);
10269 }
Dianne Hackborn12527f92009-11-11 17:39:50 -080010270 addBroadcastToHistoryLocked(r);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010271 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070010272 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010273 }
10274
10275 // Now take care of the next serialized one...
10276
10277 // If we are waiting for a process to come up to handle the next
10278 // broadcast, then do nothing at this point. Just in case, we
10279 // check that the process we're waiting for still exists.
10280 if (mPendingBroadcast != null) {
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070010281 if (DEBUG_BROADCAST_LIGHT) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010282 Slog.v(TAG, "processNextBroadcast: waiting for "
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070010283 + mPendingBroadcast.curApp);
10284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010285
10286 boolean isDead;
10287 synchronized (mPidsSelfLocked) {
10288 isDead = (mPidsSelfLocked.get(mPendingBroadcast.curApp.pid) == null);
10289 }
10290 if (!isDead) {
10291 // It's still alive, so keep waiting
10292 return;
10293 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010294 Slog.w(TAG, "pending app " + mPendingBroadcast.curApp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010295 + " died before responding to broadcast");
10296 mPendingBroadcast = null;
10297 }
10298 }
10299
Dianne Hackborn82f3f002009-06-16 18:49:05 -070010300 boolean looped = false;
10301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010302 do {
10303 if (mOrderedBroadcasts.size() == 0) {
10304 // No more broadcasts pending, so all done!
10305 scheduleAppGcsLocked();
Dianne Hackborn82f3f002009-06-16 18:49:05 -070010306 if (looped) {
10307 // If we had finished the last ordered broadcast, then
10308 // make sure all processes have correct oom and sched
10309 // adjustments.
10310 updateOomAdjLocked();
10311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010312 return;
10313 }
10314 r = mOrderedBroadcasts.get(0);
10315 boolean forceReceive = false;
10316
10317 // Ensure that even if something goes awry with the timeout
10318 // detection, we catch "hung" broadcasts here, discard them,
Jeff Hamiltonacf84742010-05-25 22:10:18 -050010319 // and continue to make progress.
10320 //
10321 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
10322 // receivers don't get executed with with timeouts. They're intended for
10323 // one time heavy lifting after system upgrades and can take
10324 // significant amounts of time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010325 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
Jeff Hamiltonacf84742010-05-25 22:10:18 -050010326 if (mSystemReady && r.dispatchTime > 0) {
10327 long now = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010328 if ((numReceivers > 0) &&
10329 (now > r.dispatchTime + (2*BROADCAST_TIMEOUT*numReceivers))) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010330 Slog.w(TAG, "Hung broadcast discarded after timeout failure:"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010331 + " now=" + now
10332 + " dispatchTime=" + r.dispatchTime
Dianne Hackborn12527f92009-11-11 17:39:50 -080010333 + " startTime=" + r.receiverTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010334 + " intent=" + r.intent
10335 + " numReceivers=" + numReceivers
10336 + " nextReceiver=" + r.nextReceiver
10337 + " state=" + r.state);
10338 broadcastTimeout(); // forcibly finish this broadcast
10339 forceReceive = true;
10340 r.state = BroadcastRecord.IDLE;
10341 }
10342 }
10343
10344 if (r.state != BroadcastRecord.IDLE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010345 if (DEBUG_BROADCAST) Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010346 "processNextBroadcast() called when not idle (state="
10347 + r.state + ")");
10348 return;
10349 }
10350
10351 if (r.receivers == null || r.nextReceiver >= numReceivers
10352 || r.resultAbort || forceReceive) {
10353 // No more receivers for this broadcast! Send the final
10354 // result if requested...
10355 if (r.resultTo != null) {
10356 try {
10357 if (DEBUG_BROADCAST) {
10358 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010359 Slog.i(TAG, "Finishing broadcast " + r.intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010360 + " seq=" + seq + " app=" + r.callerApp);
10361 }
10362 performReceive(r.callerApp, r.resultTo,
10363 new Intent(r.intent), r.resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070010364 r.resultData, r.resultExtras, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010365 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010366 Slog.w(TAG, "Failure sending broadcast result of " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010367 }
10368 }
10369
Joe Onorato8a9b2202010-02-26 18:56:32 -080010370 if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010371 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG);
10372
Joe Onorato8a9b2202010-02-26 18:56:32 -080010373 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070010374 + r);
10375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010376 // ... and on to the next...
Dianne Hackborn12527f92009-11-11 17:39:50 -080010377 addBroadcastToHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010378 mOrderedBroadcasts.remove(0);
10379 r = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070010380 looped = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010381 continue;
10382 }
10383 } while (r == null);
10384
10385 // Get the next receiver...
10386 int recIdx = r.nextReceiver++;
10387
10388 // Keep track of when this receiver started, and make sure there
10389 // is a timeout message pending to kill it if need be.
Dianne Hackborn12527f92009-11-11 17:39:50 -080010390 r.receiverTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010391 if (recIdx == 0) {
Dianne Hackborn12527f92009-11-11 17:39:50 -080010392 r.dispatchTime = r.receiverTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010393
Joe Onorato8a9b2202010-02-26 18:56:32 -080010394 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070010395 + r);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010396 if (DEBUG_BROADCAST) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010397 "Submitting BROADCAST_TIMEOUT_MSG for "
Dianne Hackborn12527f92009-11-11 17:39:50 -080010398 + (r.receiverTime + BROADCAST_TIMEOUT));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010399 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
Dianne Hackborn12527f92009-11-11 17:39:50 -080010400 mHandler.sendMessageAtTime(msg, r.receiverTime+BROADCAST_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010401 }
10402
10403 Object nextReceiver = r.receivers.get(recIdx);
10404 if (nextReceiver instanceof BroadcastFilter) {
10405 // Simple case: this is a registered receiver who gets
10406 // a direct call.
10407 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010408 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070010409 "Delivering ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010410 + filter + ": " + r);
10411 deliverToRegisteredReceiver(r, filter, r.ordered);
10412 if (r.receiver == null || !r.ordered) {
10413 // The receiver has already finished, so schedule to
10414 // process the next one.
Dianne Hackborn399cccb2010-04-13 22:57:49 -070010415 if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing: ordered="
10416 + r.ordered + " receiver=" + r.receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010417 r.state = BroadcastRecord.IDLE;
10418 scheduleBroadcastsLocked();
10419 }
10420 return;
10421 }
10422
10423 // Hard case: need to instantiate the receiver, possibly
10424 // starting its application process to host it.
10425
10426 ResolveInfo info =
10427 (ResolveInfo)nextReceiver;
10428
10429 boolean skip = false;
10430 int perm = checkComponentPermission(info.activityInfo.permission,
10431 r.callingPid, r.callingUid,
10432 info.activityInfo.exported
10433 ? -1 : info.activityInfo.applicationInfo.uid);
10434 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010435 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010436 + r.intent.toString()
10437 + " from " + r.callerPackage + " (pid=" + r.callingPid
10438 + ", uid=" + r.callingUid + ")"
10439 + " requires " + info.activityInfo.permission
10440 + " due to receiver " + info.activityInfo.packageName
10441 + "/" + info.activityInfo.name);
10442 skip = true;
10443 }
10444 if (r.callingUid != Process.SYSTEM_UID &&
10445 r.requiredPermission != null) {
10446 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010447 perm = AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010448 checkPermission(r.requiredPermission,
10449 info.activityInfo.applicationInfo.packageName);
10450 } catch (RemoteException e) {
10451 perm = PackageManager.PERMISSION_DENIED;
10452 }
10453 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010454 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010455 + r.intent + " to "
10456 + info.activityInfo.applicationInfo.packageName
10457 + " requires " + r.requiredPermission
10458 + " due to sender " + r.callerPackage
10459 + " (uid " + r.callingUid + ")");
10460 skip = true;
10461 }
10462 }
10463 if (r.curApp != null && r.curApp.crashing) {
10464 // If the target process is crashing, just skip it.
10465 skip = true;
10466 }
10467
10468 if (skip) {
10469 r.receiver = null;
10470 r.curFilter = null;
10471 r.state = BroadcastRecord.IDLE;
10472 scheduleBroadcastsLocked();
10473 return;
10474 }
10475
10476 r.state = BroadcastRecord.APP_RECEIVE;
10477 String targetProcess = info.activityInfo.processName;
10478 r.curComponent = new ComponentName(
10479 info.activityInfo.applicationInfo.packageName,
10480 info.activityInfo.name);
10481 r.curReceiver = info.activityInfo;
10482
10483 // Is this receiver's application already running?
10484 ProcessRecord app = getProcessRecordLocked(targetProcess,
10485 info.activityInfo.applicationInfo.uid);
10486 if (app != null && app.thread != null) {
10487 try {
10488 processCurBroadcastLocked(r, app);
10489 return;
10490 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010491 Slog.w(TAG, "Exception when sending broadcast to "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010492 + r.curComponent, e);
10493 }
10494
10495 // If a dead object exception was thrown -- fall through to
10496 // restart the application.
10497 }
10498
Dianne Hackborn9acc0302009-08-25 00:27:12 -070010499 // Not running -- get it started, to be executed when the app comes up.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010500 if ((r.curApp=startProcessLocked(targetProcess,
10501 info.activityInfo.applicationInfo, true,
10502 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070010503 "broadcast", r.curComponent,
10504 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0))
10505 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010506 // Ah, this recipient is unavailable. Finish it if necessary,
10507 // and mark the broadcast record as ready for the next.
Joe Onorato8a9b2202010-02-26 18:56:32 -080010508 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010509 + info.activityInfo.applicationInfo.packageName + "/"
10510 + info.activityInfo.applicationInfo.uid + " for broadcast "
10511 + r.intent + ": process is bad");
10512 logBroadcastReceiverDiscard(r);
10513 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
10514 r.resultExtras, r.resultAbort, true);
10515 scheduleBroadcastsLocked();
10516 r.state = BroadcastRecord.IDLE;
10517 return;
10518 }
10519
10520 mPendingBroadcast = r;
10521 }
10522 }
10523
10524 // =========================================================
10525 // INSTRUMENTATION
10526 // =========================================================
10527
10528 public boolean startInstrumentation(ComponentName className,
10529 String profileFile, int flags, Bundle arguments,
10530 IInstrumentationWatcher watcher) {
10531 // Refuse possible leaked file descriptors
10532 if (arguments != null && arguments.hasFileDescriptors()) {
10533 throw new IllegalArgumentException("File descriptors passed in Bundle");
10534 }
10535
10536 synchronized(this) {
10537 InstrumentationInfo ii = null;
10538 ApplicationInfo ai = null;
10539 try {
10540 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010541 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010543 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010544 } catch (PackageManager.NameNotFoundException e) {
10545 }
10546 if (ii == null) {
10547 reportStartInstrumentationFailure(watcher, className,
10548 "Unable to find instrumentation info for: " + className);
10549 return false;
10550 }
10551 if (ai == null) {
10552 reportStartInstrumentationFailure(watcher, className,
10553 "Unable to find instrumentation target package: " + ii.targetPackage);
10554 return false;
10555 }
10556
10557 int match = mContext.getPackageManager().checkSignatures(
10558 ii.targetPackage, ii.packageName);
10559 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
10560 String msg = "Permission Denial: starting instrumentation "
10561 + className + " from pid="
10562 + Binder.getCallingPid()
10563 + ", uid=" + Binder.getCallingPid()
10564 + " not allowed because package " + ii.packageName
10565 + " does not have a signature matching the target "
10566 + ii.targetPackage;
10567 reportStartInstrumentationFailure(watcher, className, msg);
10568 throw new SecurityException(msg);
10569 }
10570
10571 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080010572 forceStopPackageLocked(ii.targetPackage, -1, true, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010573 ProcessRecord app = addAppLocked(ai);
10574 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070010575 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010576 app.instrumentationProfileFile = profileFile;
10577 app.instrumentationArguments = arguments;
10578 app.instrumentationWatcher = watcher;
10579 app.instrumentationResultClass = className;
10580 Binder.restoreCallingIdentity(origId);
10581 }
10582
10583 return true;
10584 }
10585
10586 /**
10587 * Report errors that occur while attempting to start Instrumentation. Always writes the
10588 * error to the logs, but if somebody is watching, send the report there too. This enables
10589 * the "am" command to report errors with more information.
10590 *
10591 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
10592 * @param cn The component name of the instrumentation.
10593 * @param report The error report.
10594 */
10595 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
10596 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010597 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010598 try {
10599 if (watcher != null) {
10600 Bundle results = new Bundle();
10601 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
10602 results.putString("Error", report);
10603 watcher.instrumentationStatus(cn, -1, results);
10604 }
10605 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010606 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010607 }
10608 }
10609
10610 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
10611 if (app.instrumentationWatcher != null) {
10612 try {
10613 // NOTE: IInstrumentationWatcher *must* be oneway here
10614 app.instrumentationWatcher.instrumentationFinished(
10615 app.instrumentationClass,
10616 resultCode,
10617 results);
10618 } catch (RemoteException e) {
10619 }
10620 }
10621 app.instrumentationWatcher = null;
10622 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070010623 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010624 app.instrumentationProfileFile = null;
10625 app.instrumentationArguments = null;
10626
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080010627 forceStopPackageLocked(app.processName, -1, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628 }
10629
10630 public void finishInstrumentation(IApplicationThread target,
10631 int resultCode, Bundle results) {
10632 // Refuse possible leaked file descriptors
10633 if (results != null && results.hasFileDescriptors()) {
10634 throw new IllegalArgumentException("File descriptors passed in Intent");
10635 }
10636
10637 synchronized(this) {
10638 ProcessRecord app = getRecordForAppLocked(target);
10639 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010640 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010641 return;
10642 }
10643 final long origId = Binder.clearCallingIdentity();
10644 finishInstrumentationLocked(app, resultCode, results);
10645 Binder.restoreCallingIdentity(origId);
10646 }
10647 }
10648
10649 // =========================================================
10650 // CONFIGURATION
10651 // =========================================================
10652
10653 public ConfigurationInfo getDeviceConfigurationInfo() {
10654 ConfigurationInfo config = new ConfigurationInfo();
10655 synchronized (this) {
10656 config.reqTouchScreen = mConfiguration.touchscreen;
10657 config.reqKeyboardType = mConfiguration.keyboard;
10658 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070010659 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
10660 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010661 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
10662 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070010663 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
10664 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010665 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
10666 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070010667 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010668 }
10669 return config;
10670 }
10671
10672 public Configuration getConfiguration() {
10673 Configuration ci;
10674 synchronized(this) {
10675 ci = new Configuration(mConfiguration);
10676 }
10677 return ci;
10678 }
10679
10680 public void updateConfiguration(Configuration values) {
10681 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
10682 "updateConfiguration()");
10683
10684 synchronized(this) {
10685 if (values == null && mWindowManager != null) {
10686 // sentinel: fetch the current configuration from the window manager
10687 values = mWindowManager.computeNewConfiguration();
10688 }
10689
10690 final long origId = Binder.clearCallingIdentity();
10691 updateConfigurationLocked(values, null);
10692 Binder.restoreCallingIdentity(origId);
10693 }
10694 }
10695
10696 /**
10697 * Do either or both things: (1) change the current configuration, and (2)
10698 * make sure the given activity is running with the (now) current
10699 * configuration. Returns true if the activity has been left running, or
10700 * false if <var>starting</var> is being destroyed to match the new
10701 * configuration.
10702 */
10703 public boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010704 ActivityRecord starting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010705 int changes = 0;
10706
10707 boolean kept = true;
10708
10709 if (values != null) {
10710 Configuration newConfig = new Configuration(mConfiguration);
10711 changes = newConfig.updateFrom(values);
10712 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070010713 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010714 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010715 }
10716
Doug Zongker2bec3d42009-12-04 12:52:44 -080010717 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010718
10719 if (values.locale != null) {
10720 saveLocaleLocked(values.locale,
10721 !values.locale.equals(mConfiguration.locale),
10722 values.userSetLocale);
10723 }
10724
Dianne Hackborne36d6e22010-02-17 19:46:25 -080010725 mConfigurationSeq++;
10726 if (mConfigurationSeq <= 0) {
10727 mConfigurationSeq = 1;
10728 }
10729 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010730 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010731 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080010732
10733 AttributeCache ac = AttributeCache.instance();
10734 if (ac != null) {
10735 ac.updateConfiguration(mConfiguration);
10736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010737
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080010738 if (Settings.System.hasInterestingConfigurationChanges(changes)) {
10739 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
10740 msg.obj = new Configuration(mConfiguration);
10741 mHandler.sendMessage(msg);
10742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010743
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010744 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10745 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010746 try {
10747 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010748 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070010749 + app.processName + " new config " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010750 app.thread.scheduleConfigurationChanged(mConfiguration);
10751 }
10752 } catch (Exception e) {
10753 }
10754 }
10755 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080010756 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
10757 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010758 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
10759 null, false, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080010760 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
10761 broadcastIntentLocked(null, null,
10762 new Intent(Intent.ACTION_LOCALE_CHANGED),
10763 null, null, 0, null, null,
10764 null, false, false, MY_PID, Process.SYSTEM_UID);
10765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766 }
10767 }
10768
10769 if (changes != 0 && starting == null) {
10770 // If the configuration changed, and the caller is not already
10771 // in the process of starting an activity, then find the top
10772 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070010773 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010774 }
10775
10776 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070010777 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010778 if (kept) {
10779 // If this didn't result in the starting activity being
10780 // destroyed, then we need to make sure at this point that all
10781 // other activities are made visible.
Joe Onorato8a9b2202010-02-26 18:56:32 -080010782 if (DEBUG_SWITCH) Slog.i(TAG, "Config didn't destroy " + starting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010783 + ", ensuring others are correct.");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070010784 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010785 }
10786 }
10787
Dianne Hackborne36d6e22010-02-17 19:46:25 -080010788 if (values != null && mWindowManager != null) {
10789 mWindowManager.setNewConfiguration(mConfiguration);
10790 }
10791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010792 return kept;
10793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010794
10795 /**
10796 * Save the locale. You must be inside a synchronized (this) block.
10797 */
10798 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
10799 if(isDiff) {
10800 SystemProperties.set("user.language", l.getLanguage());
10801 SystemProperties.set("user.region", l.getCountry());
10802 }
10803
10804 if(isPersist) {
10805 SystemProperties.set("persist.sys.language", l.getLanguage());
10806 SystemProperties.set("persist.sys.country", l.getCountry());
10807 SystemProperties.set("persist.sys.localevar", l.getVariant());
10808 }
10809 }
10810
10811 // =========================================================
10812 // LIFETIME MANAGEMENT
10813 // =========================================================
10814
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010815 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
10816 ProcessRecord TOP_APP, boolean recursed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010817 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010818 // This adjustment has already been computed. If we are calling
10819 // from the top, we may have already computed our adjustment with
10820 // an earlier hidden adjustment that isn't really for us... if
10821 // so, use the new hidden adjustment.
10822 if (!recursed && app.hidden) {
10823 app.curAdj = hiddenAdj;
10824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 return app.curAdj;
10826 }
10827
10828 if (app.thread == null) {
10829 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010830 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010831 return (app.curAdj=EMPTY_APP_ADJ);
10832 }
10833
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010834 if (app.maxAdj <= FOREGROUND_APP_ADJ) {
10835 // The max adjustment doesn't allow this app to be anything
10836 // below foreground, so it is not worth doing work for it.
10837 app.adjType = "fixed";
10838 app.adjSeq = mAdjSeq;
10839 app.curRawAdj = app.maxAdj;
10840 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
10841 return (app.curAdj=app.maxAdj);
10842 }
10843
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010844 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010845 app.adjSource = null;
10846 app.adjTarget = null;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010847 app.empty = false;
10848 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010849
The Android Open Source Project4df24232009-03-05 14:34:35 -080010850 // Determine the importance of the process, starting with most
10851 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010852 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010853 int schedGroup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010854 int N;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010855 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010856 // The last app on the list is the foreground app.
10857 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010858 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010859 app.adjType = "top-activity";
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010860 } else if (app.instrumentationClass != null) {
10861 // Don't want to kill running instrumentation.
10862 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010863 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010864 app.adjType = "instrumentation";
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010865 } else if (app.persistentActivities > 0) {
10866 // Special persistent activities... shouldn't be used these days.
10867 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010868 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010869 app.adjType = "persistent";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010870 } else if (app.curReceiver != null ||
10871 (mPendingBroadcast != null && mPendingBroadcast.curApp == app)) {
10872 // An app that is currently receiving a broadcast also
10873 // counts as being in the foreground.
10874 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010875 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010876 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010877 } else if (app.executingServices.size() > 0) {
10878 // An app that is currently executing a service callback also
10879 // counts as being in the foreground.
10880 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010881 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010882 app.adjType = "exec-service";
10883 } else if (app.foregroundServices) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010884 // The user is aware of this app, so make it visible.
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010885 adj = PERCEPTIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010886 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010887 app.adjType = "foreground-service";
10888 } else if (app.forcingToForeground != null) {
10889 // The user is aware of this app, so make it visible.
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010890 adj = PERCEPTIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010891 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010892 app.adjType = "force-foreground";
10893 app.adjSource = app.forcingToForeground;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010894 } else if (app == mHeavyWeightProcess) {
10895 // We don't want to kill the current heavy-weight process.
10896 adj = HEAVY_WEIGHT_APP_ADJ;
10897 schedGroup = Process.THREAD_GROUP_DEFAULT;
10898 app.adjType = "heavy";
The Android Open Source Project4df24232009-03-05 14:34:35 -080010899 } else if (app == mHomeProcess) {
10900 // This process is hosting what we currently consider to be the
10901 // home app, so we don't want to let it go into the background.
10902 adj = HOME_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010903 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010904 app.adjType = "home";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010905 } else if ((N=app.activities.size()) != 0) {
10906 // This app is in the background with paused activities.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010907 app.hidden = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010908 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010909 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010910 app.adjType = "bg-activities";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010911 N = app.activities.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010912 for (int j=0; j<N; j++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010913 if (app.activities.get(j).visible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010914 // This app has a visible activity!
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010915 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010916 adj = VISIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010917 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010918 app.adjType = "visible";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010919 break;
10920 }
10921 }
10922 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010923 // A very not-needed process. If this is lower in the lru list,
10924 // we will push it in to the empty bucket.
10925 app.hidden = true;
10926 app.empty = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010927 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010928 adj = hiddenAdj;
10929 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010930 }
10931
Joe Onorato8a9b2202010-02-26 18:56:32 -080010932 //Slog.i(TAG, "OOM " + app + ": initial adj=" + adj);
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010933
The Android Open Source Project4df24232009-03-05 14:34:35 -080010934 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010935 // there are applications dependent on our services or providers, but
10936 // this gives us a baseline and makes sure we don't get into an
10937 // infinite recursion.
10938 app.adjSeq = mAdjSeq;
10939 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010940
Christopher Tate6fa95972009-06-05 18:43:55 -070010941 if (mBackupTarget != null && app == mBackupTarget.app) {
10942 // If possible we want to avoid killing apps while they're being backed up
10943 if (adj > BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010944 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Christopher Tate6fa95972009-06-05 18:43:55 -070010945 adj = BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010946 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010947 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070010948 }
10949 }
10950
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010951 if (app.services.size() != 0 && (adj > FOREGROUND_APP_ADJ
10952 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010953 final long now = SystemClock.uptimeMillis();
10954 // This process is more important if the top activity is
10955 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010956 Iterator<ServiceRecord> jt = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010957 while (jt.hasNext() && adj > FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010958 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010959 if (s.startRequested) {
10960 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
10961 // This service has seen some activity within
10962 // recent memory, so we will keep its process ahead
10963 // of the background processes.
10964 if (adj > SECONDARY_SERVER_ADJ) {
10965 adj = SECONDARY_SERVER_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010966 app.adjType = "started-services";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010967 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010968 }
10969 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080010970 // If we have let the service slide into the background
10971 // state, still have some text describing what it is doing
10972 // even though the service no longer has an impact.
10973 if (adj > SECONDARY_SERVER_ADJ) {
10974 app.adjType = "started-bg-services";
10975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010976 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010977 if (s.connections.size() > 0 && (adj > FOREGROUND_APP_ADJ
10978 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010979 Iterator<ConnectionRecord> kt
10980 = s.connections.values().iterator();
10981 while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
10982 // XXX should compute this based on the max of
10983 // all connected clients.
10984 ConnectionRecord cr = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070010985 if (cr.binding.client == app) {
10986 // Binding to ourself is not interesting.
10987 continue;
10988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010989 if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
10990 ProcessRecord client = cr.binding.client;
10991 int myHiddenAdj = hiddenAdj;
10992 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010993 if (client.hiddenAdj >= VISIBLE_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994 myHiddenAdj = client.hiddenAdj;
10995 } else {
10996 myHiddenAdj = VISIBLE_APP_ADJ;
10997 }
10998 }
10999 int clientAdj = computeOomAdjLocked(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011000 client, myHiddenAdj, TOP_APP, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011001 if (adj > clientAdj) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011002 adj = clientAdj >= VISIBLE_APP_ADJ
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011003 ? clientAdj : VISIBLE_APP_ADJ;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011004 if (!client.hidden) {
11005 app.hidden = false;
11006 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011007 app.adjType = "service";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011008 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
11009 .REASON_SERVICE_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011010 app.adjSource = cr.binding.client;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070011011 app.adjTarget = s.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011012 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011013 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
11014 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
11015 schedGroup = Process.THREAD_GROUP_DEFAULT;
11016 }
11017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011018 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011019 ActivityRecord a = cr.activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011020 //if (a != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011021 // Slog.i(TAG, "Connection to " + a ": state=" + a.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011022 //}
11023 if (a != null && adj > FOREGROUND_APP_ADJ &&
11024 (a.state == ActivityState.RESUMED
11025 || a.state == ActivityState.PAUSING)) {
11026 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011027 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011028 app.hidden = false;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011029 app.adjType = "service";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011030 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
11031 .REASON_SERVICE_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011032 app.adjSource = a;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070011033 app.adjTarget = s.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011034 }
11035 }
11036 }
11037 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070011038
11039 // Finally, f this process has active services running in it, we
11040 // would like to avoid killing it unless it would prevent the current
11041 // application from running. By default we put the process in
11042 // with the rest of the background processes; as we scan through
11043 // its services we may bump it up from there.
11044 if (adj > hiddenAdj) {
11045 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011046 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070011047 app.adjType = "bg-services";
11048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011049 }
11050
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011051 if (app.pubProviders.size() != 0 && (adj > FOREGROUND_APP_ADJ
11052 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011053 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011054 while (jt.hasNext() && (adj > FOREGROUND_APP_ADJ
11055 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011056 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011057 if (cpr.clients.size() != 0) {
11058 Iterator<ProcessRecord> kt = cpr.clients.iterator();
11059 while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
11060 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070011061 if (client == app) {
11062 // Being our own client is not interesting.
11063 continue;
11064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011065 int myHiddenAdj = hiddenAdj;
11066 if (myHiddenAdj > client.hiddenAdj) {
11067 if (client.hiddenAdj > FOREGROUND_APP_ADJ) {
11068 myHiddenAdj = client.hiddenAdj;
11069 } else {
11070 myHiddenAdj = FOREGROUND_APP_ADJ;
11071 }
11072 }
11073 int clientAdj = computeOomAdjLocked(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011074 client, myHiddenAdj, TOP_APP, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011075 if (adj > clientAdj) {
11076 adj = clientAdj > FOREGROUND_APP_ADJ
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011077 ? clientAdj : FOREGROUND_APP_ADJ;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011078 if (!client.hidden) {
11079 app.hidden = false;
11080 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011081 app.adjType = "provider";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011082 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
11083 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011084 app.adjSource = client;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070011085 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011086 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011087 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
11088 schedGroup = Process.THREAD_GROUP_DEFAULT;
11089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011090 }
11091 }
11092 // If the provider has external (non-framework) process
11093 // dependencies, ensure that its adjustment is at least
11094 // FOREGROUND_APP_ADJ.
11095 if (cpr.externals != 0) {
11096 if (adj > FOREGROUND_APP_ADJ) {
11097 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011098 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011099 app.hidden = false;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011100 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070011101 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 }
11103 }
11104 }
11105 }
11106
11107 app.curRawAdj = adj;
11108
Joe Onorato8a9b2202010-02-26 18:56:32 -080011109 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011110 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
11111 if (adj > app.maxAdj) {
11112 adj = app.maxAdj;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011113 if (app.maxAdj <= PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011114 schedGroup = Process.THREAD_GROUP_DEFAULT;
11115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011116 }
11117
11118 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011119 app.curSchedGroup = schedGroup;
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070011120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011121 return adj;
11122 }
11123
11124 /**
11125 * Ask a given process to GC right now.
11126 */
11127 final void performAppGcLocked(ProcessRecord app) {
11128 try {
11129 app.lastRequestedGc = SystemClock.uptimeMillis();
11130 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011131 if (app.reportLowMemory) {
11132 app.reportLowMemory = false;
11133 app.thread.scheduleLowMemory();
11134 } else {
11135 app.thread.processInBackground();
11136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011137 }
11138 } catch (Exception e) {
11139 // whatever.
11140 }
11141 }
11142
11143 /**
11144 * Returns true if things are idle enough to perform GCs.
11145 */
Josh Bartel7f208742010-02-25 11:01:44 -060011146 private final boolean canGcNowLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011147 return mParallelBroadcasts.size() == 0
11148 && mOrderedBroadcasts.size() == 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011149 && (mSleeping || (mMainStack.mResumedActivity != null &&
11150 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011151 }
11152
11153 /**
11154 * Perform GCs on all processes that are waiting for it, but only
11155 * if things are idle.
11156 */
11157 final void performAppGcsLocked() {
11158 final int N = mProcessesToGc.size();
11159 if (N <= 0) {
11160 return;
11161 }
Josh Bartel7f208742010-02-25 11:01:44 -060011162 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011163 while (mProcessesToGc.size() > 0) {
11164 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011165 if (proc.curRawAdj > PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011166 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
11167 <= SystemClock.uptimeMillis()) {
11168 // To avoid spamming the system, we will GC processes one
11169 // at a time, waiting a few seconds between each.
11170 performAppGcLocked(proc);
11171 scheduleAppGcsLocked();
11172 return;
11173 } else {
11174 // It hasn't been long enough since we last GCed this
11175 // process... put it in the list to wait for its time.
11176 addProcessToGcListLocked(proc);
11177 break;
11178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011179 }
11180 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011181
11182 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011183 }
11184 }
11185
11186 /**
11187 * If all looks good, perform GCs on all processes waiting for them.
11188 */
11189 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060011190 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011191 performAppGcsLocked();
11192 return;
11193 }
11194 // Still not idle, wait some more.
11195 scheduleAppGcsLocked();
11196 }
11197
11198 /**
11199 * Schedule the execution of all pending app GCs.
11200 */
11201 final void scheduleAppGcsLocked() {
11202 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011203
11204 if (mProcessesToGc.size() > 0) {
11205 // Schedule a GC for the time to the next process.
11206 ProcessRecord proc = mProcessesToGc.get(0);
11207 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
11208
11209 long when = mProcessesToGc.get(0).lastRequestedGc + GC_MIN_INTERVAL;
11210 long now = SystemClock.uptimeMillis();
11211 if (when < (now+GC_TIMEOUT)) {
11212 when = now + GC_TIMEOUT;
11213 }
11214 mHandler.sendMessageAtTime(msg, when);
11215 }
11216 }
11217
11218 /**
11219 * Add a process to the array of processes waiting to be GCed. Keeps the
11220 * list in sorted order by the last GC time. The process can't already be
11221 * on the list.
11222 */
11223 final void addProcessToGcListLocked(ProcessRecord proc) {
11224 boolean added = false;
11225 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
11226 if (mProcessesToGc.get(i).lastRequestedGc <
11227 proc.lastRequestedGc) {
11228 added = true;
11229 mProcessesToGc.add(i+1, proc);
11230 break;
11231 }
11232 }
11233 if (!added) {
11234 mProcessesToGc.add(0, proc);
11235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011236 }
11237
11238 /**
11239 * Set up to ask a process to GC itself. This will either do it
11240 * immediately, or put it on the list of processes to gc the next
11241 * time things are idle.
11242 */
11243 final void scheduleAppGcLocked(ProcessRecord app) {
11244 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011245 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011246 return;
11247 }
11248 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011249 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011250 scheduleAppGcsLocked();
11251 }
11252 }
11253
11254 private final boolean updateOomAdjLocked(
11255 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP) {
11256 app.hiddenAdj = hiddenAdj;
11257
11258 if (app.thread == null) {
11259 return true;
11260 }
11261
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011262 int adj = computeOomAdjLocked(app, hiddenAdj, TOP_APP, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011263
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011264 if ((app.pid != 0 && app.pid != MY_PID) || Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011265 if (app.curRawAdj != app.setRawAdj) {
11266 if (app.curRawAdj > FOREGROUND_APP_ADJ
11267 && app.setRawAdj <= FOREGROUND_APP_ADJ) {
11268 // If this app is transitioning from foreground to
11269 // non-foreground, have it do a gc.
11270 scheduleAppGcLocked(app);
11271 } else if (app.curRawAdj >= HIDDEN_APP_MIN_ADJ
11272 && app.setRawAdj < HIDDEN_APP_MIN_ADJ) {
11273 // Likewise do a gc when an app is moving in to the
11274 // background (such as a service stopping).
11275 scheduleAppGcLocked(app);
11276 }
11277 app.setRawAdj = app.curRawAdj;
11278 }
11279 if (adj != app.setAdj) {
11280 if (Process.setOomAdj(app.pid, adj)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011281 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282 TAG, "Set app " + app.processName +
11283 " oom adj to " + adj);
11284 app.setAdj = adj;
11285 } else {
11286 return false;
11287 }
11288 }
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070011289 if (app.setSchedGroup != app.curSchedGroup) {
11290 app.setSchedGroup = app.curSchedGroup;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011291 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070011292 "Setting process group of " + app.processName
11293 + " to " + app.curSchedGroup);
11294 if (true) {
San Mehat9438de22009-06-10 09:11:28 -070011295 long oldId = Binder.clearCallingIdentity();
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070011296 try {
11297 Process.setProcessGroup(app.pid, app.curSchedGroup);
11298 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011299 Slog.w(TAG, "Failed setting process group of " + app.pid
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070011300 + " to " + app.curSchedGroup);
San Mehat9438de22009-06-10 09:11:28 -070011301 e.printStackTrace();
11302 } finally {
11303 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070011304 }
11305 }
11306 if (false) {
11307 if (app.thread != null) {
11308 try {
11309 app.thread.setSchedulingGroup(app.curSchedGroup);
11310 } catch (RemoteException e) {
11311 }
11312 }
11313 }
11314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011315 }
11316
11317 return true;
11318 }
11319
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011320 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011321 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011322 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011323 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011324 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011325 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011326 }
11327 }
11328 return resumedActivity;
11329 }
11330
11331 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011332 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
11334 int curAdj = app.curAdj;
11335 final boolean wasHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
11336 && app.curAdj <= HIDDEN_APP_MAX_ADJ;
11337
11338 mAdjSeq++;
11339
11340 final boolean res = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP);
11341 if (res) {
11342 final boolean nowHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
11343 && app.curAdj <= HIDDEN_APP_MAX_ADJ;
11344 if (nowHidden != wasHidden) {
11345 // Changed to/from hidden state, so apps after it in the LRU
11346 // list may also be changed.
11347 updateOomAdjLocked();
11348 }
11349 }
11350 return res;
11351 }
11352
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011353 final boolean updateOomAdjLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011354 boolean didOomAdj = true;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011355 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011356 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
11357
11358 if (false) {
11359 RuntimeException e = new RuntimeException();
11360 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011361 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 }
11363
11364 mAdjSeq++;
11365
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080011366 // Let's determine how many processes we have running vs.
11367 // how many slots we have for background processes; we may want
11368 // to put multiple processes in a slot of there are enough of
11369 // them.
11370 int numSlots = HIDDEN_APP_MAX_ADJ - HIDDEN_APP_MIN_ADJ + 1;
11371 int factor = (mLruProcesses.size()-4)/numSlots;
11372 if (factor < 1) factor = 1;
11373 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070011374 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080011375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011376 // First try updating the OOM adjustment for each of the
11377 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011378 int i = mLruProcesses.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 int curHiddenAdj = HIDDEN_APP_MIN_ADJ;
11380 while (i > 0) {
11381 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011382 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011383 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011384 if (updateOomAdjLocked(app, curHiddenAdj, TOP_APP)) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011385 if (curHiddenAdj < EMPTY_APP_ADJ
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011386 && app.curAdj == curHiddenAdj) {
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080011387 step++;
11388 if (step >= factor) {
11389 step = 0;
11390 curHiddenAdj++;
11391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011392 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070011393 if (app.curAdj >= HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn149427c2010-04-23 14:20:03 -070011394 if (!app.killedBackground) {
11395 numHidden++;
11396 if (numHidden > MAX_HIDDEN_APPS) {
Dianne Hackborn906497c2010-05-10 15:57:38 -070011397 Slog.i(TAG, "No longer want " + app.processName
11398 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackborn149427c2010-04-23 14:20:03 -070011399 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
11400 app.processName, app.setAdj, "too many background");
11401 app.killedBackground = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -070011402 Process.killProcessQuiet(app.pid);
Dianne Hackborn149427c2010-04-23 14:20:03 -070011403 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070011404 }
11405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011406 } else {
11407 didOomAdj = false;
11408 }
11409 }
11410
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011411 // If we return false, we will fall back on killing processes to
11412 // have a fixed limit. Do this if a limit has been requested; else
11413 // only return false if one of the adjustments failed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011414 return ENFORCE_PROCESS_LIMIT || mProcessLimit > 0 ? false : didOomAdj;
11415 }
11416
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011417 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 synchronized (this) {
11419 int i;
11420
11421 // First remove any unused application processes whose package
11422 // has been removed.
11423 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
11424 final ProcessRecord app = mRemovedProcesses.get(i);
11425 if (app.activities.size() == 0
11426 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011427 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011428 TAG, "Exiting empty application process "
11429 + app.processName + " ("
11430 + (app.thread != null ? app.thread.asBinder() : null)
11431 + ")\n");
11432 if (app.pid > 0 && app.pid != MY_PID) {
11433 Process.killProcess(app.pid);
11434 } else {
11435 try {
11436 app.thread.scheduleExit();
11437 } catch (Exception e) {
11438 // Ignore exceptions.
11439 }
11440 }
11441 cleanUpApplicationRecordLocked(app, false, -1);
11442 mRemovedProcesses.remove(i);
11443
11444 if (app.persistent) {
11445 if (app.persistent) {
11446 addAppLocked(app.info);
11447 }
11448 }
11449 }
11450 }
11451
11452 // Now try updating the OOM adjustment for each of the
11453 // application processes based on their current state.
11454 // If the setOomAdj() API is not supported, then go with our
11455 // back-up plan...
11456 if (!updateOomAdjLocked()) {
11457
11458 // Count how many processes are running services.
11459 int numServiceProcs = 0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011460 for (i=mLruProcesses.size()-1; i>=0; i--) {
11461 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011462
11463 if (app.persistent || app.services.size() != 0
11464 || app.curReceiver != null
11465 || app.persistentActivities > 0) {
11466 // Don't count processes holding services against our
11467 // maximum process count.
Joe Onorato8a9b2202010-02-26 18:56:32 -080011468 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011469 TAG, "Not trimming app " + app + " with services: "
11470 + app.services);
11471 numServiceProcs++;
11472 }
11473 }
11474
11475 int curMaxProcs = mProcessLimit;
11476 if (curMaxProcs <= 0) curMaxProcs = MAX_PROCESSES;
11477 if (mAlwaysFinishActivities) {
11478 curMaxProcs = 1;
11479 }
11480 curMaxProcs += numServiceProcs;
11481
11482 // Quit as many processes as we can to get down to the desired
11483 // process count. First remove any processes that no longer
11484 // have activites running in them.
11485 for ( i=0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011486 i<mLruProcesses.size()
11487 && mLruProcesses.size() > curMaxProcs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011488 i++) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011489 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011490 // Quit an application only if it is not currently
11491 // running any activities.
11492 if (!app.persistent && app.activities.size() == 0
11493 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011494 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011495 TAG, "Exiting empty application process "
11496 + app.processName + " ("
11497 + (app.thread != null ? app.thread.asBinder() : null)
11498 + ")\n");
11499 if (app.pid > 0 && app.pid != MY_PID) {
11500 Process.killProcess(app.pid);
11501 } else {
11502 try {
11503 app.thread.scheduleExit();
11504 } catch (Exception e) {
11505 // Ignore exceptions.
11506 }
11507 }
11508 // todo: For now we assume the application is not buggy
11509 // or evil, and will quit as a result of our request.
11510 // Eventually we need to drive this off of the death
11511 // notification, and kill the process if it takes too long.
11512 cleanUpApplicationRecordLocked(app, false, i);
11513 i--;
11514 }
11515 }
11516
11517 // If we still have too many processes, now from the least
11518 // recently used process we start finishing activities.
Joe Onorato8a9b2202010-02-26 18:56:32 -080011519 if (Config.LOGV) Slog.v(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011520 TAG, "*** NOW HAVE " + mLruProcesses.size() +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011521 " of " + curMaxProcs + " processes");
11522 for ( i=0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011523 i<mLruProcesses.size()
11524 && mLruProcesses.size() > curMaxProcs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011525 i++) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011526 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011527 // Quit the application only if we have a state saved for
11528 // all of its activities.
11529 boolean canQuit = !app.persistent && app.curReceiver == null
11530 && app.services.size() == 0
11531 && app.persistentActivities == 0;
11532 int NUMA = app.activities.size();
11533 int j;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011534 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011535 TAG, "Looking to quit " + app.processName);
11536 for (j=0; j<NUMA && canQuit; j++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011537 ActivityRecord r = app.activities.get(j);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011538 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011539 TAG, " " + r.intent.getComponent().flattenToShortString()
11540 + ": frozen=" + r.haveState + ", visible=" + r.visible);
11541 canQuit = (r.haveState || !r.stateNotNeeded)
11542 && !r.visible && r.stopped;
11543 }
11544 if (canQuit) {
11545 // Finish all of the activities, and then the app itself.
11546 for (j=0; j<NUMA; j++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011547 ActivityRecord r = app.activities.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011548 if (!r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011549 r.stack.destroyActivityLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011550 }
11551 r.resultTo = null;
11552 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011553 Slog.i(TAG, "Exiting application process "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011554 + app.processName + " ("
11555 + (app.thread != null ? app.thread.asBinder() : null)
11556 + ")\n");
11557 if (app.pid > 0 && app.pid != MY_PID) {
11558 Process.killProcess(app.pid);
11559 } else {
11560 try {
11561 app.thread.scheduleExit();
11562 } catch (Exception e) {
11563 // Ignore exceptions.
11564 }
11565 }
11566 // todo: For now we assume the application is not buggy
11567 // or evil, and will quit as a result of our request.
11568 // Eventually we need to drive this off of the death
11569 // notification, and kill the process if it takes too long.
11570 cleanUpApplicationRecordLocked(app, false, i);
11571 i--;
11572 //dump();
11573 }
11574 }
11575
11576 }
11577
11578 int curMaxActivities = MAX_ACTIVITIES;
11579 if (mAlwaysFinishActivities) {
11580 curMaxActivities = 1;
11581 }
11582
11583 // Finally, if there are too many activities now running, try to
11584 // finish as many as we can to get back down to the limit.
11585 for ( i=0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011586 i<mMainStack.mLRUActivities.size()
11587 && mMainStack.mLRUActivities.size() > curMaxActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011588 i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011589 final ActivityRecord r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011590 = (ActivityRecord)mMainStack.mLRUActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011591
11592 // We can finish this one if we have its icicle saved and
11593 // it is not persistent.
11594 if ((r.haveState || !r.stateNotNeeded) && !r.visible
11595 && r.stopped && !r.persistent && !r.finishing) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011596 final int origSize = mMainStack.mLRUActivities.size();
11597 r.stack.destroyActivityLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011598
11599 // This will remove it from the LRU list, so keep
11600 // our index at the same value. Note that this check to
11601 // see if the size changes is just paranoia -- if
11602 // something unexpected happens, we don't want to end up
11603 // in an infinite loop.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011604 if (origSize > mMainStack.mLRUActivities.size()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011605 i--;
11606 }
11607 }
11608 }
11609 }
11610 }
11611
11612 /** This method sends the specified signal to each of the persistent apps */
11613 public void signalPersistentProcesses(int sig) throws RemoteException {
11614 if (sig != Process.SIGNAL_USR1) {
11615 throw new SecurityException("Only SIGNAL_USR1 is allowed");
11616 }
11617
11618 synchronized (this) {
11619 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
11620 != PackageManager.PERMISSION_GRANTED) {
11621 throw new SecurityException("Requires permission "
11622 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
11623 }
11624
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011625 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11626 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011627 if (r.thread != null && r.persistent) {
11628 Process.sendSignal(r.pid, sig);
11629 }
11630 }
11631 }
11632 }
11633
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080011634 public boolean profileControl(String process, boolean start,
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070011635 String path, ParcelFileDescriptor fd) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080011636
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070011637 try {
11638 synchronized (this) {
11639 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
11640 // its own permission.
11641 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
11642 != PackageManager.PERMISSION_GRANTED) {
11643 throw new SecurityException("Requires permission "
11644 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080011645 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070011646
11647 if (start && fd == null) {
11648 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080011649 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070011650
11651 ProcessRecord proc = null;
11652 try {
11653 int pid = Integer.parseInt(process);
11654 synchronized (mPidsSelfLocked) {
11655 proc = mPidsSelfLocked.get(pid);
11656 }
11657 } catch (NumberFormatException e) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080011658 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070011659
11660 if (proc == null) {
11661 HashMap<String, SparseArray<ProcessRecord>> all
11662 = mProcessNames.getMap();
11663 SparseArray<ProcessRecord> procs = all.get(process);
11664 if (procs != null && procs.size() > 0) {
11665 proc = procs.valueAt(0);
11666 }
11667 }
11668
11669 if (proc == null || proc.thread == null) {
11670 throw new IllegalArgumentException("Unknown process: " + process);
11671 }
11672
11673 boolean isSecure = "1".equals(SystemProperties.get(SYSTEM_SECURE, "0"));
11674 if (isSecure) {
11675 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
11676 throw new SecurityException("Process not debuggable: " + proc);
11677 }
11678 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080011679
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070011680 proc.thread.profilerControl(start, path, fd);
11681 fd = null;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080011682 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070011683 }
11684 } catch (RemoteException e) {
11685 throw new IllegalStateException("Process disappeared");
11686 } finally {
11687 if (fd != null) {
11688 try {
11689 fd.close();
11690 } catch (IOException e) {
11691 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080011692 }
11693 }
11694 }
11695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011696 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
11697 public void monitor() {
11698 synchronized (this) { }
11699 }
11700}