blob: 4ea2f041c74d7ea893356e579eb227b015122f4f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Dianne Hackborn860755f2010-06-03 18:47:52 -070019import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070021import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070022import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import com.android.server.IntentResolver;
24import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.SystemServer;
26import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070027import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080028import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029
Dianne Hackborndd71fc82009-12-16 19:24:32 -080030import dalvik.system.Zygote;
31
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.app.Activity;
33import android.app.ActivityManager;
34import android.app.ActivityManagerNative;
35import android.app.ActivityThread;
36import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070037import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020038import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070040import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.IApplicationThread;
42import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070043import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070044import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.app.IServiceConnection;
46import android.app.IThumbnailReceiver;
47import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070048import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070049import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070051import android.app.Service;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080052import android.app.WallpaperManager;
Christopher Tate45281862010-03-05 15:46:30 -080053import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020054import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080055import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070056import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.content.ComponentName;
58import android.content.ContentResolver;
59import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020060import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.Intent;
62import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070063import android.content.IIntentReceiver;
64import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070065import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.content.pm.ActivityInfo;
67import android.content.pm.ApplicationInfo;
68import android.content.pm.ConfigurationInfo;
69import android.content.pm.IPackageDataObserver;
70import android.content.pm.IPackageManager;
71import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080072import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070074import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.content.pm.ProviderInfo;
76import android.content.pm.ResolveInfo;
77import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070078import android.content.pm.UserInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070079import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040080import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.content.res.Configuration;
82import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070083import android.net.Proxy;
84import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.net.Uri;
86import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080087import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080088import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070089import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080090import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080092import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.os.FileUtils;
94import android.os.Handler;
95import android.os.IBinder;
96import android.os.IPermissionController;
97import android.os.Looper;
98import android.os.Message;
99import android.os.Parcel;
100import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700102import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.os.RemoteException;
104import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700105import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.SystemClock;
107import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700108import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700111import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800112import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800113import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.util.PrintWriterPrinter;
115import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700116import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700117import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.view.Gravity;
119import android.view.LayoutInflater;
120import android.view.View;
121import android.view.WindowManager;
122import android.view.WindowManagerPolicy;
123
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700124import java.io.BufferedInputStream;
125import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700126import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700127import java.io.DataInputStream;
128import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import java.io.File;
130import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700131import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700133import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200134import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800135import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700137import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import java.lang.IllegalStateException;
139import java.lang.ref.WeakReference;
140import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700141import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700142import java.util.Collections;
143import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.util.HashMap;
145import java.util.HashSet;
146import java.util.Iterator;
147import java.util.List;
148import java.util.Locale;
149import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700150import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700151import java.util.concurrent.atomic.AtomicBoolean;
152import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700154public final class ActivityManagerService extends ActivityManagerNative
155 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700156 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700158 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400160 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 static final boolean DEBUG_SWITCH = localLOGV || false;
162 static final boolean DEBUG_TASKS = localLOGV || false;
163 static final boolean DEBUG_PAUSE = localLOGV || false;
164 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
165 static final boolean DEBUG_TRANSITION = localLOGV || false;
166 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800167 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700168 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700170 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 static final boolean DEBUG_VISBILITY = localLOGV || false;
172 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700173 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800174 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700176 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700177 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700178 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700179 static final boolean DEBUG_POWER = localLOGV || false;
180 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700181 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 static final boolean VALIDATE_TOKENS = false;
183 static final boolean SHOW_ACTIVITY_START_TIME = true;
184
185 // Control over CPU and battery monitoring.
186 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
187 static final boolean MONITOR_CPU_USAGE = true;
188 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
189 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
190 static final boolean MONITOR_THREAD_CPU_USAGE = false;
191
Dianne Hackborn1655be42009-05-08 14:29:01 -0700192 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700193 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700194
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800195 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 // Maximum number of recent tasks that we can remember.
198 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700199
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700200 // Amount of time after a call to stopAppSwitches() during which we will
201 // prevent further untrusted switches from happening.
202 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
204 // How long we wait for a launched process to attach to the activity manager
205 // before we decide it's never going to come up for real.
206 static final int PROC_START_TIMEOUT = 10*1000;
207
Jeff Brown3f9dd282011-07-08 20:02:19 -0700208 // How long we wait for a launched process to attach to the activity manager
209 // before we decide it's never going to come up for real, when the process was
210 // started with a wrapper for instrumentation (such as Valgrind) because it
211 // could take much longer than usual.
212 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 // How long to wait after going idle before forcing apps to GC.
215 static final int GC_TIMEOUT = 5*1000;
216
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700217 // The minimum amount of time between successive GC requests for a process.
218 static final int GC_MIN_INTERVAL = 60*1000;
219
Dianne Hackborn287952c2010-09-22 22:34:31 -0700220 // The rate at which we check for apps using excessive power -- 15 mins.
221 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
222
223 // The minimum sample duration we will allow before deciding we have
224 // enough data on wake locks to start killing things.
225 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
226
227 // The minimum sample duration we will allow before deciding we have
228 // enough data on CPU usage to start killing things.
229 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800232 static final int BROADCAST_FG_TIMEOUT = 10*1000;
233 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234
235 // How long we wait for a service to finish executing.
236 static final int SERVICE_TIMEOUT = 20*1000;
237
238 // How long a service needs to be running until restarting its process
239 // is no longer considered to be a relaunch of the service.
240 static final int SERVICE_RESTART_DURATION = 5*1000;
241
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700242 // How long a service needs to be running until it will start back at
243 // SERVICE_RESTART_DURATION after being killed.
244 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
245
246 // Multiplying factor to increase restart duration time by, for each time
247 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
248 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
249
250 // The minimum amount of time between restarting services that we allow.
251 // That is, when multiple services are restarting, we won't allow each
252 // to restart less than this amount of time from the last one.
253 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 // Maximum amount of time for there to be no activity on a service before
256 // we consider it non-essential and allow its process to go on the
257 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700258 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259
260 // How long we wait until we timeout on key dispatching.
261 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 // How long we wait until we timeout on key dispatching during instrumentation.
264 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
265
Dan Egnor42471dd2010-01-07 17:25:22 -0800266 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267
268 static final String[] EMPTY_STRING_ARRAY = new String[0];
269
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700270 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700271
272 private final boolean mHeadless;
273
Joe Onorato54a4a412011-11-02 20:50:08 -0700274 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
275 // default actuion automatically. Important for devices without direct input
276 // devices.
277 private boolean mShowDialogs = true;
278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700280 * Description of a request to start a new activity, which has been held
281 * due to app switches being disabled.
282 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700283 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700284 ActivityRecord r;
285 ActivityRecord sourceRecord;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700286 Uri[] grantedUriPermissions;
287 int grantedMode;
288 boolean onlyIfNeeded;
289 }
290
291 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
292 = new ArrayList<PendingActivityLaunch>();
293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800295 BroadcastQueue mFgBroadcastQueue;
296 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800297 // Convenient for easy iteration over the queues. Foreground is first
298 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800299 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800300
301 BroadcastQueue broadcastQueueForIntent(Intent intent) {
302 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
303 if (DEBUG_BACKGROUND_BROADCAST) {
304 Slog.i(TAG, "Broadcast intent " + intent + " on "
305 + (isFg ? "foreground" : "background")
306 + " queue");
307 }
308 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
309 }
310
311 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
312 for (BroadcastQueue queue : mBroadcastQueues) {
313 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
314 if (r != null) {
315 return r;
316 }
317 }
318 return null;
319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320
321 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 * Activity we have told the window manager to have key focus.
323 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700324 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700325 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 * List of intents that were used to start the most recent tasks.
327 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700328 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329
330 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700331 * Process management.
332 */
333 final ProcessList mProcessList = new ProcessList();
334
335 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 * All of the applications we currently have running organized by name.
337 * The keys are strings of the application package name (as
338 * returned by the package manager), and the keys are ApplicationRecord
339 * objects.
340 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700341 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342
343 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800344 * The currently running isolated processes.
345 */
346 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
347
348 /**
349 * Counter for assigning isolated process uids, to avoid frequently reusing the
350 * same ones.
351 */
352 int mNextIsolatedProcessUid = 0;
353
354 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700355 * The currently running heavy-weight process, if any.
356 */
357 ProcessRecord mHeavyWeightProcess = null;
358
359 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 * The last time that various processes have crashed.
361 */
362 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
363
364 /**
365 * Set of applications that we consider to be bad, and will reject
366 * incoming broadcasts from (which the user has no control over).
367 * Processes are added to this set when they have crashed twice within
368 * a minimum amount of time; they are removed from it when they are
369 * later restarted (hopefully due to some user action). The value is the
370 * time it was added to the list.
371 */
372 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
373
374 /**
375 * All of the processes we currently have running organized by pid.
376 * The keys are the pid running the application.
377 *
378 * <p>NOTE: This object is protected by its own lock, NOT the global
379 * activity manager lock!
380 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700381 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382
383 /**
384 * All of the processes that have been forced to be foreground. The key
385 * is the pid of the caller who requested it (we hold a death
386 * link on it).
387 */
388 abstract class ForegroundToken implements IBinder.DeathRecipient {
389 int pid;
390 IBinder token;
391 }
392 final SparseArray<ForegroundToken> mForegroundProcesses
393 = new SparseArray<ForegroundToken>();
394
395 /**
396 * List of records for processes that someone had tried to start before the
397 * system was ready. We don't start them at that point, but ensure they
398 * are started by the time booting is complete.
399 */
400 final ArrayList<ProcessRecord> mProcessesOnHold
401 = new ArrayList<ProcessRecord>();
402
403 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 * List of persistent applications that are in the process
405 * of being started.
406 */
407 final ArrayList<ProcessRecord> mPersistentStartingProcesses
408 = new ArrayList<ProcessRecord>();
409
410 /**
411 * Processes that are being forcibly torn down.
412 */
413 final ArrayList<ProcessRecord> mRemovedProcesses
414 = new ArrayList<ProcessRecord>();
415
416 /**
417 * List of running applications, sorted by recent usage.
418 * The first entry in the list is the least recently used.
419 * It contains ApplicationRecord objects. This list does NOT include
420 * any persistent application records (since we never want to exit them).
421 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800422 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 = new ArrayList<ProcessRecord>();
424
425 /**
426 * List of processes that should gc as soon as things are idle.
427 */
428 final ArrayList<ProcessRecord> mProcessesToGc
429 = new ArrayList<ProcessRecord>();
430
431 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800432 * This is the process holding what we currently consider to be
433 * the "home" activity.
434 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700435 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800436
437 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700438 * This is the process holding the activity the user last visited that
439 * is in a different process from the one they are currently in.
440 */
441 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800442
443 /**
444 * The time at which the previous process was last visible.
445 */
446 long mPreviousProcessVisibleTime;
447
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700448 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400449 * Packages that the user has asked to have run in screen size
450 * compatibility mode instead of filling the screen.
451 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700452 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400453
454 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 * Set of PendingResultRecord objects that are currently active.
456 */
457 final HashSet mPendingResultRecords = new HashSet();
458
459 /**
460 * Set of IntentSenderRecord objects that are currently active.
461 */
462 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
463 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
464
465 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800466 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700467 * already logged DropBox entries for. Guarded by itself. If
468 * something (rogue user app) forces this over
469 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
470 */
471 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
472 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
473
474 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700475 * Strict Mode background batched logging state.
476 *
477 * The string buffer is guarded by itself, and its lock is also
478 * used to determine if another batched write is already
479 * in-flight.
480 */
481 private final StringBuilder mStrictModeBuffer = new StringBuilder();
482
483 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 * Keeps track of all IIntentReceivers that have been registered for
485 * broadcasts. Hash keys are the receiver IBinder, hash value is
486 * a ReceiverList.
487 */
488 final HashMap mRegisteredReceivers = new HashMap();
489
490 /**
491 * Resolver for broadcast intents to registered receivers.
492 * Holds BroadcastFilter (subclass of IntentFilter).
493 */
494 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
495 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
496 @Override
497 protected boolean allowFilterResult(
498 BroadcastFilter filter, List<BroadcastFilter> dest) {
499 IBinder target = filter.receiverList.receiver.asBinder();
500 for (int i=dest.size()-1; i>=0; i--) {
501 if (dest.get(i).receiverList.receiver.asBinder() == target) {
502 return false;
503 }
504 }
505 return true;
506 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700507
508 @Override
509 protected String packageForFilter(BroadcastFilter filter) {
510 return filter.packageName;
511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 };
513
514 /**
515 * State of all active sticky broadcasts. Keys are the action of the
516 * sticky Intent, values are an ArrayList of all broadcasted intents with
517 * that action (which should usually be one).
518 */
519 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
520 new HashMap<String, ArrayList<Intent>>();
521
Amith Yamasani742a6712011-05-04 14:49:28 -0700522 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523
524 /**
525 * All currently bound service connections. Keys are the IBinder of
526 * the client's IServiceConnection.
527 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700528 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
529 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530
531 /**
532 * List of services that we have been asked to start,
533 * but haven't yet been able to. It is used to hold start requests
534 * while waiting for their corresponding application thread to get
535 * going.
536 */
537 final ArrayList<ServiceRecord> mPendingServices
538 = new ArrayList<ServiceRecord>();
539
540 /**
541 * List of services that are scheduled to restart following a crash.
542 */
543 final ArrayList<ServiceRecord> mRestartingServices
544 = new ArrayList<ServiceRecord>();
545
546 /**
547 * List of services that are in the process of being stopped.
548 */
549 final ArrayList<ServiceRecord> mStoppingServices
550 = new ArrayList<ServiceRecord>();
551
552 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700553 * Backup/restore process management
554 */
555 String mBackupAppName = null;
556 BackupRecord mBackupTarget = null;
557
558 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 * List of PendingThumbnailsRecord objects of clients who are still
560 * waiting to receive all of the thumbnails for a task.
561 */
562 final ArrayList mPendingThumbnails = new ArrayList();
563
564 /**
565 * List of HistoryRecord objects that have been finished and must
566 * still report back to a pending thumbnail receiver.
567 */
568 final ArrayList mCancelledThumbnails = new ArrayList();
569
Amith Yamasani742a6712011-05-04 14:49:28 -0700570 final ProviderMap mProviderMap = new ProviderMap();
571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 /**
573 * List of content providers who have clients waiting for them. The
574 * application is currently being launched and the provider will be
575 * removed from this list once it is published.
576 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700577 final ArrayList<ContentProviderRecord> mLaunchingProviders
578 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579
580 /**
581 * Global set of specific Uri permissions that have been granted.
582 */
583 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
584 = new SparseArray<HashMap<Uri, UriPermission>>();
585
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800586 CoreSettingsObserver mCoreSettingsObserver;
587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 /**
589 * Thread-local storage used to carry caller permissions over through
590 * indirect content-provider access.
591 * @see #ActivityManagerService.openContentUri()
592 */
593 private class Identity {
594 public int pid;
595 public int uid;
596
597 Identity(int _pid, int _uid) {
598 pid = _pid;
599 uid = _uid;
600 }
601 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
604
605 /**
606 * All information we have collected about the runtime performance of
607 * any user id that can impact battery performance.
608 */
609 final BatteryStatsService mBatteryStatsService;
610
611 /**
612 * information about component usage
613 */
614 final UsageStatsService mUsageStatsService;
615
616 /**
617 * Current configuration information. HistoryRecord objects are given
618 * a reference to this object to indicate which configuration they are
619 * currently running in, so this object must be kept immutable.
620 */
621 Configuration mConfiguration = new Configuration();
622
623 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800624 * Current sequencing integer of the configuration, for skipping old
625 * configurations.
626 */
627 int mConfigurationSeq = 0;
628
629 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700630 * Hardware-reported OpenGLES version.
631 */
632 final int GL_ES_VERSION;
633
634 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 * List of initialization arguments to pass to all processes when binding applications to them.
636 * For example, references to the commonly used services.
637 */
638 HashMap<String, IBinder> mAppBindArgs;
639
640 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700641 * Temporary to avoid allocations. Protected by main lock.
642 */
643 final StringBuilder mStringBuilder = new StringBuilder(256);
644
645 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 * Used to control how we initialize the service.
647 */
648 boolean mStartRunning = false;
649 ComponentName mTopComponent;
650 String mTopAction;
651 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700652 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 boolean mSystemReady = false;
654 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700655 boolean mWaitingUpdate = false;
656 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700657 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700658 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659
660 Context mContext;
661
662 int mFactoryTest;
663
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700664 boolean mCheckedForSetup;
665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700667 * The time at which we will allow normal application switches again,
668 * after a call to {@link #stopAppSwitches()}.
669 */
670 long mAppSwitchesAllowedTime;
671
672 /**
673 * This is set to true after the first switch after mAppSwitchesAllowedTime
674 * is set; any switches after that will clear the time.
675 */
676 boolean mDidAppSwitch;
677
678 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700679 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700680 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700681 long mLastPowerCheckRealtime;
682
683 /**
684 * Last time (in uptime) at which we checked for power usage.
685 */
686 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700687
688 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 * Set while we are wanting to sleep, to prevent any
690 * activities from being started/resumed.
691 */
692 boolean mSleeping = false;
693
694 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700695 * Set if we are shutting down the system, similar to sleeping.
696 */
697 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698
699 /**
700 * Task identifier that activities are currently being started
701 * in. Incremented each time a new task is created.
702 * todo: Replace this with a TokenSpace class that generates non-repeating
703 * integers that won't wrap.
704 */
705 int mCurTask = 1;
706
707 /**
708 * Current sequence id for oom_adj computation traversal.
709 */
710 int mAdjSeq = 0;
711
712 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700713 * Current sequence id for process LRU updating.
714 */
715 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716
717 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700718 * Keep track of the number of service processes we last found, to
719 * determine on the next iteration which should be B services.
720 */
721 int mNumServiceProcs = 0;
722 int mNewNumServiceProcs = 0;
723
724 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 * System monitoring: number of processes that died since the last
726 * N procs were started.
727 */
728 int[] mProcDeaths = new int[20];
729
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700730 /**
731 * This is set if we had to do a delayed dexopt of an app before launching
732 * it, to increasing the ANR timeouts in that case.
733 */
734 boolean mDidDexOpt;
735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 String mDebugApp = null;
737 boolean mWaitForDebugger = false;
738 boolean mDebugTransient = false;
739 String mOrigDebugApp = null;
740 boolean mOrigWaitForDebugger = false;
741 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700742 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700743 String mProfileApp = null;
744 ProcessRecord mProfileProc = null;
745 String mProfileFile;
746 ParcelFileDescriptor mProfileFd;
747 int mProfileType = 0;
748 boolean mAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749
Jeff Sharkeya4620792011-05-20 15:29:23 -0700750 final RemoteCallbackList<IProcessObserver> mProcessObservers
751 = new RemoteCallbackList<IProcessObserver>();
752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 /**
754 * Callback of last caller to {@link #requestPss}.
755 */
756 Runnable mRequestPssCallback;
757
758 /**
759 * Remaining processes for which we are waiting results from the last
760 * call to {@link #requestPss}.
761 */
762 final ArrayList<ProcessRecord> mRequestPssList
763 = new ArrayList<ProcessRecord>();
764
765 /**
766 * Runtime statistics collection thread. This object's lock is used to
767 * protect all related state.
768 */
769 final Thread mProcessStatsThread;
770
771 /**
772 * Used to collect process stats when showing not responding dialog.
773 * Protected by mProcessStatsThread.
774 */
775 final ProcessStats mProcessStats = new ProcessStats(
776 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700777 final AtomicLong mLastCpuTime = new AtomicLong(0);
778 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 long mLastWriteTime = 0;
781
782 /**
783 * Set to true after the system has finished booting.
784 */
785 boolean mBooted = false;
786
Dianne Hackborn7d608422011-08-07 16:24:18 -0700787 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700788 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789
790 WindowManagerService mWindowManager;
791
792 static ActivityManagerService mSelf;
793 static ActivityThread mSystemThread;
794
795 private final class AppDeathRecipient implements IBinder.DeathRecipient {
796 final ProcessRecord mApp;
797 final int mPid;
798 final IApplicationThread mAppThread;
799
800 AppDeathRecipient(ProcessRecord app, int pid,
801 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800802 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 TAG, "New death recipient " + this
804 + " for thread " + thread.asBinder());
805 mApp = app;
806 mPid = pid;
807 mAppThread = thread;
808 }
809
810 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800811 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 TAG, "Death received in " + this
813 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 synchronized(ActivityManagerService.this) {
815 appDiedLocked(mApp, mPid, mAppThread);
816 }
817 }
818 }
819
820 static final int SHOW_ERROR_MSG = 1;
821 static final int SHOW_NOT_RESPONDING_MSG = 2;
822 static final int SHOW_FACTORY_ERROR_MSG = 3;
823 static final int UPDATE_CONFIGURATION_MSG = 4;
824 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
825 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 static final int SERVICE_TIMEOUT_MSG = 12;
827 static final int UPDATE_TIME_ZONE = 13;
828 static final int SHOW_UID_ERROR_MSG = 14;
829 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700831 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700832 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800833 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700834 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
835 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700836 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700837 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700838 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700839 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700840 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700841 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
842 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700843 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800845 static final int FIRST_ACTIVITY_STACK_MSG = 100;
846 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
847 static final int FIRST_COMPAT_MODE_MSG = 300;
848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700850 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700851 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852
853 final Handler mHandler = new Handler() {
854 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800855 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 //}
857
858 public void handleMessage(Message msg) {
859 switch (msg.what) {
860 case SHOW_ERROR_MSG: {
861 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 synchronized (ActivityManagerService.this) {
863 ProcessRecord proc = (ProcessRecord)data.get("app");
864 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800865 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 return;
867 }
868 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700869 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800870 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 d.show();
872 proc.crashDialog = d;
873 } else {
874 // The device is asleep, so just pretend that the user
875 // saw a crash dialog and hit "force quit".
876 res.set(0);
877 }
878 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700879
880 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 } break;
882 case SHOW_NOT_RESPONDING_MSG: {
883 synchronized (ActivityManagerService.this) {
884 HashMap data = (HashMap) msg.obj;
885 ProcessRecord proc = (ProcessRecord)data.get("app");
886 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800887 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 return;
889 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800890
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700891 Intent intent = new Intent("android.intent.action.ANR");
892 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800893 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
894 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700895 }
896 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800897 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700898 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700901 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 d.show();
903 proc.anrDialog = d;
904 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700905
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700906 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700908 case SHOW_STRICT_MODE_VIOLATION_MSG: {
909 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
910 synchronized (ActivityManagerService.this) {
911 ProcessRecord proc = (ProcessRecord) data.get("app");
912 if (proc == null) {
913 Slog.e(TAG, "App not found when showing strict mode dialog.");
914 break;
915 }
916 if (proc.crashDialog != null) {
917 Slog.e(TAG, "App already has strict mode dialog: " + proc);
918 return;
919 }
920 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700921 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700922 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
923 d.show();
924 proc.crashDialog = d;
925 } else {
926 // The device is asleep, so just pretend that the user
927 // saw a crash dialog and hit "force quit".
928 res.set(0);
929 }
930 }
931 ensureBootCompleted();
932 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 case SHOW_FACTORY_ERROR_MSG: {
934 Dialog d = new FactoryErrorDialog(
935 mContext, msg.getData().getCharSequence("msg"));
936 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700937 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 } break;
939 case UPDATE_CONFIGURATION_MSG: {
940 final ContentResolver resolver = mContext.getContentResolver();
941 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
942 } break;
943 case GC_BACKGROUND_PROCESSES_MSG: {
944 synchronized (ActivityManagerService.this) {
945 performAppGcsIfAppropriateLocked();
946 }
947 } break;
948 case WAIT_FOR_DEBUGGER_MSG: {
949 synchronized (ActivityManagerService.this) {
950 ProcessRecord app = (ProcessRecord)msg.obj;
951 if (msg.arg1 != 0) {
952 if (!app.waitedForDebugger) {
953 Dialog d = new AppWaitingForDebuggerDialog(
954 ActivityManagerService.this,
955 mContext, app);
956 app.waitDialog = d;
957 app.waitedForDebugger = true;
958 d.show();
959 }
960 } else {
961 if (app.waitDialog != null) {
962 app.waitDialog.dismiss();
963 app.waitDialog = null;
964 }
965 }
966 }
967 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700969 if (mDidDexOpt) {
970 mDidDexOpt = false;
971 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
972 nmsg.obj = msg.obj;
973 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
974 return;
975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 serviceTimeout((ProcessRecord)msg.obj);
977 } break;
978 case UPDATE_TIME_ZONE: {
979 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800980 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
981 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 if (r.thread != null) {
983 try {
984 r.thread.updateTimeZone();
985 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800986 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 }
988 }
989 }
990 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700991 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700992 case CLEAR_DNS_CACHE: {
993 synchronized (ActivityManagerService.this) {
994 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
995 ProcessRecord r = mLruProcesses.get(i);
996 if (r.thread != null) {
997 try {
998 r.thread.clearDnsCache();
999 } catch (RemoteException ex) {
1000 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1001 }
1002 }
1003 }
1004 }
1005 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001006 case UPDATE_HTTP_PROXY: {
1007 ProxyProperties proxy = (ProxyProperties)msg.obj;
1008 String host = "";
1009 String port = "";
1010 String exclList = "";
1011 if (proxy != null) {
1012 host = proxy.getHost();
1013 port = Integer.toString(proxy.getPort());
1014 exclList = proxy.getExclusionList();
1015 }
1016 synchronized (ActivityManagerService.this) {
1017 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1018 ProcessRecord r = mLruProcesses.get(i);
1019 if (r.thread != null) {
1020 try {
1021 r.thread.setHttpProxy(host, port, exclList);
1022 } catch (RemoteException ex) {
1023 Slog.w(TAG, "Failed to update http proxy for: " +
1024 r.info.processName);
1025 }
1026 }
1027 }
1028 }
1029 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001031 String title = "System UIDs Inconsistent";
1032 String text = "UIDs on the system are inconsistent, you need to wipe your"
1033 + " data partition or your device will be unstable.";
1034 Log.e(TAG, title + ": " + text);
1035 if (mShowDialogs) {
1036 // XXX This is a temporary dialog, no need to localize.
1037 AlertDialog d = new BaseErrorDialog(mContext);
1038 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1039 d.setCancelable(false);
1040 d.setTitle(title);
1041 d.setMessage(text);
1042 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1043 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1044 mUidAlert = d;
1045 d.show();
1046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 } break;
1048 case IM_FEELING_LUCKY_MSG: {
1049 if (mUidAlert != null) {
1050 mUidAlert.dismiss();
1051 mUidAlert = null;
1052 }
1053 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001055 if (mDidDexOpt) {
1056 mDidDexOpt = false;
1057 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1058 nmsg.obj = msg.obj;
1059 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1060 return;
1061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 ProcessRecord app = (ProcessRecord)msg.obj;
1063 synchronized (ActivityManagerService.this) {
1064 processStartTimedOutLocked(app);
1065 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001066 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001067 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1068 synchronized (ActivityManagerService.this) {
1069 doPendingActivityLaunchesLocked(true);
1070 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001071 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001072 case KILL_APPLICATION_MSG: {
1073 synchronized (ActivityManagerService.this) {
1074 int uid = msg.arg1;
1075 boolean restart = (msg.arg2 == 1);
1076 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001077 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001078 }
1079 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001080 case FINALIZE_PENDING_INTENT_MSG: {
1081 ((PendingIntentRecord)msg.obj).completeFinalize();
1082 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001083 case POST_HEAVY_NOTIFICATION_MSG: {
1084 INotificationManager inm = NotificationManager.getService();
1085 if (inm == null) {
1086 return;
1087 }
1088
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001089 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001090 ProcessRecord process = root.app;
1091 if (process == null) {
1092 return;
1093 }
1094
1095 try {
1096 Context context = mContext.createPackageContext(process.info.packageName, 0);
1097 String text = mContext.getString(R.string.heavy_weight_notification,
1098 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1099 Notification notification = new Notification();
1100 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1101 notification.when = 0;
1102 notification.flags = Notification.FLAG_ONGOING_EVENT;
1103 notification.tickerText = text;
1104 notification.defaults = 0; // please be quiet
1105 notification.sound = null;
1106 notification.vibrate = null;
1107 notification.setLatestEventInfo(context, text,
1108 mContext.getText(R.string.heavy_weight_notification_detail),
1109 PendingIntent.getActivity(mContext, 0, root.intent,
1110 PendingIntent.FLAG_CANCEL_CURRENT));
1111
1112 try {
1113 int[] outId = new int[1];
1114 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1115 notification, outId);
1116 } catch (RuntimeException e) {
1117 Slog.w(ActivityManagerService.TAG,
1118 "Error showing notification for heavy-weight app", e);
1119 } catch (RemoteException e) {
1120 }
1121 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001122 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001123 }
1124 } break;
1125 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1126 INotificationManager inm = NotificationManager.getService();
1127 if (inm == null) {
1128 return;
1129 }
1130 try {
1131 inm.cancelNotification("android",
1132 R.string.heavy_weight_notification);
1133 } catch (RuntimeException e) {
1134 Slog.w(ActivityManagerService.TAG,
1135 "Error canceling notification for service", e);
1136 } catch (RemoteException e) {
1137 }
1138 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001139 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1140 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001141 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001142 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001143 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1144 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001145 }
1146 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001147 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1148 synchronized (ActivityManagerService.this) {
1149 ActivityRecord ar = (ActivityRecord)msg.obj;
1150 if (mCompatModeDialog != null) {
1151 if (mCompatModeDialog.mAppInfo.packageName.equals(
1152 ar.info.applicationInfo.packageName)) {
1153 return;
1154 }
1155 mCompatModeDialog.dismiss();
1156 mCompatModeDialog = null;
1157 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001158 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001159 if (mCompatModePackages.getPackageAskCompatModeLocked(
1160 ar.packageName)) {
1161 int mode = mCompatModePackages.computeCompatModeLocked(
1162 ar.info.applicationInfo);
1163 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1164 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1165 mCompatModeDialog = new CompatModeDialog(
1166 ActivityManagerService.this, mContext,
1167 ar.info.applicationInfo);
1168 mCompatModeDialog.show();
1169 }
1170 }
1171 }
1172 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001173 break;
1174 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001175 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001176 final int pid = msg.arg1;
1177 final int uid = msg.arg2;
1178 final boolean foregroundActivities = (Boolean) msg.obj;
1179 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001180 break;
1181 }
1182 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001183 final int pid = msg.arg1;
1184 final int uid = msg.arg2;
1185 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001186 break;
1187 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001188 case REPORT_MEM_USAGE: {
1189 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1190 if (!isDebuggable) {
1191 return;
1192 }
1193 synchronized (ActivityManagerService.this) {
1194 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001195 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1196 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001197 // avoid spamming.
1198 return;
1199 }
1200 mLastMemUsageReportTime = now;
1201 }
1202 Thread thread = new Thread() {
1203 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001204 StringBuilder dropBuilder = new StringBuilder(1024);
1205 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001206 StringWriter oomSw = new StringWriter();
1207 PrintWriter oomPw = new PrintWriter(oomSw);
1208 StringWriter catSw = new StringWriter();
1209 PrintWriter catPw = new PrintWriter(catSw);
1210 String[] emptyArgs = new String[] { };
1211 StringBuilder tag = new StringBuilder(128);
1212 StringBuilder stack = new StringBuilder(128);
1213 tag.append("Low on memory -- ");
1214 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1215 tag, stack);
1216 dropBuilder.append(stack);
1217 dropBuilder.append('\n');
1218 dropBuilder.append('\n');
1219 String oomString = oomSw.toString();
1220 dropBuilder.append(oomString);
1221 dropBuilder.append('\n');
1222 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001223 try {
1224 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1225 "procrank", });
1226 final InputStreamReader converter = new InputStreamReader(
1227 proc.getInputStream());
1228 BufferedReader in = new BufferedReader(converter);
1229 String line;
1230 while (true) {
1231 line = in.readLine();
1232 if (line == null) {
1233 break;
1234 }
1235 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001236 logBuilder.append(line);
1237 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001238 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001239 dropBuilder.append(line);
1240 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001241 }
1242 converter.close();
1243 } catch (IOException e) {
1244 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001245 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001246 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001247 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001248 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001249 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001250 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001251 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001252 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001253 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001254 addErrorToDropBox("lowmem", null, "system_server", null,
1255 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001256 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001257 synchronized (ActivityManagerService.this) {
1258 long now = SystemClock.uptimeMillis();
1259 if (mLastMemUsageReportTime < now) {
1260 mLastMemUsageReportTime = now;
1261 }
1262 }
1263 }
1264 };
1265 thread.start();
1266 break;
1267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 }
1269 }
1270 };
1271
1272 public static void setSystemProcess() {
1273 try {
1274 ActivityManagerService m = mSelf;
1275
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001276 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001278 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001279 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 if (MONITOR_CPU_USAGE) {
1281 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 ServiceManager.addService("permission", new PermissionController(m));
1284
1285 ApplicationInfo info =
1286 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001287 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001288 mSystemThread.installSystemApplicationInfo(info);
1289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 synchronized (mSelf) {
1291 ProcessRecord app = mSelf.newProcessRecordLocked(
1292 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001293 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001295 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001296 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001297 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 synchronized (mSelf.mPidsSelfLocked) {
1299 mSelf.mPidsSelfLocked.put(app.pid, app);
1300 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001301 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 }
1303 } catch (PackageManager.NameNotFoundException e) {
1304 throw new RuntimeException(
1305 "Unable to find android system package", e);
1306 }
1307 }
1308
1309 public void setWindowManager(WindowManagerService wm) {
1310 mWindowManager = wm;
1311 }
1312
1313 public static final Context main(int factoryTest) {
1314 AThread thr = new AThread();
1315 thr.start();
1316
1317 synchronized (thr) {
1318 while (thr.mService == null) {
1319 try {
1320 thr.wait();
1321 } catch (InterruptedException e) {
1322 }
1323 }
1324 }
1325
1326 ActivityManagerService m = thr.mService;
1327 mSelf = m;
1328 ActivityThread at = ActivityThread.systemMain();
1329 mSystemThread = at;
1330 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001331 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 m.mContext = context;
1333 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001334 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335
1336 m.mBatteryStatsService.publish(context);
1337 m.mUsageStatsService.publish(context);
1338
1339 synchronized (thr) {
1340 thr.mReady = true;
1341 thr.notifyAll();
1342 }
1343
1344 m.startRunning(null, null, null, null);
1345
1346 return context;
1347 }
1348
1349 public static ActivityManagerService self() {
1350 return mSelf;
1351 }
1352
1353 static class AThread extends Thread {
1354 ActivityManagerService mService;
1355 boolean mReady = false;
1356
1357 public AThread() {
1358 super("ActivityManager");
1359 }
1360
1361 public void run() {
1362 Looper.prepare();
1363
1364 android.os.Process.setThreadPriority(
1365 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001366 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367
1368 ActivityManagerService m = new ActivityManagerService();
1369
1370 synchronized (this) {
1371 mService = m;
1372 notifyAll();
1373 }
1374
1375 synchronized (this) {
1376 while (!mReady) {
1377 try {
1378 wait();
1379 } catch (InterruptedException e) {
1380 }
1381 }
1382 }
1383
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001384 // For debug builds, log event loop stalls to dropbox for analysis.
1385 if (StrictMode.conditionallyEnableDebugLogging()) {
1386 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1387 }
1388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 Looper.loop();
1390 }
1391 }
1392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 static class MemBinder extends Binder {
1394 ActivityManagerService mActivityManagerService;
1395 MemBinder(ActivityManagerService activityManagerService) {
1396 mActivityManagerService = activityManagerService;
1397 }
1398
1399 @Override
1400 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001401 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1402 != PackageManager.PERMISSION_GRANTED) {
1403 pw.println("Permission Denial: can't dump meminfo from from pid="
1404 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1405 + " without permission " + android.Manifest.permission.DUMP);
1406 return;
1407 }
1408
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001409 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001410 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 }
1412 }
1413
Chet Haase9c1e23b2011-03-24 10:51:31 -07001414 static class GraphicsBinder extends Binder {
1415 ActivityManagerService mActivityManagerService;
1416 GraphicsBinder(ActivityManagerService activityManagerService) {
1417 mActivityManagerService = activityManagerService;
1418 }
1419
1420 @Override
1421 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001422 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1423 != PackageManager.PERMISSION_GRANTED) {
1424 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1425 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1426 + " without permission " + android.Manifest.permission.DUMP);
1427 return;
1428 }
1429
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001430 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001431 }
1432 }
1433
Jeff Brown6754ba22011-12-14 20:20:01 -08001434 static class DbBinder extends Binder {
1435 ActivityManagerService mActivityManagerService;
1436 DbBinder(ActivityManagerService activityManagerService) {
1437 mActivityManagerService = activityManagerService;
1438 }
1439
1440 @Override
1441 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1442 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1443 != PackageManager.PERMISSION_GRANTED) {
1444 pw.println("Permission Denial: can't dump dbinfo from from pid="
1445 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1446 + " without permission " + android.Manifest.permission.DUMP);
1447 return;
1448 }
1449
1450 mActivityManagerService.dumpDbInfo(fd, pw, args);
1451 }
1452 }
1453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 static class CpuBinder extends Binder {
1455 ActivityManagerService mActivityManagerService;
1456 CpuBinder(ActivityManagerService activityManagerService) {
1457 mActivityManagerService = activityManagerService;
1458 }
1459
1460 @Override
1461 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001462 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1463 != PackageManager.PERMISSION_GRANTED) {
1464 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1465 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1466 + " without permission " + android.Manifest.permission.DUMP);
1467 return;
1468 }
1469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001471 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1472 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1473 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 }
1475 }
1476 }
1477
1478 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001479 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001480
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001481 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1482 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1483 mBroadcastQueues[0] = mFgBroadcastQueue;
1484 mBroadcastQueues[1] = mBgBroadcastQueue;
1485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 File dataDir = Environment.getDataDirectory();
1487 File systemDir = new File(dataDir, "system");
1488 systemDir.mkdirs();
1489 mBatteryStatsService = new BatteryStatsService(new File(
1490 systemDir, "batterystats.bin").toString());
1491 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001492 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001493 mOnBattery = DEBUG_POWER ? true
1494 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001495 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001497 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001498 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001499 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500
Jack Palevichb90d28c2009-07-22 15:35:24 -07001501 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1502 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1503
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001504 mConfiguration.setToDefaults();
1505 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001506 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 mProcessStats.init();
1508
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001509 mCompatModePackages = new CompatModePackages(this, systemDir);
1510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 // Add ourself to the Watchdog monitors.
1512 Watchdog.getInstance().addMonitor(this);
1513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 mProcessStatsThread = new Thread("ProcessStats") {
1515 public void run() {
1516 while (true) {
1517 try {
1518 try {
1519 synchronized(this) {
1520 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001521 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001523 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 // + ", write delay=" + nextWriteDelay);
1525 if (nextWriteDelay < nextCpuDelay) {
1526 nextCpuDelay = nextWriteDelay;
1527 }
1528 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001529 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 this.wait(nextCpuDelay);
1531 }
1532 }
1533 } catch (InterruptedException e) {
1534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 updateCpuStatsNow();
1536 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001537 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539 }
1540 }
1541 };
1542 mProcessStatsThread.start();
1543 }
1544
1545 @Override
1546 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1547 throws RemoteException {
1548 try {
1549 return super.onTransact(code, data, reply, flags);
1550 } catch (RuntimeException e) {
1551 // The activity manager only throws security exceptions, so let's
1552 // log all others.
1553 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001554 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 }
1556 throw e;
1557 }
1558 }
1559
1560 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001561 final long now = SystemClock.uptimeMillis();
1562 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1563 return;
1564 }
1565 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1566 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 mProcessStatsThread.notify();
1568 }
1569 }
1570 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 void updateCpuStatsNow() {
1573 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001574 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 final long now = SystemClock.uptimeMillis();
1576 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001579 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1580 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 haveNewCpuStats = true;
1582 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001583 //Slog.i(TAG, mProcessStats.printCurrentState());
1584 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 // + mProcessStats.getTotalCpuPercent() + "%");
1586
Joe Onorato8a9b2202010-02-26 18:56:32 -08001587 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 if ("true".equals(SystemProperties.get("events.cpu"))) {
1589 int user = mProcessStats.getLastUserTime();
1590 int system = mProcessStats.getLastSystemTime();
1591 int iowait = mProcessStats.getLastIoWaitTime();
1592 int irq = mProcessStats.getLastIrqTime();
1593 int softIrq = mProcessStats.getLastSoftIrqTime();
1594 int idle = mProcessStats.getLastIdleTime();
1595
1596 int total = user + system + iowait + irq + softIrq + idle;
1597 if (total == 0) total = 1;
1598
Doug Zongker2bec3d42009-12-04 12:52:44 -08001599 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 ((user+system+iowait+irq+softIrq) * 100) / total,
1601 (user * 100) / total,
1602 (system * 100) / total,
1603 (iowait * 100) / total,
1604 (irq * 100) / total,
1605 (softIrq * 100) / total);
1606 }
1607 }
1608
Amith Yamasanie43530a2009-08-21 13:11:37 -07001609 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001610 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001611 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 synchronized(mPidsSelfLocked) {
1613 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001614 if (mOnBattery) {
1615 int perc = bstats.startAddingCpuLocked();
1616 int totalUTime = 0;
1617 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001618 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001620 ProcessStats.Stats st = mProcessStats.getStats(i);
1621 if (!st.working) {
1622 continue;
1623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001625 int otherUTime = (st.rel_utime*perc)/100;
1626 int otherSTime = (st.rel_stime*perc)/100;
1627 totalUTime += otherUTime;
1628 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 if (pr != null) {
1630 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001631 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1632 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001633 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001634 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001635 } else {
1636 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001637 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001638 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001639 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1640 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001641 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001645 bstats.finishAddingCpuLocked(perc, totalUTime,
1646 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
1648 }
1649 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1652 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001653 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 }
1655 }
1656 }
1657 }
1658
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001659 @Override
1660 public void batteryNeedsCpuUpdate() {
1661 updateCpuStatsNow();
1662 }
1663
1664 @Override
1665 public void batteryPowerChanged(boolean onBattery) {
1666 // When plugging in, update the CPU stats first before changing
1667 // the plug state.
1668 updateCpuStatsNow();
1669 synchronized (this) {
1670 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001671 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001672 }
1673 }
1674 }
1675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 /**
1677 * Initialize the application bind args. These are passed to each
1678 * process when the bindApplication() IPC is sent to the process. They're
1679 * lazily setup to make sure the services are running when they're asked for.
1680 */
1681 private HashMap<String, IBinder> getCommonServicesLocked() {
1682 if (mAppBindArgs == null) {
1683 mAppBindArgs = new HashMap<String, IBinder>();
1684
1685 // Setup the application init args
1686 mAppBindArgs.put("package", ServiceManager.getService("package"));
1687 mAppBindArgs.put("window", ServiceManager.getService("window"));
1688 mAppBindArgs.put(Context.ALARM_SERVICE,
1689 ServiceManager.getService(Context.ALARM_SERVICE));
1690 }
1691 return mAppBindArgs;
1692 }
1693
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001694 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 if (mFocusedActivity != r) {
1696 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001697 if (r != null) {
1698 mWindowManager.setFocusedApp(r.appToken, true);
1699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 }
1701 }
1702
Dianne Hackborn906497c2010-05-10 15:57:38 -07001703 private final void updateLruProcessInternalLocked(ProcessRecord app,
1704 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001706 int lrui = mLruProcesses.indexOf(app);
1707 if (lrui >= 0) mLruProcesses.remove(lrui);
1708
1709 int i = mLruProcesses.size()-1;
1710 int skipTop = 0;
1711
Dianne Hackborn906497c2010-05-10 15:57:38 -07001712 app.lruSeq = mLruSeq;
1713
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001714 // compute the new weight for this process.
1715 if (updateActivityTime) {
1716 app.lastActivityTime = SystemClock.uptimeMillis();
1717 }
1718 if (app.activities.size() > 0) {
1719 // If this process has activities, we more strongly want to keep
1720 // it around.
1721 app.lruWeight = app.lastActivityTime;
1722 } else if (app.pubProviders.size() > 0) {
1723 // If this process contains content providers, we want to keep
1724 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001725 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001726 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001727 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001728 } else {
1729 // If this process doesn't have activities, we less strongly
1730 // want to keep it around, and generally want to avoid getting
1731 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001732 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001733 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001734 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001735 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001736
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001737 while (i >= 0) {
1738 ProcessRecord p = mLruProcesses.get(i);
1739 // If this app shouldn't be in front of the first N background
1740 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001741 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001742 skipTop--;
1743 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001744 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001745 mLruProcesses.add(i+1, app);
1746 break;
1747 }
1748 i--;
1749 }
1750 if (i < 0) {
1751 mLruProcesses.add(0, app);
1752 }
1753
Dianne Hackborn906497c2010-05-10 15:57:38 -07001754 // If the app is currently using a content provider or service,
1755 // bump those processes as well.
1756 if (app.connections.size() > 0) {
1757 for (ConnectionRecord cr : app.connections) {
1758 if (cr.binding != null && cr.binding.service != null
1759 && cr.binding.service.app != null
1760 && cr.binding.service.app.lruSeq != mLruSeq) {
1761 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1762 updateActivityTime, i+1);
1763 }
1764 }
1765 }
1766 if (app.conProviders.size() > 0) {
1767 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001768 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1769 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001770 updateActivityTime, i+1);
1771 }
1772 }
1773 }
1774
Joe Onorato8a9b2202010-02-26 18:56:32 -08001775 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 if (oomAdj) {
1777 updateOomAdjLocked();
1778 }
1779 }
1780
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001781 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001782 boolean oomAdj, boolean updateActivityTime) {
1783 mLruSeq++;
1784 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1785 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001786
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001787 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 String processName, int uid) {
1789 if (uid == Process.SYSTEM_UID) {
1790 // The system gets to run in any process. If there are multiple
1791 // processes with the same uid, just pick the first (this
1792 // should never happen).
1793 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1794 processName);
1795 return procs != null ? procs.valueAt(0) : null;
1796 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001797 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 ProcessRecord proc = mProcessNames.get(processName, uid);
1799 return proc;
1800 }
1801
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001802 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001803 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001804 try {
1805 if (pm.performDexOpt(packageName)) {
1806 mDidDexOpt = true;
1807 }
1808 } catch (RemoteException e) {
1809 }
1810 }
1811
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001812 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 int transit = mWindowManager.getPendingAppTransition();
1814 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1815 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1816 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1817 }
1818
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001819 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001821 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1822 boolean isolated) {
1823 ProcessRecord app;
1824 if (!isolated) {
1825 app = getProcessRecordLocked(processName, info.uid);
1826 } else {
1827 // If this is an isolated process, it can't re-use an existing process.
1828 app = null;
1829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 // We don't have to do anything more if:
1831 // (1) There is an existing application record; and
1832 // (2) The caller doesn't think it is dead, OR there is no thread
1833 // object attached to it so we know it couldn't have crashed; and
1834 // (3) There is a pid assigned to it, so it is either starting or
1835 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001836 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 + " app=" + app + " knownToBeDead=" + knownToBeDead
1838 + " thread=" + (app != null ? app.thread : null)
1839 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001840 if (app != null && app.pid > 0) {
1841 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001842 // We already have the app running, or are waiting for it to
1843 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001844 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001845 // If this is a new package in the process, add the package to the list
1846 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001847 return app;
1848 } else {
1849 // An application record is attached to a previous process,
1850 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001851 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001852 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 String hostingNameStr = hostingName != null
1857 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001858
1859 if (!isolated) {
1860 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1861 // If we are in the background, then check to see if this process
1862 // is bad. If so, we will just silently fail.
1863 if (mBadProcesses.get(info.processName, info.uid) != null) {
1864 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1865 + "/" + info.processName);
1866 return null;
1867 }
1868 } else {
1869 // When the user is explicitly starting a process, then clear its
1870 // crash count so that we won't make it bad until they see at
1871 // least one crash dialog again, and make the process good again
1872 // if it had been bad.
1873 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001874 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001875 mProcessCrashTimes.remove(info.processName, info.uid);
1876 if (mBadProcesses.get(info.processName, info.uid) != null) {
1877 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1878 info.processName);
1879 mBadProcesses.remove(info.processName, info.uid);
1880 if (app != null) {
1881 app.bad = false;
1882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
1884 }
1885 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001888 app = newProcessRecordLocked(null, info, processName, isolated);
1889 if (app == null) {
1890 Slog.w(TAG, "Failed making new process record for "
1891 + processName + "/" + info.uid + " isolated=" + isolated);
1892 return null;
1893 }
1894 mProcessNames.put(processName, app.uid, app);
1895 if (isolated) {
1896 mIsolatedProcesses.put(app.uid, app);
1897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 } else {
1899 // If this is a new package in the process, add the package to the list
1900 app.addPackage(info.packageName);
1901 }
1902
1903 // If the system is not ready yet, then hold off on starting this
1904 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001905 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001906 && !isAllowedWhileBooting(info)
1907 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 if (!mProcessesOnHold.contains(app)) {
1909 mProcessesOnHold.add(app);
1910 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001911 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 return app;
1913 }
1914
1915 startProcessLocked(app, hostingType, hostingNameStr);
1916 return (app.pid != 0) ? app : null;
1917 }
1918
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001919 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1920 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1921 }
1922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 private final void startProcessLocked(ProcessRecord app,
1924 String hostingType, String hostingNameStr) {
1925 if (app.pid > 0 && app.pid != MY_PID) {
1926 synchronized (mPidsSelfLocked) {
1927 mPidsSelfLocked.remove(app.pid);
1928 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1929 }
1930 app.pid = 0;
1931 }
1932
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001933 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1934 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 mProcessesOnHold.remove(app);
1936
1937 updateCpuStats();
1938
1939 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1940 mProcDeaths[0] = 0;
1941
1942 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001943 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001946 if (!app.isolated) {
1947 try {
1948 gids = mContext.getPackageManager().getPackageGids(
1949 app.info.packageName);
1950 } catch (PackageManager.NameNotFoundException e) {
1951 Slog.w(TAG, "Unable to retrieve gids", e);
1952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 }
1954 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1955 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1956 && mTopComponent != null
1957 && app.processName.equals(mTopComponent.getPackageName())) {
1958 uid = 0;
1959 }
1960 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1961 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1962 uid = 0;
1963 }
1964 }
1965 int debugFlags = 0;
1966 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1967 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001968 // Also turn on CheckJNI for debuggable apps. It's quite
1969 // awkward to turn on otherwise.
1970 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001972 // Run the app in safe mode if its manifest requests so or the
1973 // system is booted in safe mode.
1974 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1975 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001976 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1979 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1980 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001981 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1982 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 if ("1".equals(SystemProperties.get("debug.assert"))) {
1985 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1986 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001987
1988 // Start the process. It will either succeed and return a result containing
1989 // the PID of the new process, or else throw a RuntimeException.
1990 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001991 app.processName, uid, uid, gids, debugFlags,
1992 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07001993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1995 synchronized (bs) {
1996 if (bs.isOnBattery()) {
1997 app.batteryStats.incStartsLocked();
1998 }
1999 }
2000
Jeff Brown3f9dd282011-07-08 20:02:19 -07002001 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 app.processName, hostingType,
2003 hostingNameStr != null ? hostingNameStr : "");
2004
2005 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002006 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 }
2008
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002009 StringBuilder buf = mStringBuilder;
2010 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 buf.append("Start proc ");
2012 buf.append(app.processName);
2013 buf.append(" for ");
2014 buf.append(hostingType);
2015 if (hostingNameStr != null) {
2016 buf.append(" ");
2017 buf.append(hostingNameStr);
2018 }
2019 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002020 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 buf.append(" uid=");
2022 buf.append(uid);
2023 buf.append(" gids={");
2024 if (gids != null) {
2025 for (int gi=0; gi<gids.length; gi++) {
2026 if (gi != 0) buf.append(", ");
2027 buf.append(gids[gi]);
2028
2029 }
2030 }
2031 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002032 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002033 app.pid = startResult.pid;
2034 app.usingWrapper = startResult.usingWrapper;
2035 app.removed = false;
2036 synchronized (mPidsSelfLocked) {
2037 this.mPidsSelfLocked.put(startResult.pid, app);
2038 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2039 msg.obj = app;
2040 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2041 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 }
2043 } catch (RuntimeException e) {
2044 // XXX do better error recovery.
2045 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002046 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 }
2048 }
2049
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002050 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 if (resumed) {
2052 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2053 } else {
2054 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2055 }
2056 }
2057
Amith Yamasani742a6712011-05-04 14:49:28 -07002058 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002059 if (mHeadless) {
2060 // Added because none of the other calls to ensureBootCompleted seem to fire
2061 // when running headless.
2062 ensureBootCompleted();
2063 return false;
2064 }
2065
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002066 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2067 && mTopAction == null) {
2068 // We are running in factory test mode, but unable to find
2069 // the factory test app, so just sit around displaying the
2070 // error message and don't try to start anything.
2071 return false;
2072 }
2073 Intent intent = new Intent(
2074 mTopAction,
2075 mTopData != null ? Uri.parse(mTopData) : null);
2076 intent.setComponent(mTopComponent);
2077 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2078 intent.addCategory(Intent.CATEGORY_HOME);
2079 }
2080 ActivityInfo aInfo =
2081 intent.resolveActivityInfo(mContext.getPackageManager(),
2082 STOCK_PM_FLAGS);
2083 if (aInfo != null) {
2084 intent.setComponent(new ComponentName(
2085 aInfo.applicationInfo.packageName, aInfo.name));
2086 // Don't do this if the home app is currently being
2087 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002088 aInfo = new ActivityInfo(aInfo);
2089 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002090 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2091 aInfo.applicationInfo.uid);
2092 if (app == null || app.instrumentationClass == null) {
2093 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002094 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002095 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002096 }
2097 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002098
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002099 return true;
2100 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002101
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002102 /**
2103 * Starts the "new version setup screen" if appropriate.
2104 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002105 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002106 // Only do this once per boot.
2107 if (mCheckedForSetup) {
2108 return;
2109 }
2110
2111 // We will show this screen if the current one is a different
2112 // version than the last one shown, and we are not running in
2113 // low-level factory test mode.
2114 final ContentResolver resolver = mContext.getContentResolver();
2115 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2116 Settings.Secure.getInt(resolver,
2117 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2118 mCheckedForSetup = true;
2119
2120 // See if we should be showing the platform update setup UI.
2121 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2122 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2123 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2124
2125 // We don't allow third party apps to replace this.
2126 ResolveInfo ri = null;
2127 for (int i=0; ris != null && i<ris.size(); i++) {
2128 if ((ris.get(i).activityInfo.applicationInfo.flags
2129 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2130 ri = ris.get(i);
2131 break;
2132 }
2133 }
2134
2135 if (ri != null) {
2136 String vers = ri.activityInfo.metaData != null
2137 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2138 : null;
2139 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2140 vers = ri.activityInfo.applicationInfo.metaData.getString(
2141 Intent.METADATA_SETUP_VERSION);
2142 }
2143 String lastVers = Settings.Secure.getString(
2144 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2145 if (vers != null && !vers.equals(lastVers)) {
2146 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2147 intent.setComponent(new ComponentName(
2148 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002149 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002150 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002151 }
2152 }
2153 }
2154 }
2155
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002156 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002157 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002158 }
2159
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002160 void enforceNotIsolatedCaller(String caller) {
2161 if (UserId.isIsolated(Binder.getCallingUid())) {
2162 throw new SecurityException("Isolated process not allowed to call " + caller);
2163 }
2164 }
2165
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002166 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002167 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002168 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002169 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2170 }
2171 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002172
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002173 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002174 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2175 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002176 synchronized (this) {
2177 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2178 }
2179 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002180
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002181 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002182 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002183 synchronized (this) {
2184 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2185 }
2186 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002187
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002188 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002189 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2190 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002191 synchronized (this) {
2192 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002193 }
2194 }
2195
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002196 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002197 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002198 synchronized (this) {
2199 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2200 }
2201 }
2202
2203 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002204 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2205 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002206 synchronized (this) {
2207 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2208 }
2209 }
2210
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002211 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002212 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002213
2214 final int identHash = System.identityHashCode(r);
2215 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217
Jeff Sharkeya4620792011-05-20 15:29:23 -07002218 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2219 int i = mProcessObservers.beginBroadcast();
2220 while (i > 0) {
2221 i--;
2222 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2223 if (observer != null) {
2224 try {
2225 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2226 } catch (RemoteException e) {
2227 }
2228 }
2229 }
2230 mProcessObservers.finishBroadcast();
2231 }
2232
2233 private void dispatchProcessDied(int pid, int uid) {
2234 int i = mProcessObservers.beginBroadcast();
2235 while (i > 0) {
2236 i--;
2237 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2238 if (observer != null) {
2239 try {
2240 observer.onProcessDied(pid, uid);
2241 } catch (RemoteException e) {
2242 }
2243 }
2244 }
2245 mProcessObservers.finishBroadcast();
2246 }
2247
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002248 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002249 final int N = mPendingActivityLaunches.size();
2250 if (N <= 0) {
2251 return;
2252 }
2253 for (int i=0; i<N; i++) {
2254 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002255 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002256 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
2257 doResume && i == (N-1));
2258 }
2259 mPendingActivityLaunches.clear();
2260 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002261
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002262 public final int startActivity(IApplicationThread caller,
2263 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2264 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002265 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
2266 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002267 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002268 int userId = 0;
2269 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2270 // Requesting home, set the identity to the current user
2271 // HACK!
2272 userId = mCurrentUserId;
2273 } else {
2274 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2275 // the current user's userId
2276 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2277 userId = 0;
2278 } else {
2279 userId = Binder.getOrigCallingUser();
2280 }
2281 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002282 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -07002283 grantedUriPermissions, grantedMode, resultTo, resultWho, requestCode, onlyIfNeeded,
2284 debug, profileFile, profileFd, autoStopProfiler, null, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002285 }
2286
2287 public final WaitResult startActivityAndWait(IApplicationThread caller,
2288 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2289 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002290 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
2291 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002292 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002293 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002294 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002295 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002296 grantedUriPermissions, grantedMode, resultTo, resultWho,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002297 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
Amith Yamasani742a6712011-05-04 14:49:28 -07002298 res, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002299 return res;
2300 }
2301
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002302 public final int startActivityWithConfig(IApplicationThread caller,
2303 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2304 int grantedMode, IBinder resultTo,
2305 String resultWho, int requestCode, boolean onlyIfNeeded,
2306 boolean debug, Configuration config) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002307 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002308 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002309 grantedUriPermissions, grantedMode, resultTo, resultWho,
Amith Yamasani742a6712011-05-04 14:49:28 -07002310 requestCode, onlyIfNeeded,
2311 debug, null, null, false, null, config, Binder.getOrigCallingUser());
2312 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002313 }
2314
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002315 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002316 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002317 IBinder resultTo, String resultWho, int requestCode,
2318 int flagsMask, int flagsValues) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002319 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002320 // Refuse possible leaked file descriptors
2321 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2322 throw new IllegalArgumentException("File descriptors passed in Intent");
2323 }
2324
2325 IIntentSender sender = intent.getTarget();
2326 if (!(sender instanceof PendingIntentRecord)) {
2327 throw new IllegalArgumentException("Bad PendingIntent object");
2328 }
2329
2330 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002331
2332 synchronized (this) {
2333 // If this is coming from the currently resumed activity, it is
2334 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002335 if (mMainStack.mResumedActivity != null
2336 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002337 Binder.getCallingUid()) {
2338 mAppSwitchesAllowedTime = 0;
2339 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002340 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002341 int ret = pir.sendInner(0, fillInIntent, resolvedType, null,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002342 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
Amith Yamasani742a6712011-05-04 14:49:28 -07002343 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002344 }
2345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 public boolean startNextMatchingActivity(IBinder callingActivity,
2347 Intent intent) {
2348 // Refuse possible leaked file descriptors
2349 if (intent != null && intent.hasFileDescriptors() == true) {
2350 throw new IllegalArgumentException("File descriptors passed in Intent");
2351 }
2352
2353 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002354 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2355 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 return false;
2357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 if (r.app == null || r.app.thread == null) {
2359 // The caller is not running... d'oh!
2360 return false;
2361 }
2362 intent = new Intent(intent);
2363 // The caller is not allowed to change the data.
2364 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2365 // And we are resetting to find the next component...
2366 intent.setComponent(null);
2367
2368 ActivityInfo aInfo = null;
2369 try {
2370 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002371 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002373 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374
2375 // Look for the original activity in the list...
2376 final int N = resolves != null ? resolves.size() : 0;
2377 for (int i=0; i<N; i++) {
2378 ResolveInfo rInfo = resolves.get(i);
2379 if (rInfo.activityInfo.packageName.equals(r.packageName)
2380 && rInfo.activityInfo.name.equals(r.info.name)) {
2381 // We found the current one... the next matching is
2382 // after it.
2383 i++;
2384 if (i<N) {
2385 aInfo = resolves.get(i).activityInfo;
2386 }
2387 break;
2388 }
2389 }
2390 } catch (RemoteException e) {
2391 }
2392
2393 if (aInfo == null) {
2394 // Nobody who is next!
2395 return false;
2396 }
2397
2398 intent.setComponent(new ComponentName(
2399 aInfo.applicationInfo.packageName, aInfo.name));
2400 intent.setFlags(intent.getFlags()&~(
2401 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2402 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2403 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2404 Intent.FLAG_ACTIVITY_NEW_TASK));
2405
2406 // Okay now we need to start the new activity, replacing the
2407 // currently running activity. This is a little tricky because
2408 // we want to start the new one as if the current one is finished,
2409 // but not finish the current one first so that there is no flicker.
2410 // And thus...
2411 final boolean wasFinishing = r.finishing;
2412 r.finishing = true;
2413
2414 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002415 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 final String resultWho = r.resultWho;
2417 final int requestCode = r.requestCode;
2418 r.resultTo = null;
2419 if (resultTo != null) {
2420 resultTo.removeResultsLocked(r, resultWho, requestCode);
2421 }
2422
2423 final long origId = Binder.clearCallingIdentity();
2424 // XXX we are not dealing with propagating grantedUriPermissions...
2425 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002426 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002427 r.resolvedType, null, 0, aInfo,
2428 resultTo != null ? resultTo.appToken : null, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002429 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 Binder.restoreCallingIdentity(origId);
2431
2432 r.finishing = wasFinishing;
2433 if (res != START_SUCCESS) {
2434 return false;
2435 }
2436 return true;
2437 }
2438 }
2439
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002440 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 Intent intent, String resolvedType, IBinder resultTo,
2442 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002443
2444 // This is so super not safe, that only the system (or okay root)
2445 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002446 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002447 final int callingUid = Binder.getCallingUid();
2448 if (callingUid != 0 && callingUid != Process.myUid()) {
2449 throw new SecurityException(
2450 "startActivityInPackage only available to the system");
2451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452
Amith Yamasani742a6712011-05-04 14:49:28 -07002453 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002454 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false,
Amith Yamasani742a6712011-05-04 14:49:28 -07002455 null, null, false, null, null, userId);
2456 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002457 }
2458
2459 public final int startActivities(IApplicationThread caller,
2460 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002461 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002462 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
2463 Binder.getOrigCallingUser());
2464 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002465 }
2466
2467 public final int startActivitiesInPackage(int uid,
2468 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2469
2470 // This is so super not safe, that only the system (or okay root)
2471 // can do it.
2472 final int callingUid = Binder.getCallingUid();
2473 if (callingUid != 0 && callingUid != Process.myUid()) {
2474 throw new SecurityException(
2475 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002477 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
2478 UserId.getUserId(uid));
2479 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 }
2481
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002482 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002484 // Quick case: check if the top-most recent task is the same.
2485 if (N > 0 && mRecentTasks.get(0) == task) {
2486 return;
2487 }
2488 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 for (int i=0; i<N; i++) {
2490 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002491 if (task.userId == tr.userId
2492 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2493 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 mRecentTasks.remove(i);
2495 i--;
2496 N--;
2497 if (task.intent == null) {
2498 // If the new recent task we are adding is not fully
2499 // specified, then replace it with the existing recent task.
2500 task = tr;
2501 }
2502 }
2503 }
2504 if (N >= MAX_RECENT_TASKS) {
2505 mRecentTasks.remove(N-1);
2506 }
2507 mRecentTasks.add(0, task);
2508 }
2509
2510 public void setRequestedOrientation(IBinder token,
2511 int requestedOrientation) {
2512 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002513 ActivityRecord r = mMainStack.isInStackLocked(token);
2514 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 return;
2516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002518 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002520 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002521 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 if (config != null) {
2523 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002524 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002525 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 }
2527 }
2528 Binder.restoreCallingIdentity(origId);
2529 }
2530 }
2531
2532 public int getRequestedOrientation(IBinder token) {
2533 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002534 ActivityRecord r = mMainStack.isInStackLocked(token);
2535 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2537 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002538 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 }
2540 }
2541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 /**
2543 * This is the internal entry point for handling Activity.finish().
2544 *
2545 * @param token The Binder token referencing the Activity we want to finish.
2546 * @param resultCode Result code, if any, from this Activity.
2547 * @param resultData Result data (Intent), if any, from this Activity.
2548 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002549 * @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 -08002550 */
2551 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2552 // Refuse possible leaked file descriptors
2553 if (resultData != null && resultData.hasFileDescriptors() == true) {
2554 throw new IllegalArgumentException("File descriptors passed in Intent");
2555 }
2556
2557 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002558 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002560 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 if (next != null) {
2562 // ask watcher if this is allowed
2563 boolean resumeOK = true;
2564 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002565 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002567 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 }
2569
2570 if (!resumeOK) {
2571 return false;
2572 }
2573 }
2574 }
2575 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002576 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 resultData, "app-request");
2578 Binder.restoreCallingIdentity(origId);
2579 return res;
2580 }
2581 }
2582
Dianne Hackborn860755f2010-06-03 18:47:52 -07002583 public final void finishHeavyWeightApp() {
2584 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2585 != PackageManager.PERMISSION_GRANTED) {
2586 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2587 + Binder.getCallingPid()
2588 + ", uid=" + Binder.getCallingUid()
2589 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2590 Slog.w(TAG, msg);
2591 throw new SecurityException(msg);
2592 }
2593
2594 synchronized(this) {
2595 if (mHeavyWeightProcess == null) {
2596 return;
2597 }
2598
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002599 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002600 mHeavyWeightProcess.activities);
2601 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002602 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002603 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002604 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002605 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002606 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002607 null, "finish-heavy");
2608 }
2609 }
2610 }
2611
2612 mHeavyWeightProcess = null;
2613 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2614 }
2615 }
2616
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002617 public void crashApplication(int uid, int initialPid, String packageName,
2618 String message) {
2619 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2620 != PackageManager.PERMISSION_GRANTED) {
2621 String msg = "Permission Denial: crashApplication() from pid="
2622 + Binder.getCallingPid()
2623 + ", uid=" + Binder.getCallingUid()
2624 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2625 Slog.w(TAG, msg);
2626 throw new SecurityException(msg);
2627 }
2628
2629 synchronized(this) {
2630 ProcessRecord proc = null;
2631
2632 // Figure out which process to kill. We don't trust that initialPid
2633 // still has any relation to current pids, so must scan through the
2634 // list.
2635 synchronized (mPidsSelfLocked) {
2636 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2637 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002638 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002639 continue;
2640 }
2641 if (p.pid == initialPid) {
2642 proc = p;
2643 break;
2644 }
2645 for (String str : p.pkgList) {
2646 if (str.equals(packageName)) {
2647 proc = p;
2648 }
2649 }
2650 }
2651 }
2652
2653 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002654 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002655 + " initialPid=" + initialPid
2656 + " packageName=" + packageName);
2657 return;
2658 }
2659
2660 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002661 if (proc.pid == Process.myPid()) {
2662 Log.w(TAG, "crashApplication: trying to crash self!");
2663 return;
2664 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002665 long ident = Binder.clearCallingIdentity();
2666 try {
2667 proc.thread.scheduleCrash(message);
2668 } catch (RemoteException e) {
2669 }
2670 Binder.restoreCallingIdentity(ident);
2671 }
2672 }
2673 }
2674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 public final void finishSubActivity(IBinder token, String resultWho,
2676 int requestCode) {
2677 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002678 ActivityRecord self = mMainStack.isInStackLocked(token);
2679 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 return;
2681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682
2683 final long origId = Binder.clearCallingIdentity();
2684
2685 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002686 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2687 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 if (r.resultTo == self && r.requestCode == requestCode) {
2689 if ((r.resultWho == null && resultWho == null) ||
2690 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002691 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 Activity.RESULT_CANCELED, null, "request-sub");
2693 }
2694 }
2695 }
2696
2697 Binder.restoreCallingIdentity(origId);
2698 }
2699 }
2700
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002701 public boolean willActivityBeVisible(IBinder token) {
2702 synchronized(this) {
2703 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002704 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2705 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002706 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002707 return true;
2708 }
2709 if (r.fullscreen && !r.finishing) {
2710 return false;
2711 }
2712 }
2713 return true;
2714 }
2715 }
2716
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002717 public void overridePendingTransition(IBinder token, String packageName,
2718 int enterAnim, int exitAnim) {
2719 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002720 ActivityRecord self = mMainStack.isInStackLocked(token);
2721 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002722 return;
2723 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002724
2725 final long origId = Binder.clearCallingIdentity();
2726
2727 if (self.state == ActivityState.RESUMED
2728 || self.state == ActivityState.PAUSING) {
2729 mWindowManager.overridePendingAppTransition(packageName,
2730 enterAnim, exitAnim);
2731 }
2732
2733 Binder.restoreCallingIdentity(origId);
2734 }
2735 }
2736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 * Main function for removing an existing process from the activity manager
2739 * as a result of that process going away. Clears out all connections
2740 * to the process.
2741 */
2742 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002743 boolean restarting, boolean allowRestart) {
2744 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002746 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 }
2748
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002749 if (mProfileProc == app) {
2750 clearProfilerLocked();
2751 }
2752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002754 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2755 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2756 mMainStack.mPausingActivity = null;
2757 }
2758 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2759 mMainStack.mLastPausedActivity = null;
2760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761
2762 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002763 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764
2765 boolean atTop = true;
2766 boolean hasVisibleActivities = false;
2767
2768 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002769 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002770 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 TAG, "Removing app " + app + " from history with " + i + " entries");
2772 while (i > 0) {
2773 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002774 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002775 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2777 if (r.app == app) {
2778 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002779 if (ActivityStack.DEBUG_ADD_REMOVE) {
2780 RuntimeException here = new RuntimeException("here");
2781 here.fillInStackTrace();
2782 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2783 + ": haveState=" + r.haveState
2784 + " stateNotNeeded=" + r.stateNotNeeded
2785 + " finishing=" + r.finishing
2786 + " state=" + r.state, here);
2787 }
2788 if (!r.finishing) {
2789 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002790 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2791 System.identityHashCode(r),
2792 r.task.taskId, r.shortComponentName,
2793 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002794 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002795 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796
2797 } else {
2798 // We have the current state for this activity, so
2799 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002800 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 TAG, "Keeping entry, setting app to null");
2802 if (r.visible) {
2803 hasVisibleActivities = true;
2804 }
2805 r.app = null;
2806 r.nowVisible = false;
2807 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002808 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2809 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 r.icicle = null;
2811 }
2812 }
2813
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002814 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 }
2816 atTop = false;
2817 }
2818
2819 app.activities.clear();
2820
2821 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002822 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 + " running instrumentation " + app.instrumentationClass);
2824 Bundle info = new Bundle();
2825 info.putString("shortMsg", "Process crashed.");
2826 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2827 }
2828
2829 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002830 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 // If there was nothing to resume, and we are not already
2832 // restarting this process, but there is a visible activity that
2833 // is hosted by the process... then make sure all visible
2834 // activities are running, taking care of restarting this
2835 // process.
2836 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002837 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 }
2839 }
2840 }
2841 }
2842
2843 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2844 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002846 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2847 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2849 return i;
2850 }
2851 }
2852 return -1;
2853 }
2854
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002855 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 IApplicationThread thread) {
2857 if (thread == null) {
2858 return null;
2859 }
2860
2861 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002862 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 }
2864
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002865 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 IApplicationThread thread) {
2867
2868 mProcDeaths[0]++;
2869
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002870 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2871 synchronized (stats) {
2872 stats.noteProcessDiedLocked(app.info.uid, pid);
2873 }
2874
Magnus Edlund7bb25812010-02-24 15:45:06 +01002875 // Clean up already done if the process has been re-started.
2876 if (app.pid == pid && app.thread != null &&
2877 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002878 if (!app.killedBackground) {
2879 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2880 + ") has died.");
2881 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002882 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002883 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 TAG, "Dying app: " + app + ", pid: " + pid
2885 + ", thread: " + thread.asBinder());
2886 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002887 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888
2889 if (doLowMem) {
2890 // If there are no longer any background processes running,
2891 // and the app that died was not running instrumentation,
2892 // then tell everyone we are now low on memory.
2893 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002894 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2895 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002896 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 haveBg = true;
2898 break;
2899 }
2900 }
2901
2902 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002903 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002904 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002905 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2906 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002907 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002908 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2909 // The low memory report is overriding any current
2910 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002911 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002912 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002913 rec.lastRequestedGc = 0;
2914 } else {
2915 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002917 rec.reportLowMemory = true;
2918 rec.lastLowMemory = now;
2919 mProcessesToGc.remove(rec);
2920 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 }
2922 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002923 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002924 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 }
2926 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002927 } else if (app.pid != pid) {
2928 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002929 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002930 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002931 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002932 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002933 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 + thread.asBinder());
2935 }
2936 }
2937
Dan Egnor42471dd2010-01-07 17:25:22 -08002938 /**
2939 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002940 * @param clearTraces causes the dump file to be erased prior to the new
2941 * traces being written, if true; when false, the new traces will be
2942 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002943 * @param firstPids of dalvik VM processes to dump stack traces for first
2944 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002945 * @return file containing stack traces, or null if no dump file is configured
2946 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002947 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2948 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002949 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2950 if (tracesPath == null || tracesPath.length() == 0) {
2951 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002953
2954 File tracesFile = new File(tracesPath);
2955 try {
2956 File tracesDir = tracesFile.getParentFile();
2957 if (!tracesDir.exists()) tracesFile.mkdirs();
2958 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2959
Christopher Tate6ee412d2010-05-28 12:01:56 -07002960 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002961 tracesFile.createNewFile();
2962 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2963 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002964 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002965 return null;
2966 }
2967
2968 // Use a FileObserver to detect when traces finish writing.
2969 // The order of traces is considered important to maintain for legibility.
2970 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2971 public synchronized void onEvent(int event, String path) { notify(); }
2972 };
2973
2974 try {
2975 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002976
2977 // First collect all of the stacks of the most important pids.
2978 try {
2979 int num = firstPids.size();
2980 for (int i = 0; i < num; i++) {
2981 synchronized (observer) {
2982 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2983 observer.wait(200); // Wait for write-close, give up after 200msec
2984 }
2985 }
2986 } catch (InterruptedException e) {
2987 Log.wtf(TAG, e);
2988 }
2989
2990 // Next measure CPU usage.
2991 if (processStats != null) {
2992 processStats.init();
2993 System.gc();
2994 processStats.update();
2995 try {
2996 synchronized (processStats) {
2997 processStats.wait(500); // measure over 1/2 second.
2998 }
2999 } catch (InterruptedException e) {
3000 }
3001 processStats.update();
3002
3003 // We'll take the stack crawls of just the top apps using CPU.
3004 final int N = processStats.countWorkingStats();
3005 int numProcs = 0;
3006 for (int i=0; i<N && numProcs<5; i++) {
3007 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3008 if (lastPids.indexOfKey(stats.pid) >= 0) {
3009 numProcs++;
3010 try {
3011 synchronized (observer) {
3012 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3013 observer.wait(200); // Wait for write-close, give up after 200msec
3014 }
3015 } catch (InterruptedException e) {
3016 Log.wtf(TAG, e);
3017 }
3018
3019 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003020 }
3021 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003022
3023 return tracesFile;
3024
Dan Egnor42471dd2010-01-07 17:25:22 -08003025 } finally {
3026 observer.stopWatching();
3027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 }
3029
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003030 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3031 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003032 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3033 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3034
Dianne Hackborn287952c2010-09-22 22:34:31 -07003035 if (mController != null) {
3036 try {
3037 // 0 == continue, -1 = kill process immediately
3038 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3039 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3040 } catch (RemoteException e) {
3041 mController = null;
3042 }
3043 }
3044
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003045 long anrTime = SystemClock.uptimeMillis();
3046 if (MONITOR_CPU_USAGE) {
3047 updateCpuStatsNow();
3048 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003049
3050 synchronized (this) {
3051 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3052 if (mShuttingDown) {
3053 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3054 return;
3055 } else if (app.notResponding) {
3056 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3057 return;
3058 } else if (app.crashing) {
3059 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3060 return;
3061 }
3062
3063 // In case we come through here for the same app before completing
3064 // this one, mark as anring now so we will bail out.
3065 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003066
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003067 // Log the ANR to the event log.
3068 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3069 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003070
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003071 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003072 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003073
3074 int parentPid = app.pid;
3075 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003076 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003077
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003078 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003079
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003080 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3081 ProcessRecord r = mLruProcesses.get(i);
3082 if (r != null && r.thread != null) {
3083 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003084 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3085 if (r.persistent) {
3086 firstPids.add(pid);
3087 } else {
3088 lastPids.put(pid, Boolean.TRUE);
3089 }
3090 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 }
3093 }
3094
Dan Egnor42471dd2010-01-07 17:25:22 -08003095 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003096 StringBuilder info = mStringBuilder;
3097 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003098 info.append("ANR in ").append(app.processName);
3099 if (activity != null && activity.shortComponentName != null) {
3100 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003101 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003102 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003103 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003104 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003106 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003107 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109
Dianne Hackborn287952c2010-09-22 22:34:31 -07003110 final ProcessStats processStats = new ProcessStats(true);
3111
3112 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3113
Dan Egnor42471dd2010-01-07 17:25:22 -08003114 String cpuInfo = null;
3115 if (MONITOR_CPU_USAGE) {
3116 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003117 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003118 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003119 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003120 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003121 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 }
3123
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003124 info.append(processStats.printCurrentState(anrTime));
3125
Joe Onorato8a9b2202010-02-26 18:56:32 -08003126 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003127 if (tracesFile == null) {
3128 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3129 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3130 }
3131
Jeff Sharkeya353d262011-10-28 11:12:06 -07003132 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3133 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003134
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003135 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003137 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3138 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003140 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3141 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 }
3143 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003144 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 }
3146 }
3147
Dan Egnor42471dd2010-01-07 17:25:22 -08003148 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3149 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3150 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003151
3152 synchronized (this) {
3153 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003154 Slog.w(TAG, "Killing " + app + ": background ANR");
3155 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3156 app.processName, app.setAdj, "background ANR");
3157 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003158 return;
3159 }
3160
3161 // Set the app's notResponding state, and look up the errorReportReceiver
3162 makeAppNotRespondingLocked(app,
3163 activity != null ? activity.shortComponentName : null,
3164 annotation != null ? "ANR " + annotation : "ANR",
3165 info.toString());
3166
3167 // Bring up the infamous App Not Responding dialog
3168 Message msg = Message.obtain();
3169 HashMap map = new HashMap();
3170 msg.what = SHOW_NOT_RESPONDING_MSG;
3171 msg.obj = map;
3172 map.put("app", app);
3173 if (activity != null) {
3174 map.put("activity", activity);
3175 }
3176
3177 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 }
3180
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003181 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3182 if (!mLaunchWarningShown) {
3183 mLaunchWarningShown = true;
3184 mHandler.post(new Runnable() {
3185 @Override
3186 public void run() {
3187 synchronized (ActivityManagerService.this) {
3188 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3189 d.show();
3190 mHandler.postDelayed(new Runnable() {
3191 @Override
3192 public void run() {
3193 synchronized (ActivityManagerService.this) {
3194 d.dismiss();
3195 mLaunchWarningShown = false;
3196 }
3197 }
3198 }, 4000);
3199 }
3200 }
3201 });
3202 }
3203 }
3204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003206 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003207 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 int uid = Binder.getCallingUid();
3209 int pid = Binder.getCallingPid();
3210 long callingId = Binder.clearCallingIdentity();
3211 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003212 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 int pkgUid = -1;
3214 synchronized(this) {
3215 try {
3216 pkgUid = pm.getPackageUid(packageName);
3217 } catch (RemoteException e) {
3218 }
3219 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003220 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 return false;
3222 }
3223 if (uid == pkgUid || checkComponentPermission(
3224 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003225 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003227 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 } else {
3229 throw new SecurityException(pid+" does not have permission:"+
3230 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3231 "for process:"+packageName);
3232 }
3233 }
3234
3235 try {
3236 //clear application user data
3237 pm.clearApplicationUserData(packageName, observer);
3238 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3239 Uri.fromParts("package", packageName, null));
3240 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003241 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003242 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003243 } catch (RemoteException e) {
3244 }
3245 } finally {
3246 Binder.restoreCallingIdentity(callingId);
3247 }
3248 return true;
3249 }
3250
Dianne Hackborn03abb812010-01-04 18:43:19 -08003251 public void killBackgroundProcesses(final String packageName) {
3252 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3253 != PackageManager.PERMISSION_GRANTED &&
3254 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3255 != PackageManager.PERMISSION_GRANTED) {
3256 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 + Binder.getCallingPid()
3258 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003259 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003260 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 throw new SecurityException(msg);
3262 }
3263
3264 long callingId = Binder.clearCallingIdentity();
3265 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003266 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 int pkgUid = -1;
3268 synchronized(this) {
3269 try {
3270 pkgUid = pm.getPackageUid(packageName);
3271 } catch (RemoteException e) {
3272 }
3273 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003274 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 return;
3276 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003277 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003278 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3279 }
3280 } finally {
3281 Binder.restoreCallingIdentity(callingId);
3282 }
3283 }
3284
3285 public void killAllBackgroundProcesses() {
3286 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3287 != PackageManager.PERMISSION_GRANTED) {
3288 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3289 + Binder.getCallingPid()
3290 + ", uid=" + Binder.getCallingUid()
3291 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3292 Slog.w(TAG, msg);
3293 throw new SecurityException(msg);
3294 }
3295
3296 long callingId = Binder.clearCallingIdentity();
3297 try {
3298 synchronized(this) {
3299 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3300 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3301 final int NA = apps.size();
3302 for (int ia=0; ia<NA; ia++) {
3303 ProcessRecord app = apps.valueAt(ia);
3304 if (app.persistent) {
3305 // we don't kill persistent processes
3306 continue;
3307 }
3308 if (app.removed) {
3309 procs.add(app);
3310 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3311 app.removed = true;
3312 procs.add(app);
3313 }
3314 }
3315 }
3316
3317 int N = procs.size();
3318 for (int i=0; i<N; i++) {
3319 removeProcessLocked(procs.get(i), false, true, "kill all background");
3320 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003321 }
3322 } finally {
3323 Binder.restoreCallingIdentity(callingId);
3324 }
3325 }
3326
3327 public void forceStopPackage(final String packageName) {
3328 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3329 != PackageManager.PERMISSION_GRANTED) {
3330 String msg = "Permission Denial: forceStopPackage() from pid="
3331 + Binder.getCallingPid()
3332 + ", uid=" + Binder.getCallingUid()
3333 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003334 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003335 throw new SecurityException(msg);
3336 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003337 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003338 long callingId = Binder.clearCallingIdentity();
3339 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003340 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003341 int pkgUid = -1;
3342 synchronized(this) {
3343 try {
3344 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07003345 // Convert the uid to the one for the calling user
3346 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003347 } catch (RemoteException e) {
3348 }
3349 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003350 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003351 return;
3352 }
3353 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003354 try {
3355 pm.setPackageStoppedState(packageName, true);
3356 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003357 } catch (IllegalArgumentException e) {
3358 Slog.w(TAG, "Failed trying to unstop package "
3359 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 }
3362 } finally {
3363 Binder.restoreCallingIdentity(callingId);
3364 }
3365 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003366
3367 /*
3368 * The pkg name and uid have to be specified.
3369 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3370 */
3371 public void killApplicationWithUid(String pkg, int uid) {
3372 if (pkg == null) {
3373 return;
3374 }
3375 // Make sure the uid is valid.
3376 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003377 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003378 return;
3379 }
3380 int callerUid = Binder.getCallingUid();
3381 // Only the system server can kill an application
3382 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003383 // Post an aysnc message to kill the application
3384 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3385 msg.arg1 = uid;
3386 msg.arg2 = 0;
3387 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003388 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003389 } else {
3390 throw new SecurityException(callerUid + " cannot kill pkg: " +
3391 pkg);
3392 }
3393 }
3394
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003395 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003396 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003397 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003398 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003399 if (reason != null) {
3400 intent.putExtra("reason", reason);
3401 }
3402
3403 final int uid = Binder.getCallingUid();
3404 final long origId = Binder.clearCallingIdentity();
3405 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003406 mWindowManager.closeSystemDialogs(reason);
3407
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003408 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003409 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003410 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003411 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003412 Activity.RESULT_CANCELED, null, "close-sys");
3413 }
3414 }
3415
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003416 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003417 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003418 }
3419 Binder.restoreCallingIdentity(origId);
3420 }
3421
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003422 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003423 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003424 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003425 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3426 for (int i=pids.length-1; i>=0; i--) {
3427 infos[i] = new Debug.MemoryInfo();
3428 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003429 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003430 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003431 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003432
Dianne Hackbornb437e092011-08-05 17:50:29 -07003433 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003434 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003435 long[] pss = new long[pids.length];
3436 for (int i=pids.length-1; i>=0; i--) {
3437 pss[i] = Debug.getPss(pids[i]);
3438 }
3439 return pss;
3440 }
3441
Christopher Tate5e1ab332009-09-01 20:32:49 -07003442 public void killApplicationProcess(String processName, int uid) {
3443 if (processName == null) {
3444 return;
3445 }
3446
3447 int callerUid = Binder.getCallingUid();
3448 // Only the system server can kill an application
3449 if (callerUid == Process.SYSTEM_UID) {
3450 synchronized (this) {
3451 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003452 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003453 try {
3454 app.thread.scheduleSuicide();
3455 } catch (RemoteException e) {
3456 // If the other end already died, then our work here is done.
3457 }
3458 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003459 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003460 + processName + " / " + uid);
3461 }
3462 }
3463 } else {
3464 throw new SecurityException(callerUid + " cannot kill app process: " +
3465 processName);
3466 }
3467 }
3468
Dianne Hackborn03abb812010-01-04 18:43:19 -08003469 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07003470 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3472 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003473 if (!mProcessesReady) {
3474 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 intent.putExtra(Intent.EXTRA_UID, uid);
3477 broadcastIntentLocked(null, null, intent,
3478 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003479 false, false,
3480 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 }
3482
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003483 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003484 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003485 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003486 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487
Dianne Hackborn03abb812010-01-04 18:43:19 -08003488 // Remove all processes this package may have touched: all with the
3489 // same UID (except for the system or root user), and all whose name
3490 // matches the package name.
3491 final String procNamePrefix = packageName + ":";
3492 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3493 final int NA = apps.size();
3494 for (int ia=0; ia<NA; ia++) {
3495 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003496 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003497 // we don't kill persistent processes
3498 continue;
3499 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003500 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003501 if (doit) {
3502 procs.add(app);
3503 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003504 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3505 || app.processName.equals(packageName)
3506 || app.processName.startsWith(procNamePrefix)) {
3507 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003508 if (!doit) {
3509 return true;
3510 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003511 app.removed = true;
3512 procs.add(app);
3513 }
3514 }
3515 }
3516 }
3517
3518 int N = procs.size();
3519 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003520 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003521 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003522 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003523 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003524
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003525 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003526 boolean callerWillRestart, boolean purgeCache, boolean doit,
3527 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003528 int i;
3529 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 if (uid < 0) {
3532 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003533 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 } catch (RemoteException e) {
3535 }
3536 }
3537
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003538 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003539 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003540
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003541 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3542 while (badApps.hasNext()) {
3543 SparseArray<Long> ba = badApps.next();
3544 if (ba.get(uid) != null) {
3545 badApps.remove();
3546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 }
3548 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003549
3550 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003551 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003553 TaskRecord lastTask = null;
3554 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003555 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003556 final boolean samePackage = r.packageName.equals(name);
3557 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003558 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003559 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003560 if (r.finishing) {
3561 // If this activity is just finishing, then it is not
3562 // interesting as far as something to stop.
3563 continue;
3564 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003565 return true;
3566 }
3567 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003568 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003569 if (samePackage) {
3570 if (r.app != null) {
3571 r.app.removed = true;
3572 }
3573 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003575 lastTask = r.task;
3576 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3577 null, "force-stop")) {
3578 i--;
3579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 }
3581 }
3582
3583 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003584 int userId = UserId.getUserId(uid);
3585 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003586 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003587 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003588 if (!doit) {
3589 return true;
3590 }
3591 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003592 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593 if (service.app != null) {
3594 service.app.removed = true;
3595 }
3596 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003597 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003598 services.add(service);
3599 }
3600 }
3601
3602 N = services.size();
3603 for (i=0; i<N; i++) {
3604 bringDownServiceLocked(services.get(i), true);
3605 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003606
3607 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani37ce3a82012-02-06 12:04:42 -08003608 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(-1).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003609 if (provider.info.packageName.equals(name)
3610 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3611 if (!doit) {
3612 return true;
3613 }
3614 didSomething = true;
3615 providers.add(provider);
3616 }
3617 }
3618
3619 N = providers.size();
3620 for (i=0; i<N; i++) {
3621 removeDyingProviderLocked(null, providers.get(i));
3622 }
3623
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003624 if (doit) {
3625 if (purgeCache) {
3626 AttributeCache ac = AttributeCache.instance();
3627 if (ac != null) {
3628 ac.removePackage(name);
3629 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003630 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003631 if (mBooted) {
3632 mMainStack.resumeTopActivityLocked(null);
3633 mMainStack.scheduleIdleLocked();
3634 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003635 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003636
3637 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003638 }
3639
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003640 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003641 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003643 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003644 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003645 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003646 + "/" + uid + ")");
3647
3648 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003649 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003650 if (mHeavyWeightProcess == app) {
3651 mHeavyWeightProcess = null;
3652 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 boolean needRestart = false;
3655 if (app.pid > 0 && app.pid != MY_PID) {
3656 int pid = app.pid;
3657 synchronized (mPidsSelfLocked) {
3658 mPidsSelfLocked.remove(pid);
3659 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3660 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003661 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003662 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003663 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003664 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003666 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003668 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 } else {
3670 needRestart = true;
3671 }
3672 }
3673 } else {
3674 mRemovedProcesses.add(app);
3675 }
3676
3677 return needRestart;
3678 }
3679
3680 private final void processStartTimedOutLocked(ProcessRecord app) {
3681 final int pid = app.pid;
3682 boolean gone = false;
3683 synchronized (mPidsSelfLocked) {
3684 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3685 if (knownApp != null && knownApp.thread == null) {
3686 mPidsSelfLocked.remove(pid);
3687 gone = true;
3688 }
3689 }
3690
3691 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003692 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003693 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003694 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003695 mProcessNames.remove(app.processName, app.uid);
3696 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003697 if (mHeavyWeightProcess == app) {
3698 mHeavyWeightProcess = null;
3699 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3700 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003701 // Take care of any launching providers waiting for this process.
3702 checkAppInLaunchingProvidersLocked(app, true);
3703 // Take care of any services that are waiting for the process.
3704 for (int i=0; i<mPendingServices.size(); i++) {
3705 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003706 if ((app.uid == sr.appInfo.uid
3707 && app.processName.equals(sr.processName))
3708 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003709 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003710 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003711 mPendingServices.remove(i);
3712 i--;
3713 bringDownServiceLocked(sr, true);
3714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003716 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3717 app.processName, app.setAdj, "start timeout");
3718 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003719 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003720 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003721 try {
3722 IBackupManager bm = IBackupManager.Stub.asInterface(
3723 ServiceManager.getService(Context.BACKUP_SERVICE));
3724 bm.agentDisconnected(app.info.packageName);
3725 } catch (RemoteException e) {
3726 // Can't happen; the backup manager is local
3727 }
3728 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003729 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003730 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003731 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003734 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 }
3736 }
3737
3738 private final boolean attachApplicationLocked(IApplicationThread thread,
3739 int pid) {
3740
3741 // Find the application record that is being attached... either via
3742 // the pid if we are running in multiple processes, or just pull the
3743 // next app record if we are emulating process with anonymous threads.
3744 ProcessRecord app;
3745 if (pid != MY_PID && pid >= 0) {
3746 synchronized (mPidsSelfLocked) {
3747 app = mPidsSelfLocked.get(pid);
3748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 } else {
3750 app = null;
3751 }
3752
3753 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003754 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003756 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003758 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 } else {
3760 try {
3761 thread.scheduleExit();
3762 } catch (Exception e) {
3763 // Ignore exceptions.
3764 }
3765 }
3766 return false;
3767 }
3768
3769 // If this application record is still attached to a previous
3770 // process, clean it up now.
3771 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003772 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 }
3774
3775 // Tell the process all about itself.
3776
Joe Onorato8a9b2202010-02-26 18:56:32 -08003777 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 TAG, "Binding process pid " + pid + " to record " + app);
3779
3780 String processName = app.processName;
3781 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003782 AppDeathRecipient adr = new AppDeathRecipient(
3783 app, pid, thread);
3784 thread.asBinder().linkToDeath(adr, 0);
3785 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 } catch (RemoteException e) {
3787 app.resetPackageList();
3788 startProcessLocked(app, "link fail", processName);
3789 return false;
3790 }
3791
Doug Zongker2bec3d42009-12-04 12:52:44 -08003792 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793
3794 app.thread = thread;
3795 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003796 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3797 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 app.forcingToForeground = null;
3799 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003800 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 app.debugging = false;
3802
3803 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3804
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003805 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003806 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003808 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003809 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003810 }
3811
Joe Onorato8a9b2202010-02-26 18:56:32 -08003812 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 TAG, "New app record " + app
3814 + " thread=" + thread.asBinder() + " pid=" + pid);
3815 try {
3816 int testMode = IApplicationThread.DEBUG_OFF;
3817 if (mDebugApp != null && mDebugApp.equals(processName)) {
3818 testMode = mWaitForDebugger
3819 ? IApplicationThread.DEBUG_WAIT
3820 : IApplicationThread.DEBUG_ON;
3821 app.debugging = true;
3822 if (mDebugTransient) {
3823 mDebugApp = mOrigDebugApp;
3824 mWaitForDebugger = mOrigWaitForDebugger;
3825 }
3826 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003827 String profileFile = app.instrumentationProfileFile;
3828 ParcelFileDescriptor profileFd = null;
3829 boolean profileAutoStop = false;
3830 if (mProfileApp != null && mProfileApp.equals(processName)) {
3831 mProfileProc = app;
3832 profileFile = mProfileFile;
3833 profileFd = mProfileFd;
3834 profileAutoStop = mAutoStopProfiler;
3835 }
3836
Christopher Tate181fafa2009-05-14 11:12:14 -07003837 // If the app is being launched for restore or full backup, set it up specially
3838 boolean isRestrictedBackupMode = false;
3839 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3840 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003841 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003842 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3843 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003844
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003845 ensurePackageDexOpt(app.instrumentationInfo != null
3846 ? app.instrumentationInfo.packageName
3847 : app.info.packageName);
3848 if (app.instrumentationClass != null) {
3849 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003850 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003851 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003852 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003853 ApplicationInfo appInfo = app.instrumentationInfo != null
3854 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003855 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003856 if (profileFd != null) {
3857 profileFd = profileFd.dup();
3858 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003859 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003860 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003862 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003863 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003864 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003865 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003866 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 } catch (Exception e) {
3868 // todo: Yikes! What should we do? For now we will try to
3869 // start another process, but that could easily get us in
3870 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003871 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872
3873 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003874 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 startProcessLocked(app, "bind fail", processName);
3876 return false;
3877 }
3878
3879 // Remove this record from the list of starting applications.
3880 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003881 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3882 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 mProcessesOnHold.remove(app);
3884
3885 boolean badApp = false;
3886 boolean didSomething = false;
3887
3888 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003889 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003890 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003891 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 && processName.equals(hr.processName)) {
3893 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003894 if (mHeadless) {
3895 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3896 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 didSomething = true;
3898 }
3899 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003900 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 + hr.intent.getComponent().flattenToShortString(), e);
3902 badApp = true;
3903 }
3904 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003905 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 }
3907 }
3908
3909 // Find any services that should be running in this process...
3910 if (!badApp && mPendingServices.size() > 0) {
3911 ServiceRecord sr = null;
3912 try {
3913 for (int i=0; i<mPendingServices.size(); i++) {
3914 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003915 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
3916 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 continue;
3918 }
3919
3920 mPendingServices.remove(i);
3921 i--;
3922 realStartServiceLocked(sr, app);
3923 didSomething = true;
3924 }
3925 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003926 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 + sr.shortName, e);
3928 badApp = true;
3929 }
3930 }
3931
Christopher Tatef46723b2012-01-26 14:19:24 -08003932 // Check if a next-broadcast receiver is in this process...
3933 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08003935 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08003937 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 }
3940 }
3941
Christopher Tate181fafa2009-05-14 11:12:14 -07003942 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003943 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003944 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003945 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003946 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003947 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
3948 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
3949 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07003950 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003951 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003952 e.printStackTrace();
3953 }
3954 }
3955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 if (badApp) {
3957 // todo: Also need to kill application to deal with all
3958 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003959 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 return false;
3961 }
3962
3963 if (!didSomething) {
3964 updateOomAdjLocked();
3965 }
3966
3967 return true;
3968 }
3969
3970 public final void attachApplication(IApplicationThread thread) {
3971 synchronized (this) {
3972 int callingPid = Binder.getCallingPid();
3973 final long origId = Binder.clearCallingIdentity();
3974 attachApplicationLocked(thread, callingPid);
3975 Binder.restoreCallingIdentity(origId);
3976 }
3977 }
3978
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003979 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003981 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
3982 if (stopProfiling) {
3983 synchronized (this) {
3984 if (mProfileProc == r.app) {
3985 if (mProfileFd != null) {
3986 try {
3987 mProfileFd.close();
3988 } catch (IOException e) {
3989 }
3990 clearProfilerLocked();
3991 }
3992 }
3993 }
3994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 Binder.restoreCallingIdentity(origId);
3996 }
3997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003999 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004000 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 mWindowManager.enableScreenAfterBoot();
4002 }
4003
Dianne Hackborn661cd522011-08-22 00:26:20 -07004004 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004005 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004006 mWindowManager.showBootMessage(msg, always);
4007 }
4008
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004009 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004010 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004011 synchronized (this) {
4012 mMainStack.dismissKeyguardOnNextActivityLocked();
4013 }
4014 }
4015
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004016 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004017 IntentFilter pkgFilter = new IntentFilter();
4018 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4019 pkgFilter.addDataScheme("package");
4020 mContext.registerReceiver(new BroadcastReceiver() {
4021 @Override
4022 public void onReceive(Context context, Intent intent) {
4023 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4024 if (pkgs != null) {
4025 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004026 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004027 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004028 setResultCode(Activity.RESULT_OK);
4029 return;
4030 }
4031 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004032 }
4033 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004034 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004035 }, pkgFilter);
4036
4037 synchronized (this) {
4038 // Ensure that any processes we had put on hold are now started
4039 // up.
4040 final int NP = mProcessesOnHold.size();
4041 if (NP > 0) {
4042 ArrayList<ProcessRecord> procs =
4043 new ArrayList<ProcessRecord>(mProcessesOnHold);
4044 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004045 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4046 + procs.get(ip));
4047 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004048 }
4049 }
4050
4051 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004052 // Start looking for apps that are abusing wake locks.
4053 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004054 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004055 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004056 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004057 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004058 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004059 broadcastIntentLocked(null, null,
4060 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4061 null, null, 0, null, null,
4062 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004063 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004064 }
4065 }
4066 }
4067
4068 final void ensureBootCompleted() {
4069 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004070 boolean enableScreen;
4071 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004072 booting = mBooting;
4073 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004074 enableScreen = !mBooted;
4075 mBooted = true;
4076 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004077
4078 if (booting) {
4079 finishBooting();
4080 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004081
4082 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004083 enableScreenAfterBoot();
4084 }
4085 }
4086
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004087 public final void activityPaused(IBinder token) {
4088 final long origId = Binder.clearCallingIdentity();
4089 mMainStack.activityPaused(token, false);
4090 Binder.restoreCallingIdentity(origId);
4091 }
4092
4093 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4094 CharSequence description) {
4095 if (localLOGV) Slog.v(
4096 TAG, "Activity stopped: token=" + token);
4097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 // Refuse possible leaked file descriptors
4099 if (icicle != null && icicle.hasFileDescriptors()) {
4100 throw new IllegalArgumentException("File descriptors passed in Bundle");
4101 }
4102
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004103 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104
4105 final long origId = Binder.clearCallingIdentity();
4106
4107 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004108 r = mMainStack.isInStackLocked(token);
4109 if (r != null) {
4110 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 }
4112 }
4113
4114 if (r != null) {
4115 sendPendingThumbnail(r, null, null, null, false);
4116 }
4117
4118 trimApplications();
4119
4120 Binder.restoreCallingIdentity(origId);
4121 }
4122
4123 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004124 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004125 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 }
4127
4128 public String getCallingPackage(IBinder token) {
4129 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004130 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004131 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 }
4133 }
4134
4135 public ComponentName getCallingActivity(IBinder token) {
4136 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004137 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 return r != null ? r.intent.getComponent() : null;
4139 }
4140 }
4141
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004142 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004143 ActivityRecord r = mMainStack.isInStackLocked(token);
4144 if (r == null) {
4145 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004147 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 }
4149
4150 public ComponentName getActivityClassForToken(IBinder token) {
4151 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004152 ActivityRecord r = mMainStack.isInStackLocked(token);
4153 if (r == null) {
4154 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004156 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 }
4158 }
4159
4160 public String getPackageForToken(IBinder token) {
4161 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004162 ActivityRecord r = mMainStack.isInStackLocked(token);
4163 if (r == null) {
4164 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004166 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 }
4168 }
4169
4170 public IIntentSender getIntentSender(int type,
4171 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004172 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004173 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004175 if (intents != null) {
4176 if (intents.length < 1) {
4177 throw new IllegalArgumentException("Intents array length must be >= 1");
4178 }
4179 for (int i=0; i<intents.length; i++) {
4180 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004181 if (intent != null) {
4182 if (intent.hasFileDescriptors()) {
4183 throw new IllegalArgumentException("File descriptors passed in Intent");
4184 }
4185 if (type == INTENT_SENDER_BROADCAST &&
4186 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4187 throw new IllegalArgumentException(
4188 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4189 }
4190 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004191 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004192 }
4193 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004194 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004195 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004196 }
4197 }
4198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 synchronized(this) {
4200 int callingUid = Binder.getCallingUid();
4201 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004202 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004203 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004205 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 String msg = "Permission Denial: getIntentSender() from pid="
4207 + Binder.getCallingPid()
4208 + ", uid=" + Binder.getCallingUid()
4209 + ", (need uid=" + uid + ")"
4210 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004211 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 throw new SecurityException(msg);
4213 }
4214 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004215
Amith Yamasani742a6712011-05-04 14:49:28 -07004216 if (DEBUG_MU)
4217 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4218 + Binder.getOrigCallingUid());
4219 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004220 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004222 } catch (RemoteException e) {
4223 throw new SecurityException(e);
4224 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004225 }
4226 }
4227
4228 IIntentSender getIntentSenderLocked(int type,
4229 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004230 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004231 if (DEBUG_MU)
4232 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004233 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004234 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004235 activity = mMainStack.isInStackLocked(token);
4236 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004237 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004239 if (activity.finishing) {
4240 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004242 }
4243
4244 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4245 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4246 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4247 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4248 |PendingIntent.FLAG_UPDATE_CURRENT);
4249
4250 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4251 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004252 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004253 WeakReference<PendingIntentRecord> ref;
4254 ref = mIntentSenderRecords.get(key);
4255 PendingIntentRecord rec = ref != null ? ref.get() : null;
4256 if (rec != null) {
4257 if (!cancelCurrent) {
4258 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004259 if (rec.key.requestIntent != null) {
4260 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4261 }
4262 if (intents != null) {
4263 intents[intents.length-1] = rec.key.requestIntent;
4264 rec.key.allIntents = intents;
4265 rec.key.allResolvedTypes = resolvedTypes;
4266 } else {
4267 rec.key.allIntents = null;
4268 rec.key.allResolvedTypes = null;
4269 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 return rec;
4272 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004273 rec.canceled = true;
4274 mIntentSenderRecords.remove(key);
4275 }
4276 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 return rec;
4278 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004279 rec = new PendingIntentRecord(this, key, callingUid);
4280 mIntentSenderRecords.put(key, rec.ref);
4281 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
4282 if (activity.pendingResults == null) {
4283 activity.pendingResults
4284 = new HashSet<WeakReference<PendingIntentRecord>>();
4285 }
4286 activity.pendingResults.add(rec.ref);
4287 }
4288 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 }
4290
4291 public void cancelIntentSender(IIntentSender sender) {
4292 if (!(sender instanceof PendingIntentRecord)) {
4293 return;
4294 }
4295 synchronized(this) {
4296 PendingIntentRecord rec = (PendingIntentRecord)sender;
4297 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004298 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 .getPackageUid(rec.key.packageName);
4300 if (uid != Binder.getCallingUid()) {
4301 String msg = "Permission Denial: cancelIntentSender() from pid="
4302 + Binder.getCallingPid()
4303 + ", uid=" + Binder.getCallingUid()
4304 + " is not allowed to cancel packges "
4305 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004306 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 throw new SecurityException(msg);
4308 }
4309 } catch (RemoteException e) {
4310 throw new SecurityException(e);
4311 }
4312 cancelIntentSenderLocked(rec, true);
4313 }
4314 }
4315
4316 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4317 rec.canceled = true;
4318 mIntentSenderRecords.remove(rec.key);
4319 if (cleanActivity && rec.key.activity != null) {
4320 rec.key.activity.pendingResults.remove(rec.ref);
4321 }
4322 }
4323
4324 public String getPackageForIntentSender(IIntentSender pendingResult) {
4325 if (!(pendingResult instanceof PendingIntentRecord)) {
4326 return null;
4327 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004328 try {
4329 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4330 return res.key.packageName;
4331 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 }
4333 return null;
4334 }
4335
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004336 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4337 if (!(pendingResult instanceof PendingIntentRecord)) {
4338 return false;
4339 }
4340 try {
4341 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4342 if (res.key.allIntents == null) {
4343 return false;
4344 }
4345 for (int i=0; i<res.key.allIntents.length; i++) {
4346 Intent intent = res.key.allIntents[i];
4347 if (intent.getPackage() != null && intent.getComponent() != null) {
4348 return false;
4349 }
4350 }
4351 return true;
4352 } catch (ClassCastException e) {
4353 }
4354 return false;
4355 }
4356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 public void setProcessLimit(int max) {
4358 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4359 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004360 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004361 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004362 mProcessLimitOverride = max;
4363 }
4364 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 }
4366
4367 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004368 synchronized (this) {
4369 return mProcessLimitOverride;
4370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 }
4372
4373 void foregroundTokenDied(ForegroundToken token) {
4374 synchronized (ActivityManagerService.this) {
4375 synchronized (mPidsSelfLocked) {
4376 ForegroundToken cur
4377 = mForegroundProcesses.get(token.pid);
4378 if (cur != token) {
4379 return;
4380 }
4381 mForegroundProcesses.remove(token.pid);
4382 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4383 if (pr == null) {
4384 return;
4385 }
4386 pr.forcingToForeground = null;
4387 pr.foregroundServices = false;
4388 }
4389 updateOomAdjLocked();
4390 }
4391 }
4392
4393 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4394 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4395 "setProcessForeground()");
4396 synchronized(this) {
4397 boolean changed = false;
4398
4399 synchronized (mPidsSelfLocked) {
4400 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004401 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004402 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 return;
4404 }
4405 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4406 if (oldToken != null) {
4407 oldToken.token.unlinkToDeath(oldToken, 0);
4408 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004409 if (pr != null) {
4410 pr.forcingToForeground = null;
4411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412 changed = true;
4413 }
4414 if (isForeground && token != null) {
4415 ForegroundToken newToken = new ForegroundToken() {
4416 public void binderDied() {
4417 foregroundTokenDied(this);
4418 }
4419 };
4420 newToken.pid = pid;
4421 newToken.token = token;
4422 try {
4423 token.linkToDeath(newToken, 0);
4424 mForegroundProcesses.put(pid, newToken);
4425 pr.forcingToForeground = token;
4426 changed = true;
4427 } catch (RemoteException e) {
4428 // If the process died while doing this, we will later
4429 // do the cleanup with the process death link.
4430 }
4431 }
4432 }
4433
4434 if (changed) {
4435 updateOomAdjLocked();
4436 }
4437 }
4438 }
4439
4440 // =========================================================
4441 // PERMISSIONS
4442 // =========================================================
4443
4444 static class PermissionController extends IPermissionController.Stub {
4445 ActivityManagerService mActivityManagerService;
4446 PermissionController(ActivityManagerService activityManagerService) {
4447 mActivityManagerService = activityManagerService;
4448 }
4449
4450 public boolean checkPermission(String permission, int pid, int uid) {
4451 return mActivityManagerService.checkPermission(permission, pid,
4452 uid) == PackageManager.PERMISSION_GRANTED;
4453 }
4454 }
4455
4456 /**
4457 * This can be called with or without the global lock held.
4458 */
4459 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004460 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 // We might be performing an operation on behalf of an indirect binder
4462 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4463 // client identity accordingly before proceeding.
4464 Identity tlsIdentity = sCallerIdentity.get();
4465 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004466 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004467 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4468 uid = tlsIdentity.uid;
4469 pid = tlsIdentity.pid;
4470 }
4471
4472 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004473 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 return PackageManager.PERMISSION_GRANTED;
4475 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004476 // Isolated processes don't get any permissions.
4477 if (UserId.isIsolated(uid)) {
4478 return PackageManager.PERMISSION_DENIED;
4479 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004480 // If there is a uid that owns whatever is being accessed, it has
4481 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004482 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004483 return PackageManager.PERMISSION_GRANTED;
4484 }
4485 // If the target is not exported, then nobody else can get to it.
4486 if (!exported) {
4487 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 return PackageManager.PERMISSION_DENIED;
4489 }
4490 if (permission == null) {
4491 return PackageManager.PERMISSION_GRANTED;
4492 }
4493 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004494 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 .checkUidPermission(permission, uid);
4496 } catch (RemoteException e) {
4497 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004498 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 }
4500 return PackageManager.PERMISSION_DENIED;
4501 }
4502
4503 /**
4504 * As the only public entry point for permissions checking, this method
4505 * can enforce the semantic that requesting a check on a null global
4506 * permission is automatically denied. (Internally a null permission
4507 * string is used when calling {@link #checkComponentPermission} in cases
4508 * when only uid-based security is needed.)
4509 *
4510 * This can be called with or without the global lock held.
4511 */
4512 public int checkPermission(String permission, int pid, int uid) {
4513 if (permission == null) {
4514 return PackageManager.PERMISSION_DENIED;
4515 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004516 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 }
4518
4519 /**
4520 * Binder IPC calls go through the public entry point.
4521 * This can be called with or without the global lock held.
4522 */
4523 int checkCallingPermission(String permission) {
4524 return checkPermission(permission,
4525 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004526 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 }
4528
4529 /**
4530 * This can be called with or without the global lock held.
4531 */
4532 void enforceCallingPermission(String permission, String func) {
4533 if (checkCallingPermission(permission)
4534 == PackageManager.PERMISSION_GRANTED) {
4535 return;
4536 }
4537
4538 String msg = "Permission Denial: " + func + " from pid="
4539 + Binder.getCallingPid()
4540 + ", uid=" + Binder.getCallingUid()
4541 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004542 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 throw new SecurityException(msg);
4544 }
4545
4546 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07004547 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
4548 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4549 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
4550 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4551 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004553 // Is the component private from the target uid?
4554 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
4555
4556 // Acceptable if the there is no read permission needed from the
4557 // target or the target is holding the read permission.
4558 if (!readPerm) {
4559 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004561 == PackageManager.PERMISSION_GRANTED)) {
4562 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563 }
4564 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004565
4566 // Acceptable if the there is no write permission needed from the
4567 // target or the target is holding the read permission.
4568 if (!writePerm) {
4569 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004571 == PackageManager.PERMISSION_GRANTED)) {
4572 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004573 }
4574 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004575
4576 // Acceptable if there is a path permission matching the URI that
4577 // the target holds the permission on.
4578 PathPermission[] pps = pi.pathPermissions;
4579 if (pps != null && (!readPerm || !writePerm)) {
4580 final String path = uri.getPath();
4581 int i = pps.length;
4582 while (i > 0 && (!readPerm || !writePerm)) {
4583 i--;
4584 PathPermission pp = pps[i];
4585 if (!readPerm) {
4586 final String pprperm = pp.getReadPermission();
4587 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4588 + pprperm + " for " + pp.getPath()
4589 + ": match=" + pp.match(path)
4590 + " check=" + pm.checkUidPermission(pprperm, uid));
4591 if (pprperm != null && pp.match(path) &&
4592 (pm.checkUidPermission(pprperm, uid)
4593 == PackageManager.PERMISSION_GRANTED)) {
4594 readPerm = true;
4595 }
4596 }
4597 if (!writePerm) {
4598 final String ppwperm = pp.getWritePermission();
4599 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4600 + ppwperm + " for " + pp.getPath()
4601 + ": match=" + pp.match(path)
4602 + " check=" + pm.checkUidPermission(ppwperm, uid));
4603 if (ppwperm != null && pp.match(path) &&
4604 (pm.checkUidPermission(ppwperm, uid)
4605 == PackageManager.PERMISSION_GRANTED)) {
4606 writePerm = true;
4607 }
4608 }
4609 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611 } catch (RemoteException e) {
4612 return false;
4613 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004614
4615 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 }
4617
4618 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4619 int modeFlags) {
4620 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004621 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 return true;
4623 }
4624 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4625 if (perms == null) return false;
4626 UriPermission perm = perms.get(uri);
4627 if (perm == null) return false;
4628 return (modeFlags&perm.modeFlags) == modeFlags;
4629 }
4630
4631 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004632 enforceNotIsolatedCaller("checkUriPermission");
4633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 // Another redirected-binder-call permissions check as in
4635 // {@link checkComponentPermission}.
4636 Identity tlsIdentity = sCallerIdentity.get();
4637 if (tlsIdentity != null) {
4638 uid = tlsIdentity.uid;
4639 pid = tlsIdentity.pid;
4640 }
4641
Amith Yamasani742a6712011-05-04 14:49:28 -07004642 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004643 // Our own process gets to do everything.
4644 if (pid == MY_PID) {
4645 return PackageManager.PERMISSION_GRANTED;
4646 }
4647 synchronized(this) {
4648 return checkUriPermissionLocked(uri, uid, modeFlags)
4649 ? PackageManager.PERMISSION_GRANTED
4650 : PackageManager.PERMISSION_DENIED;
4651 }
4652 }
4653
Dianne Hackborn39792d22010-08-19 18:01:52 -07004654 /**
4655 * Check if the targetPkg can be granted permission to access uri by
4656 * the callingUid using the given modeFlags. Throws a security exception
4657 * if callingUid is not allowed to do this. Returns the uid of the target
4658 * if the URI permission grant should be performed; returns -1 if it is not
4659 * needed (for example targetPkg already has permission to access the URI).
4660 */
4661 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
4662 Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004663 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4664 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4665 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004666 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004667 }
4668
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004669 if (targetPkg != null) {
4670 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4671 "Checking grant " + targetPkg + " permission to " + uri);
4672 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004673
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004674 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675
4676 // If this is not a content: uri, we can't do anything with it.
4677 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004678 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004679 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004680 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004681 }
4682
4683 String name = uri.getAuthority();
4684 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004685 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4686 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 if (cpr != null) {
4688 pi = cpr.info;
4689 } else {
4690 try {
4691 pi = pm.resolveContentProvider(name,
4692 PackageManager.GET_URI_PERMISSION_PATTERNS);
4693 } catch (RemoteException ex) {
4694 }
4695 }
4696 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004697 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004698 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004699 }
4700
4701 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004702 if (targetPkg != null) {
4703 try {
4704 targetUid = pm.getPackageUid(targetPkg);
4705 if (targetUid < 0) {
4706 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4707 "Can't grant URI permission no uid for: " + targetPkg);
4708 return -1;
4709 }
4710 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004711 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004712 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004713 } else {
4714 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 }
4716
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004717 if (targetUid >= 0) {
4718 // First... does the target actually need this permission?
4719 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4720 // No need to grant the target this permission.
4721 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4722 "Target " + targetPkg + " already has full permission to " + uri);
4723 return -1;
4724 }
4725 } else {
4726 // First... there is no target package, so can anyone access it?
4727 boolean allowed = pi.exported;
4728 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4729 if (pi.readPermission != null) {
4730 allowed = false;
4731 }
4732 }
4733 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4734 if (pi.writePermission != null) {
4735 allowed = false;
4736 }
4737 }
4738 if (allowed) {
4739 return -1;
4740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004741 }
4742
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004743 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004744 if (!pi.grantUriPermissions) {
4745 throw new SecurityException("Provider " + pi.packageName
4746 + "/" + pi.name
4747 + " does not allow granting of Uri permissions (uri "
4748 + uri + ")");
4749 }
4750 if (pi.uriPermissionPatterns != null) {
4751 final int N = pi.uriPermissionPatterns.length;
4752 boolean allowed = false;
4753 for (int i=0; i<N; i++) {
4754 if (pi.uriPermissionPatterns[i] != null
4755 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4756 allowed = true;
4757 break;
4758 }
4759 }
4760 if (!allowed) {
4761 throw new SecurityException("Provider " + pi.packageName
4762 + "/" + pi.name
4763 + " does not allow granting of permission to path of Uri "
4764 + uri);
4765 }
4766 }
4767
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004768 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004770 if (callingUid != Process.myUid()) {
4771 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4772 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4773 throw new SecurityException("Uid " + callingUid
4774 + " does not have permission to uri " + uri);
4775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 }
4777 }
4778
Dianne Hackborn39792d22010-08-19 18:01:52 -07004779 return targetUid;
4780 }
4781
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004782 public int checkGrantUriPermission(int callingUid, String targetPkg,
4783 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004784 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004785 synchronized(this) {
4786 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4787 }
4788 }
4789
Dianne Hackborn39792d22010-08-19 18:01:52 -07004790 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4791 Uri uri, int modeFlags, UriPermissionOwner owner) {
4792 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4793 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4794 if (modeFlags == 0) {
4795 return;
4796 }
4797
4798 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004799 // to the uri, and the target doesn't. Let's now give this to
4800 // the target.
4801
Joe Onorato8a9b2202010-02-26 18:56:32 -08004802 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004803 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004805 HashMap<Uri, UriPermission> targetUris
4806 = mGrantedUriPermissions.get(targetUid);
4807 if (targetUris == null) {
4808 targetUris = new HashMap<Uri, UriPermission>();
4809 mGrantedUriPermissions.put(targetUid, targetUris);
4810 }
4811
4812 UriPermission perm = targetUris.get(uri);
4813 if (perm == null) {
4814 perm = new UriPermission(targetUid, uri);
4815 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004816 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004819 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004820 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004821 } else {
4822 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4823 perm.readOwners.add(owner);
4824 owner.addReadPermission(perm);
4825 }
4826 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4827 perm.writeOwners.add(owner);
4828 owner.addWritePermission(perm);
4829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004830 }
4831 }
4832
Dianne Hackborn39792d22010-08-19 18:01:52 -07004833 void grantUriPermissionLocked(int callingUid,
4834 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004835 if (targetPkg == null) {
4836 throw new NullPointerException("targetPkg");
4837 }
4838
Dianne Hackborn39792d22010-08-19 18:01:52 -07004839 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4840 if (targetUid < 0) {
4841 return;
4842 }
4843
4844 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4845 }
4846
4847 /**
4848 * Like checkGrantUriPermissionLocked, but takes an Intent.
4849 */
4850 int checkGrantUriPermissionFromIntentLocked(int callingUid,
4851 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004852 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004853 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004854 + " from " + intent + "; flags=0x"
4855 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4856
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004857 if (targetPkg == null) {
4858 throw new NullPointerException("targetPkg");
4859 }
4860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004861 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004862 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004863 }
4864 Uri data = intent.getData();
4865 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004866 return -1;
4867 }
4868 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4869 intent.getFlags());
4870 }
4871
4872 /**
4873 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4874 */
4875 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
4876 String targetPkg, Intent intent, UriPermissionOwner owner) {
4877 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
4878 intent.getFlags(), owner);
4879 }
4880
4881 void grantUriPermissionFromIntentLocked(int callingUid,
4882 String targetPkg, Intent intent, UriPermissionOwner owner) {
4883 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
4884 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004885 return;
4886 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004887
4888 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004889 }
4890
4891 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4892 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004893 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004894 synchronized(this) {
4895 final ProcessRecord r = getRecordForAppLocked(caller);
4896 if (r == null) {
4897 throw new SecurityException("Unable to find app for caller "
4898 + caller
4899 + " when granting permission to uri " + uri);
4900 }
4901 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004902 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004903 }
4904 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004905 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004906 }
4907
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004908 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004909 null);
4910 }
4911 }
4912
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004913 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004914 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4915 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4916 HashMap<Uri, UriPermission> perms
4917 = mGrantedUriPermissions.get(perm.uid);
4918 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004919 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004920 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004921 perms.remove(perm.uri);
4922 if (perms.size() == 0) {
4923 mGrantedUriPermissions.remove(perm.uid);
4924 }
4925 }
4926 }
4927 }
4928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004929 private void revokeUriPermissionLocked(int callingUid, Uri uri,
4930 int modeFlags) {
4931 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4932 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4933 if (modeFlags == 0) {
4934 return;
4935 }
4936
Joe Onorato8a9b2202010-02-26 18:56:32 -08004937 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004938 "Revoking all granted permissions to " + uri);
4939
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004940 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941
4942 final String authority = uri.getAuthority();
4943 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004944 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
4945 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004946 if (cpr != null) {
4947 pi = cpr.info;
4948 } else {
4949 try {
4950 pi = pm.resolveContentProvider(authority,
4951 PackageManager.GET_URI_PERMISSION_PATTERNS);
4952 } catch (RemoteException ex) {
4953 }
4954 }
4955 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004956 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 return;
4958 }
4959
4960 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07004961 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004962 // Right now, if you are not the original owner of the permission,
4963 // you are not allowed to revoke it.
4964 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4965 throw new SecurityException("Uid " + callingUid
4966 + " does not have permission to uri " + uri);
4967 //}
4968 }
4969
4970 // Go through all of the permissions and remove any that match.
4971 final List<String> SEGMENTS = uri.getPathSegments();
4972 if (SEGMENTS != null) {
4973 final int NS = SEGMENTS.size();
4974 int N = mGrantedUriPermissions.size();
4975 for (int i=0; i<N; i++) {
4976 HashMap<Uri, UriPermission> perms
4977 = mGrantedUriPermissions.valueAt(i);
4978 Iterator<UriPermission> it = perms.values().iterator();
4979 toploop:
4980 while (it.hasNext()) {
4981 UriPermission perm = it.next();
4982 Uri targetUri = perm.uri;
4983 if (!authority.equals(targetUri.getAuthority())) {
4984 continue;
4985 }
4986 List<String> targetSegments = targetUri.getPathSegments();
4987 if (targetSegments == null) {
4988 continue;
4989 }
4990 if (targetSegments.size() < NS) {
4991 continue;
4992 }
4993 for (int j=0; j<NS; j++) {
4994 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
4995 continue toploop;
4996 }
4997 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004998 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004999 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 perm.clearModes(modeFlags);
5001 if (perm.modeFlags == 0) {
5002 it.remove();
5003 }
5004 }
5005 if (perms.size() == 0) {
5006 mGrantedUriPermissions.remove(
5007 mGrantedUriPermissions.keyAt(i));
5008 N--;
5009 i--;
5010 }
5011 }
5012 }
5013 }
5014
5015 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5016 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005017 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005018 synchronized(this) {
5019 final ProcessRecord r = getRecordForAppLocked(caller);
5020 if (r == null) {
5021 throw new SecurityException("Unable to find app for caller "
5022 + caller
5023 + " when revoking permission to uri " + uri);
5024 }
5025 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005026 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005027 return;
5028 }
5029
5030 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5031 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5032 if (modeFlags == 0) {
5033 return;
5034 }
5035
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005036 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005037
5038 final String authority = uri.getAuthority();
5039 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005040 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005041 if (cpr != null) {
5042 pi = cpr.info;
5043 } else {
5044 try {
5045 pi = pm.resolveContentProvider(authority,
5046 PackageManager.GET_URI_PERMISSION_PATTERNS);
5047 } catch (RemoteException ex) {
5048 }
5049 }
5050 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005051 Slog.w(TAG, "No content provider found for permission revoke: "
5052 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005053 return;
5054 }
5055
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005056 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057 }
5058 }
5059
Dianne Hackborn7e269642010-08-25 19:50:20 -07005060 @Override
5061 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005062 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005063 synchronized(this) {
5064 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5065 return owner.getExternalTokenLocked();
5066 }
5067 }
5068
5069 @Override
5070 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5071 Uri uri, int modeFlags) {
5072 synchronized(this) {
5073 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5074 if (owner == null) {
5075 throw new IllegalArgumentException("Unknown owner: " + token);
5076 }
5077 if (fromUid != Binder.getCallingUid()) {
5078 if (Binder.getCallingUid() != Process.myUid()) {
5079 // Only system code can grant URI permissions on behalf
5080 // of other users.
5081 throw new SecurityException("nice try");
5082 }
5083 }
5084 if (targetPkg == null) {
5085 throw new IllegalArgumentException("null target");
5086 }
5087 if (uri == null) {
5088 throw new IllegalArgumentException("null uri");
5089 }
5090
5091 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5092 }
5093 }
5094
5095 @Override
5096 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5097 synchronized(this) {
5098 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5099 if (owner == null) {
5100 throw new IllegalArgumentException("Unknown owner: " + token);
5101 }
5102
5103 if (uri == null) {
5104 owner.removeUriPermissionsLocked(mode);
5105 } else {
5106 owner.removeUriPermissionLocked(uri, mode);
5107 }
5108 }
5109 }
5110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5112 synchronized (this) {
5113 ProcessRecord app =
5114 who != null ? getRecordForAppLocked(who) : null;
5115 if (app == null) return;
5116
5117 Message msg = Message.obtain();
5118 msg.what = WAIT_FOR_DEBUGGER_MSG;
5119 msg.obj = app;
5120 msg.arg1 = waiting ? 1 : 0;
5121 mHandler.sendMessage(msg);
5122 }
5123 }
5124
5125 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005126 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5127 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005129 outInfo.threshold = homeAppMem;
5130 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5131 outInfo.hiddenAppThreshold = hiddenAppMem;
5132 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005133 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005134 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5135 ProcessList.VISIBLE_APP_ADJ);
5136 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5137 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005138 }
5139
5140 // =========================================================
5141 // TASK MANAGEMENT
5142 // =========================================================
5143
5144 public List getTasks(int maxNum, int flags,
5145 IThumbnailReceiver receiver) {
5146 ArrayList list = new ArrayList();
5147
5148 PendingThumbnailsRecord pending = null;
5149 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005150 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005151
5152 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005153 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005154 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5155 + ", receiver=" + receiver);
5156
5157 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5158 != PackageManager.PERMISSION_GRANTED) {
5159 if (receiver != null) {
5160 // If the caller wants to wait for pending thumbnails,
5161 // it ain't gonna get them.
5162 try {
5163 receiver.finished();
5164 } catch (RemoteException ex) {
5165 }
5166 }
5167 String msg = "Permission Denial: getTasks() from pid="
5168 + Binder.getCallingPid()
5169 + ", uid=" + Binder.getCallingUid()
5170 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005171 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005172 throw new SecurityException(msg);
5173 }
5174
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005175 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005176 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005177 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005178 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 TaskRecord curTask = null;
5180 int numActivities = 0;
5181 int numRunning = 0;
5182 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005183 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005184 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005185 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186
5187 // Initialize state for next task if needed.
5188 if (top == null ||
5189 (top.state == ActivityState.INITIALIZING
5190 && top.task == r.task)) {
5191 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005192 curTask = r.task;
5193 numActivities = numRunning = 0;
5194 }
5195
5196 // Add 'r' into the current task.
5197 numActivities++;
5198 if (r.app != null && r.app.thread != null) {
5199 numRunning++;
5200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005201
Joe Onorato8a9b2202010-02-26 18:56:32 -08005202 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 TAG, r.intent.getComponent().flattenToShortString()
5204 + ": task=" + r.task);
5205
5206 // If the next one is a different task, generate a new
5207 // TaskInfo entry for what we have.
5208 if (next == null || next.task != curTask) {
5209 ActivityManager.RunningTaskInfo ci
5210 = new ActivityManager.RunningTaskInfo();
5211 ci.id = curTask.taskId;
5212 ci.baseActivity = r.intent.getComponent();
5213 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005214 if (top.thumbHolder != null) {
5215 ci.description = top.thumbHolder.lastDescription;
5216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217 ci.numActivities = numActivities;
5218 ci.numRunning = numRunning;
5219 //System.out.println(
5220 // "#" + maxNum + ": " + " descr=" + ci.description);
5221 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005222 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 TAG, "State=" + top.state + "Idle=" + top.idle
5224 + " app=" + top.app
5225 + " thr=" + (top.app != null ? top.app.thread : null));
5226 if (top.state == ActivityState.RESUMED
5227 || top.state == ActivityState.PAUSING) {
5228 if (top.idle && top.app != null
5229 && top.app.thread != null) {
5230 topRecord = top;
5231 topThumbnail = top.app.thread;
5232 } else {
5233 top.thumbnailNeeded = true;
5234 }
5235 }
5236 if (pending == null) {
5237 pending = new PendingThumbnailsRecord(receiver);
5238 }
5239 pending.pendingRecords.add(top);
5240 }
5241 list.add(ci);
5242 maxNum--;
5243 top = null;
5244 }
5245 }
5246
5247 if (pending != null) {
5248 mPendingThumbnails.add(pending);
5249 }
5250 }
5251
Joe Onorato8a9b2202010-02-26 18:56:32 -08005252 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005253
5254 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005255 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005257 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005258 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005259 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005260 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005261 }
5262 }
5263
5264 if (pending == null && receiver != null) {
5265 // In this case all thumbnails were available and the client
5266 // is being asked to be told when the remaining ones come in...
5267 // which is unusually, since the top-most currently running
5268 // activity should never have a canned thumbnail! Oh well.
5269 try {
5270 receiver.finished();
5271 } catch (RemoteException ex) {
5272 }
5273 }
5274
5275 return list;
5276 }
5277
5278 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5279 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005280 final int callingUid = Binder.getCallingUid();
5281 // If it's the system uid asking, then use the current user id.
5282 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5283 // require the entire list.
5284 final int callingUserId = callingUid == Process.SYSTEM_UID
5285 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005286 synchronized (this) {
5287 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5288 "getRecentTasks()");
5289
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005290 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005292 final int N = mRecentTasks.size();
5293 ArrayList<ActivityManager.RecentTaskInfo> res
5294 = new ArrayList<ActivityManager.RecentTaskInfo>(
5295 maxNum < N ? maxNum : N);
5296 for (int i=0; i<N && maxNum > 0; i++) {
5297 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005298 // Only add calling user's recent tasks
5299 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005300 // Return the entry if desired by the caller. We always return
5301 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005302 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005303 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5304 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005305
Dianne Hackborn905577f2011-09-07 18:31:28 -07005306 if (i == 0
5307 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005308 || (tr.intent == null)
5309 || ((tr.intent.getFlags()
5310 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5311 ActivityManager.RecentTaskInfo rti
5312 = new ActivityManager.RecentTaskInfo();
5313 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005314 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005315 rti.baseIntent = new Intent(
5316 tr.intent != null ? tr.intent : tr.affinityIntent);
5317 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005318 rti.description = tr.lastDescription;
5319
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005320 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5321 // Check whether this activity is currently available.
5322 try {
5323 if (rti.origActivity != null) {
5324 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5325 continue;
5326 }
5327 } else if (rti.baseIntent != null) {
5328 if (pm.queryIntentActivities(rti.baseIntent,
5329 null, 0) == null) {
5330 continue;
5331 }
5332 }
5333 } catch (RemoteException e) {
5334 // Will never happen.
5335 }
5336 }
5337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005338 res.add(rti);
5339 maxNum--;
5340 }
5341 }
5342 return res;
5343 }
5344 }
5345
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005346 private TaskRecord taskForIdLocked(int id) {
5347 final int N = mRecentTasks.size();
5348 for (int i=0; i<N; i++) {
5349 TaskRecord tr = mRecentTasks.get(i);
5350 if (tr.taskId == id) {
5351 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005352 }
5353 }
5354 return null;
5355 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005356
5357 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5358 synchronized (this) {
5359 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5360 "getTaskThumbnails()");
5361 TaskRecord tr = taskForIdLocked(id);
5362 if (tr != null) {
5363 return mMainStack.getTaskThumbnailsLocked(tr);
5364 }
5365 }
5366 return null;
5367 }
5368
5369 public boolean removeSubTask(int taskId, int subTaskIndex) {
5370 synchronized (this) {
5371 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5372 "removeSubTask()");
5373 long ident = Binder.clearCallingIdentity();
5374 try {
5375 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
5376 } finally {
5377 Binder.restoreCallingIdentity(ident);
5378 }
5379 }
5380 }
5381
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005382 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005383 TaskRecord tr = root.task;
5384 Intent baseIntent = new Intent(
5385 tr.intent != null ? tr.intent : tr.affinityIntent);
5386 ComponentName component = baseIntent.getComponent();
5387 if (component == null) {
5388 Slog.w(TAG, "Now component for base intent of task: " + tr);
5389 return;
5390 }
5391
5392 // Find any running services associated with this app.
5393 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07005394 for (ServiceRecord sr : mServiceMap.getAllServices(root.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005395 if (sr.packageName.equals(component.getPackageName())) {
5396 services.add(sr);
5397 }
5398 }
5399
5400 // Take care of any running services associated with the app.
5401 for (int i=0; i<services.size(); i++) {
5402 ServiceRecord sr = services.get(i);
5403 if (sr.startRequested) {
5404 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005405 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005406 stopServiceLocked(sr);
5407 } else {
5408 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
5409 sr.makeNextStartId(), baseIntent, -1));
5410 if (sr.app != null && sr.app.thread != null) {
5411 sendServiceArgsLocked(sr, false);
5412 }
5413 }
5414 }
5415 }
5416
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005417 if (killProcesses) {
5418 // Find any running processes associated with this app.
5419 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5420 SparseArray<ProcessRecord> appProcs
5421 = mProcessNames.getMap().get(component.getPackageName());
5422 if (appProcs != null) {
5423 for (int i=0; i<appProcs.size(); i++) {
5424 procs.add(appProcs.valueAt(i));
5425 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005426 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005427
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005428 // Kill the running processes.
5429 for (int i=0; i<procs.size(); i++) {
5430 ProcessRecord pr = procs.get(i);
5431 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5432 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5433 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5434 pr.processName, pr.setAdj, "remove task");
5435 Process.killProcessQuiet(pr.pid);
5436 } else {
5437 pr.waitingToKill = "remove task";
5438 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005439 }
5440 }
5441 }
5442
5443 public boolean removeTask(int taskId, int flags) {
5444 synchronized (this) {
5445 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5446 "removeTask()");
5447 long ident = Binder.clearCallingIdentity();
5448 try {
5449 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
5450 if (r != null) {
5451 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005452 cleanUpRemovedTaskLocked(r,
5453 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005454 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005455 } else {
5456 TaskRecord tr = null;
5457 int i=0;
5458 while (i < mRecentTasks.size()) {
5459 TaskRecord t = mRecentTasks.get(i);
5460 if (t.taskId == taskId) {
5461 tr = t;
5462 break;
5463 }
5464 i++;
5465 }
5466 if (tr != null) {
5467 if (tr.numActivities <= 0) {
5468 // Caller is just removing a recent task that is
5469 // not actively running. That is easy!
5470 mRecentTasks.remove(i);
5471 } else {
5472 Slog.w(TAG, "removeTask: task " + taskId
5473 + " does not have activities to remove, "
5474 + " but numActivities=" + tr.numActivities
5475 + ": " + tr);
5476 }
5477 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005478 }
5479 } finally {
5480 Binder.restoreCallingIdentity(ident);
5481 }
5482 }
5483 return false;
5484 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5487 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005488 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 TaskRecord jt = startTask;
5490
5491 // First look backwards
5492 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005493 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005494 if (r.task != jt) {
5495 jt = r.task;
5496 if (affinity.equals(jt.affinity)) {
5497 return j;
5498 }
5499 }
5500 }
5501
5502 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005503 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 jt = startTask;
5505 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005506 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 if (r.task != jt) {
5508 if (affinity.equals(jt.affinity)) {
5509 return j;
5510 }
5511 jt = r.task;
5512 }
5513 }
5514
5515 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005516 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 return N-1;
5518 }
5519
5520 return -1;
5521 }
5522
5523 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005524 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005526 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5528 "moveTaskToFront()");
5529
5530 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005531 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5532 Binder.getCallingUid(), "Task to front")) {
5533 return;
5534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 final long origId = Binder.clearCallingIdentity();
5536 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005537 TaskRecord tr = taskForIdLocked(task);
5538 if (tr != null) {
5539 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5540 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005542 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5543 // Caller wants the home activity moved with it. To accomplish this,
5544 // we'll just move the home task to the top first.
5545 mMainStack.moveHomeToFrontLocked();
5546 }
5547 mMainStack.moveTaskToFrontLocked(tr, null);
5548 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005550 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5551 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005552 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005553 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5554 mMainStack.mUserLeaving = true;
5555 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005556 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5557 // Caller wants the home activity moved with it. To accomplish this,
5558 // we'll just move the home task to the top first.
5559 mMainStack.moveHomeToFrontLocked();
5560 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005561 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005562 return;
5563 }
5564 }
5565 } finally {
5566 Binder.restoreCallingIdentity(origId);
5567 }
5568 }
5569 }
5570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 public void moveTaskToBack(int task) {
5572 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5573 "moveTaskToBack()");
5574
5575 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005576 if (mMainStack.mResumedActivity != null
5577 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005578 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5579 Binder.getCallingUid(), "Task to back")) {
5580 return;
5581 }
5582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005584 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 Binder.restoreCallingIdentity(origId);
5586 }
5587 }
5588
5589 /**
5590 * Moves an activity, and all of the other activities within the same task, to the bottom
5591 * of the history stack. The activity's order within the task is unchanged.
5592 *
5593 * @param token A reference to the activity we wish to move
5594 * @param nonRoot If false then this only works if the activity is the root
5595 * of a task; if true it will work for any activity in a task.
5596 * @return Returns true if the move completed, false if not.
5597 */
5598 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005599 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005600 synchronized(this) {
5601 final long origId = Binder.clearCallingIdentity();
5602 int taskId = getTaskForActivityLocked(token, !nonRoot);
5603 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005604 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005605 }
5606 Binder.restoreCallingIdentity(origId);
5607 }
5608 return false;
5609 }
5610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 public void moveTaskBackwards(int task) {
5612 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5613 "moveTaskBackwards()");
5614
5615 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005616 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5617 Binder.getCallingUid(), "Task backwards")) {
5618 return;
5619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005620 final long origId = Binder.clearCallingIdentity();
5621 moveTaskBackwardsLocked(task);
5622 Binder.restoreCallingIdentity(origId);
5623 }
5624 }
5625
5626 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005627 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005628 }
5629
5630 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5631 synchronized(this) {
5632 return getTaskForActivityLocked(token, onlyRoot);
5633 }
5634 }
5635
5636 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005637 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638 TaskRecord lastTask = null;
5639 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005640 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005641 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 if (!onlyRoot || lastTask != r.task) {
5643 return r.task.taskId;
5644 }
5645 return -1;
5646 }
5647 lastTask = r.task;
5648 }
5649
5650 return -1;
5651 }
5652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 // =========================================================
5654 // THUMBNAILS
5655 // =========================================================
5656
5657 public void reportThumbnail(IBinder token,
5658 Bitmap thumbnail, CharSequence description) {
5659 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5660 final long origId = Binder.clearCallingIdentity();
5661 sendPendingThumbnail(null, token, thumbnail, description, true);
5662 Binder.restoreCallingIdentity(origId);
5663 }
5664
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005665 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 Bitmap thumbnail, CharSequence description, boolean always) {
5667 TaskRecord task = null;
5668 ArrayList receivers = null;
5669
5670 //System.out.println("Send pending thumbnail: " + r);
5671
5672 synchronized(this) {
5673 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005674 r = mMainStack.isInStackLocked(token);
5675 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676 return;
5677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005679 if (thumbnail == null && r.thumbHolder != null) {
5680 thumbnail = r.thumbHolder.lastThumbnail;
5681 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 }
5683 if (thumbnail == null && !always) {
5684 // If there is no thumbnail, and this entry is not actually
5685 // going away, then abort for now and pick up the next
5686 // thumbnail we get.
5687 return;
5688 }
5689 task = r.task;
5690
5691 int N = mPendingThumbnails.size();
5692 int i=0;
5693 while (i<N) {
5694 PendingThumbnailsRecord pr =
5695 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5696 //System.out.println("Looking in " + pr.pendingRecords);
5697 if (pr.pendingRecords.remove(r)) {
5698 if (receivers == null) {
5699 receivers = new ArrayList();
5700 }
5701 receivers.add(pr);
5702 if (pr.pendingRecords.size() == 0) {
5703 pr.finished = true;
5704 mPendingThumbnails.remove(i);
5705 N--;
5706 continue;
5707 }
5708 }
5709 i++;
5710 }
5711 }
5712
5713 if (receivers != null) {
5714 final int N = receivers.size();
5715 for (int i=0; i<N; i++) {
5716 try {
5717 PendingThumbnailsRecord pr =
5718 (PendingThumbnailsRecord)receivers.get(i);
5719 pr.receiver.newThumbnail(
5720 task != null ? task.taskId : -1, thumbnail, description);
5721 if (pr.finished) {
5722 pr.receiver.finished();
5723 }
5724 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005725 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 }
5727 }
5728 }
5729 }
5730
5731 // =========================================================
5732 // CONTENT PROVIDERS
5733 // =========================================================
5734
Jeff Brown10e89712011-07-08 18:52:57 -07005735 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5736 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005738 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005739 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005740 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005741 } catch (RemoteException ex) {
5742 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005743 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005744 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5745 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005746 if (providers != null) {
5747 final int N = providers.size();
5748 for (int i=0; i<N; i++) {
5749 ProviderInfo cpi =
5750 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005751
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005752 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005753 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005755 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005756 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005758 if (DEBUG_MU)
5759 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 app.pubProviders.put(cpi.name, cpr);
5761 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005762 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 }
5764 }
5765 return providers;
5766 }
5767
5768 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005769 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005771 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005773 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005774 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775 return null;
5776 }
5777 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005778 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 == PackageManager.PERMISSION_GRANTED) {
5780 return null;
5781 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005782
5783 PathPermission[] pps = cpi.pathPermissions;
5784 if (pps != null) {
5785 int i = pps.length;
5786 while (i > 0) {
5787 i--;
5788 PathPermission pp = pps[i];
5789 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005790 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005791 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005792 return null;
5793 }
5794 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005795 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005796 == PackageManager.PERMISSION_GRANTED) {
5797 return null;
5798 }
5799 }
5800 }
5801
Dianne Hackbornb424b632010-08-18 15:59:05 -07005802 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5803 if (perms != null) {
5804 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5805 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5806 return null;
5807 }
5808 }
5809 }
5810
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005811 String msg;
5812 if (!cpi.exported) {
5813 msg = "Permission Denial: opening provider " + cpi.name
5814 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5815 + ", uid=" + callingUid + ") that is not exported from uid "
5816 + cpi.applicationInfo.uid;
5817 } else {
5818 msg = "Permission Denial: opening provider " + cpi.name
5819 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5820 + ", uid=" + callingUid + ") requires "
5821 + cpi.readPermission + " or " + cpi.writePermission;
5822 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005823 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005824 return msg;
5825 }
5826
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005827 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5828 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005829 if (r != null) {
5830 Integer cnt = r.conProviders.get(cpr);
5831 if (DEBUG_PROVIDER) Slog.v(TAG,
5832 "Adding provider requested by "
5833 + r.processName + " from process "
5834 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5835 + " cnt=" + (cnt == null ? 1 : cnt));
5836 if (cnt == null) {
5837 cpr.clients.add(r);
5838 r.conProviders.put(cpr, new Integer(1));
5839 return true;
5840 } else {
5841 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5842 }
5843 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005844 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005845 }
5846 return false;
5847 }
5848
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005849 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5850 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005851 if (r != null) {
5852 Integer cnt = r.conProviders.get(cpr);
5853 if (DEBUG_PROVIDER) Slog.v(TAG,
5854 "Removing provider requested by "
5855 + r.processName + " from process "
5856 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5857 + " cnt=" + cnt);
5858 if (cnt == null || cnt.intValue() <= 1) {
5859 cpr.clients.remove(r);
5860 r.conProviders.remove(cpr);
5861 return true;
5862 } else {
5863 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
5864 }
5865 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005866 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005867 }
5868 return false;
5869 }
5870
Amith Yamasani742a6712011-05-04 14:49:28 -07005871 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005872 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 ContentProviderRecord cpr;
5874 ProviderInfo cpi = null;
5875
5876 synchronized(this) {
5877 ProcessRecord r = null;
5878 if (caller != null) {
5879 r = getRecordForAppLocked(caller);
5880 if (r == null) {
5881 throw new SecurityException(
5882 "Unable to find app for caller " + caller
5883 + " (pid=" + Binder.getCallingPid()
5884 + ") when getting content provider " + name);
5885 }
5886 }
5887
5888 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005889 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07005890 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005891 boolean providerRunning = cpr != null;
5892 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005894 String msg;
5895 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5896 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 }
5898
5899 if (r != null && cpr.canRunHere(r)) {
5900 // This provider has been published or is in the process
5901 // of being published... but it is also allowed to run
5902 // in the caller's process, so don't make a connection
5903 // and just let the caller instantiate its own instance.
5904 if (cpr.provider != null) {
5905 // don't give caller the provider object, it needs
5906 // to make its own.
5907 cpr = new ContentProviderRecord(cpr);
5908 }
5909 return cpr;
5910 }
5911
5912 final long origId = Binder.clearCallingIdentity();
5913
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005914 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005915 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005916 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005917 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005918 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005919 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005920 // make sure to count it as being accessed and thus
5921 // back up on the LRU list. This is good because
5922 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005923 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07005924 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07005925 }
5926
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005927 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005928 if (false) {
5929 if (cpr.name.flattenToShortString().equals(
5930 "com.android.providers.calendar/.CalendarProvider2")) {
5931 Slog.v(TAG, "****************** KILLING "
5932 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005933 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005934 }
5935 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005936 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005937 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
5938 // NOTE: there is still a race here where a signal could be
5939 // pending on the process even though we managed to update its
5940 // adj level. Not sure what to do about this, but at least
5941 // the race is now smaller.
5942 if (!success) {
5943 // Uh oh... it looks like the provider's process
5944 // has been killed on us. We need to wait for a new
5945 // process to be started, and make sure its death
5946 // doesn't kill our process.
5947 Slog.i(TAG,
5948 "Existing provider " + cpr.name.flattenToShortString()
5949 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005950 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005951 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005952 if (!lastRef) {
5953 // This wasn't the last ref our process had on
5954 // the provider... we have now been killed, bail.
5955 return null;
5956 }
5957 providerRunning = false;
5958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 }
5960
5961 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005964 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005965 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005966 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07005967 resolveContentProvider(name,
5968 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 } catch (RemoteException ex) {
5970 }
5971 if (cpi == null) {
5972 return null;
5973 }
5974
Amith Yamasani742a6712011-05-04 14:49:28 -07005975 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
5976 Binder.getOrigCallingUser());
5977
Dianne Hackbornb424b632010-08-18 15:59:05 -07005978 String msg;
5979 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5980 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 }
5982
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07005983 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005984 && !cpi.processName.equals("system")) {
5985 // If this content provider does not run in the system
5986 // process, and the system is not yet ready to run other
5987 // processes, then fail fast instead of hanging.
5988 throw new IllegalArgumentException(
5989 "Attempt to launch content provider before system ready");
5990 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005991
5992 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005993 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 final boolean firstClass = cpr == null;
5995 if (firstClass) {
5996 try {
5997 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005998 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 getApplicationInfo(
6000 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006001 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006003 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 + cpi.name);
6005 return null;
6006 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006007 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006008 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 } catch (RemoteException ex) {
6010 // pm is in same process, this will never happen.
6011 }
6012 }
6013
6014 if (r != null && cpr.canRunHere(r)) {
6015 // If this is a multiprocess provider, then just return its
6016 // info and allow the caller to instantiate it. Only do
6017 // this if the provider is the same user as the caller's
6018 // process, or can run as root (so can be in any process).
6019 return cpr;
6020 }
6021
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006022 if (DEBUG_PROVIDER) {
6023 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006024 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006025 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 }
6027
6028 // This is single process, and our app is now connecting to it.
6029 // See if we are already in the process of launching this
6030 // provider.
6031 final int N = mLaunchingProviders.size();
6032 int i;
6033 for (i=0; i<N; i++) {
6034 if (mLaunchingProviders.get(i) == cpr) {
6035 break;
6036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 }
6038
6039 // If the provider is not already being launched, then get it
6040 // started.
6041 if (i >= N) {
6042 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006043
6044 try {
6045 // Content provider is now in use, its package can't be stopped.
6046 try {
6047 AppGlobals.getPackageManager().setPackageStoppedState(
6048 cpr.appInfo.packageName, false);
6049 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006050 } catch (IllegalArgumentException e) {
6051 Slog.w(TAG, "Failed trying to unstop package "
6052 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006053 }
6054
6055 ProcessRecord proc = startProcessLocked(cpi.processName,
6056 cpr.appInfo, false, 0, "content provider",
6057 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006058 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006059 if (proc == null) {
6060 Slog.w(TAG, "Unable to launch app "
6061 + cpi.applicationInfo.packageName + "/"
6062 + cpi.applicationInfo.uid + " for provider "
6063 + name + ": process is bad");
6064 return null;
6065 }
6066 cpr.launchingApp = proc;
6067 mLaunchingProviders.add(cpr);
6068 } finally {
6069 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 }
6072
6073 // Make sure the provider is published (the same provider class
6074 // may be published under multiple names).
6075 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006076 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006078
Amith Yamasani742a6712011-05-04 14:49:28 -07006079 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006080 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 }
6082 }
6083
6084 // Wait for the provider to be published...
6085 synchronized (cpr) {
6086 while (cpr.provider == null) {
6087 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006088 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 + cpi.applicationInfo.packageName + "/"
6090 + cpi.applicationInfo.uid + " for provider "
6091 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006092 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 cpi.applicationInfo.packageName,
6094 cpi.applicationInfo.uid, name);
6095 return null;
6096 }
6097 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006098 if (DEBUG_MU) {
6099 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6100 + cpr.launchingApp);
6101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 cpr.wait();
6103 } catch (InterruptedException ex) {
6104 }
6105 }
6106 }
6107 return cpr;
6108 }
6109
6110 public final ContentProviderHolder getContentProvider(
6111 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006112 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 if (caller == null) {
6114 String msg = "null IApplicationThread when getting content provider "
6115 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006116 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 throw new SecurityException(msg);
6118 }
6119
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006120 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 }
6122
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006123 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6124 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6125 "Do not have permission in call getContentProviderExternal()");
6126 return getContentProviderExternalUnchecked(name, token);
6127 }
6128
6129 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6130 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 }
6132
6133 /**
6134 * Drop a content provider from a ProcessRecord's bookkeeping
6135 * @param cpr
6136 */
6137 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006138 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006140 int userId = UserId.getUserId(Binder.getCallingUid());
6141 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006143 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006144 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006145 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 return;
6147 }
6148 final ProcessRecord r = getRecordForAppLocked(caller);
6149 if (r == null) {
6150 throw new SecurityException(
6151 "Unable to find app for caller " + caller +
6152 " when removing content provider " + name);
6153 }
6154 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006155 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006156 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6157 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6158 + r.info.processName + " from process "
6159 + localCpr.appInfo.processName);
6160 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006162 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006163 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 return;
6165 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006166 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006167 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 }
6171 }
6172
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006173 public void removeContentProviderExternal(String name, IBinder token) {
6174 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6175 "Do not have permission in call removeContentProviderExternal()");
6176 removeContentProviderExternalUnchecked(name, token);
6177 }
6178
6179 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006180 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006181 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6182 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183 if(cpr == null) {
6184 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006185 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 return;
6187 }
6188
6189 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006190 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006191 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6192 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006193 if (localCpr.hasExternalProcessHandles()) {
6194 if (localCpr.removeExternalProcessHandleLocked(token)) {
6195 updateOomAdjLocked();
6196 } else {
6197 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6198 + " with no external reference for token: "
6199 + token + ".");
6200 }
6201 } else {
6202 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6203 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006205 }
6206 }
6207
6208 public final void publishContentProviders(IApplicationThread caller,
6209 List<ContentProviderHolder> providers) {
6210 if (providers == null) {
6211 return;
6212 }
6213
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006214 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 synchronized(this) {
6216 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006217 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006218 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006219 if (r == null) {
6220 throw new SecurityException(
6221 "Unable to find app for caller " + caller
6222 + " (pid=" + Binder.getCallingPid()
6223 + ") when publishing content providers");
6224 }
6225
6226 final long origId = Binder.clearCallingIdentity();
6227
6228 final int N = providers.size();
6229 for (int i=0; i<N; i++) {
6230 ContentProviderHolder src = providers.get(i);
6231 if (src == null || src.info == null || src.provider == null) {
6232 continue;
6233 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006234 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006235 if (DEBUG_MU)
6236 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006238 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006239 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006240 String names[] = dst.info.authority.split(";");
6241 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006242 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 }
6244
6245 int NL = mLaunchingProviders.size();
6246 int j;
6247 for (j=0; j<NL; j++) {
6248 if (mLaunchingProviders.get(j) == dst) {
6249 mLaunchingProviders.remove(j);
6250 j--;
6251 NL--;
6252 }
6253 }
6254 synchronized (dst) {
6255 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006256 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 dst.notifyAll();
6258 }
6259 updateOomAdjLocked(r);
6260 }
6261 }
6262
6263 Binder.restoreCallingIdentity(origId);
6264 }
6265 }
6266
6267 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006268 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006269 synchronized (mSelf) {
6270 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6271 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006272 if (providers != null) {
6273 for (int i=providers.size()-1; i>=0; i--) {
6274 ProviderInfo pi = (ProviderInfo)providers.get(i);
6275 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6276 Slog.w(TAG, "Not installing system proc provider " + pi.name
6277 + ": not system .apk");
6278 providers.remove(i);
6279 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006280 }
6281 }
6282 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006283 if (providers != null) {
6284 mSystemThread.installSystemProviders(providers);
6285 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006286
6287 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006288
6289 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 }
6291
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006292 /**
6293 * Allows app to retrieve the MIME type of a URI without having permission
6294 * to access its content provider.
6295 *
6296 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6297 *
6298 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6299 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6300 */
6301 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006302 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006303 final String name = uri.getAuthority();
6304 final long ident = Binder.clearCallingIdentity();
6305 ContentProviderHolder holder = null;
6306
6307 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006308 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006309 if (holder != null) {
6310 return holder.provider.getType(uri);
6311 }
6312 } catch (RemoteException e) {
6313 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6314 return null;
6315 } finally {
6316 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006317 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006318 }
6319 Binder.restoreCallingIdentity(ident);
6320 }
6321
6322 return null;
6323 }
6324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 // =========================================================
6326 // GLOBAL MANAGEMENT
6327 // =========================================================
6328
6329 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006330 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 String proc = customProcess != null ? customProcess : info.processName;
6332 BatteryStatsImpl.Uid.Proc ps = null;
6333 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006334 int uid = info.uid;
6335 if (isolated) {
6336 int userId = UserId.getUserId(uid);
6337 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6338 uid = 0;
6339 while (true) {
6340 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6341 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6342 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6343 }
6344 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6345 mNextIsolatedProcessUid++;
6346 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6347 // No process for this uid, use it.
6348 break;
6349 }
6350 stepsLeft--;
6351 if (stepsLeft <= 0) {
6352 return null;
6353 }
6354 }
6355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006356 synchronized (stats) {
6357 ps = stats.getProcessStatsLocked(info.uid, proc);
6358 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006359 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 }
6361
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006362 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6363 ProcessRecord app;
6364 if (!isolated) {
6365 app = getProcessRecordLocked(info.processName, info.uid);
6366 } else {
6367 app = null;
6368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369
6370 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006371 app = newProcessRecordLocked(null, info, null, isolated);
6372 mProcessNames.put(info.processName, app.uid, app);
6373 if (isolated) {
6374 mIsolatedProcesses.put(app.uid, app);
6375 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006376 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 }
6378
Dianne Hackborne7f97212011-02-24 14:40:20 -08006379 // This package really, really can not be stopped.
6380 try {
6381 AppGlobals.getPackageManager().setPackageStoppedState(
6382 info.packageName, false);
6383 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006384 } catch (IllegalArgumentException e) {
6385 Slog.w(TAG, "Failed trying to unstop package "
6386 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006387 }
6388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6390 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6391 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006392 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 }
6394 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6395 mPersistentStartingProcesses.add(app);
6396 startProcessLocked(app, "added application", app.processName);
6397 }
6398
6399 return app;
6400 }
6401
6402 public void unhandledBack() {
6403 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6404 "unhandledBack()");
6405
6406 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006407 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006408 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 TAG, "Performing unhandledBack(): stack size = " + count);
6410 if (count > 1) {
6411 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006412 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6414 Binder.restoreCallingIdentity(origId);
6415 }
6416 }
6417 }
6418
6419 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006420 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006422 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 ParcelFileDescriptor pfd = null;
6424 if (cph != null) {
6425 // We record the binder invoker's uid in thread-local storage before
6426 // going to the content provider to open the file. Later, in the code
6427 // that handles all permissions checks, we look for this uid and use
6428 // that rather than the Activity Manager's own uid. The effect is that
6429 // we do the check against the caller's permissions even though it looks
6430 // to the content provider like the Activity Manager itself is making
6431 // the request.
6432 sCallerIdentity.set(new Identity(
6433 Binder.getCallingPid(), Binder.getCallingUid()));
6434 try {
6435 pfd = cph.provider.openFile(uri, "r");
6436 } catch (FileNotFoundException e) {
6437 // do nothing; pfd will be returned null
6438 } finally {
6439 // Ensure that whatever happens, we clean up the identity state
6440 sCallerIdentity.remove();
6441 }
6442
6443 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006444 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006446 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 }
6448 return pfd;
6449 }
6450
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006451 // Actually is sleeping or shutting down or whatever else in the future
6452 // is an inactive state.
6453 public boolean isSleeping() {
6454 return mSleeping || mShuttingDown;
6455 }
6456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 public void goingToSleep() {
6458 synchronized(this) {
6459 mSleeping = true;
6460 mWindowManager.setEventDispatching(false);
6461
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006462 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006463
6464 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006465 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006466 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6467 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006468 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 }
6470 }
6471
Dianne Hackborn55280a92009-05-07 15:53:46 -07006472 public boolean shutdown(int timeout) {
6473 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6474 != PackageManager.PERMISSION_GRANTED) {
6475 throw new SecurityException("Requires permission "
6476 + android.Manifest.permission.SHUTDOWN);
6477 }
6478
6479 boolean timedout = false;
6480
6481 synchronized(this) {
6482 mShuttingDown = true;
6483 mWindowManager.setEventDispatching(false);
6484
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006485 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006486 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006487 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006488 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006489 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006490 long delay = endTime - System.currentTimeMillis();
6491 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006492 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006493 timedout = true;
6494 break;
6495 }
6496 try {
6497 this.wait();
6498 } catch (InterruptedException e) {
6499 }
6500 }
6501 }
6502 }
6503
6504 mUsageStatsService.shutdown();
6505 mBatteryStatsService.shutdown();
6506
6507 return timedout;
6508 }
6509
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006510 public final void activitySlept(IBinder token) {
6511 if (localLOGV) Slog.v(
6512 TAG, "Activity slept: token=" + token);
6513
6514 ActivityRecord r = null;
6515
6516 final long origId = Binder.clearCallingIdentity();
6517
6518 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006519 r = mMainStack.isInStackLocked(token);
6520 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006521 mMainStack.activitySleptLocked(r);
6522 }
6523 }
6524
6525 Binder.restoreCallingIdentity(origId);
6526 }
6527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 public void wakingUp() {
6529 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006530 mWindowManager.setEventDispatching(true);
6531 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006532 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006533 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 }
6535 }
6536
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006537 public void stopAppSwitches() {
6538 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6539 != PackageManager.PERMISSION_GRANTED) {
6540 throw new SecurityException("Requires permission "
6541 + android.Manifest.permission.STOP_APP_SWITCHES);
6542 }
6543
6544 synchronized(this) {
6545 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6546 + APP_SWITCH_DELAY_TIME;
6547 mDidAppSwitch = false;
6548 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6549 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6550 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6551 }
6552 }
6553
6554 public void resumeAppSwitches() {
6555 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6556 != PackageManager.PERMISSION_GRANTED) {
6557 throw new SecurityException("Requires permission "
6558 + android.Manifest.permission.STOP_APP_SWITCHES);
6559 }
6560
6561 synchronized(this) {
6562 // Note that we don't execute any pending app switches... we will
6563 // let those wait until either the timeout, or the next start
6564 // activity request.
6565 mAppSwitchesAllowedTime = 0;
6566 }
6567 }
6568
6569 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6570 String name) {
6571 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6572 return true;
6573 }
6574
6575 final int perm = checkComponentPermission(
6576 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006577 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006578 if (perm == PackageManager.PERMISSION_GRANTED) {
6579 return true;
6580 }
6581
Joe Onorato8a9b2202010-02-26 18:56:32 -08006582 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006583 return false;
6584 }
6585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 public void setDebugApp(String packageName, boolean waitForDebugger,
6587 boolean persistent) {
6588 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6589 "setDebugApp()");
6590
6591 // Note that this is not really thread safe if there are multiple
6592 // callers into it at the same time, but that's not a situation we
6593 // care about.
6594 if (persistent) {
6595 final ContentResolver resolver = mContext.getContentResolver();
6596 Settings.System.putString(
6597 resolver, Settings.System.DEBUG_APP,
6598 packageName);
6599 Settings.System.putInt(
6600 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6601 waitForDebugger ? 1 : 0);
6602 }
6603
6604 synchronized (this) {
6605 if (!persistent) {
6606 mOrigDebugApp = mDebugApp;
6607 mOrigWaitForDebugger = mWaitForDebugger;
6608 }
6609 mDebugApp = packageName;
6610 mWaitForDebugger = waitForDebugger;
6611 mDebugTransient = !persistent;
6612 if (packageName != null) {
6613 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07006614 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 Binder.restoreCallingIdentity(origId);
6616 }
6617 }
6618 }
6619
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006620 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6621 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6622 synchronized (this) {
6623 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6624 if (!isDebuggable) {
6625 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6626 throw new SecurityException("Process not debuggable: " + app.packageName);
6627 }
6628 }
6629 mProfileApp = processName;
6630 mProfileFile = profileFile;
6631 if (mProfileFd != null) {
6632 try {
6633 mProfileFd.close();
6634 } catch (IOException e) {
6635 }
6636 mProfileFd = null;
6637 }
6638 mProfileFd = profileFd;
6639 mProfileType = 0;
6640 mAutoStopProfiler = autoStopProfiler;
6641 }
6642 }
6643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 public void setAlwaysFinish(boolean enabled) {
6645 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6646 "setAlwaysFinish()");
6647
6648 Settings.System.putInt(
6649 mContext.getContentResolver(),
6650 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6651
6652 synchronized (this) {
6653 mAlwaysFinishActivities = enabled;
6654 }
6655 }
6656
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006657 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006659 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006660 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006661 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 }
6663 }
6664
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006665 public boolean isUserAMonkey() {
6666 // For now the fact that there is a controller implies
6667 // we have a monkey.
6668 synchronized (this) {
6669 return mController != null;
6670 }
6671 }
6672
Jeff Sharkeya4620792011-05-20 15:29:23 -07006673 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006674 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6675 "registerProcessObserver()");
6676 synchronized (this) {
6677 mProcessObservers.register(observer);
6678 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006679 }
6680
6681 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006682 synchronized (this) {
6683 mProcessObservers.unregister(observer);
6684 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006685 }
6686
Daniel Sandler69a48172010-06-23 16:29:36 -04006687 public void setImmersive(IBinder token, boolean immersive) {
6688 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006689 ActivityRecord r = mMainStack.isInStackLocked(token);
6690 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006691 throw new IllegalArgumentException();
6692 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006693 r.immersive = immersive;
6694 }
6695 }
6696
6697 public boolean isImmersive(IBinder token) {
6698 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006699 ActivityRecord r = mMainStack.isInStackLocked(token);
6700 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006701 throw new IllegalArgumentException();
6702 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006703 return r.immersive;
6704 }
6705 }
6706
6707 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006708 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006709 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006710 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006711 return (r != null) ? r.immersive : false;
6712 }
6713 }
6714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 public final void enterSafeMode() {
6716 synchronized(this) {
6717 // It only makes sense to do this before the system is ready
6718 // and started launching other packages.
6719 if (!mSystemReady) {
6720 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006721 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 } catch (RemoteException e) {
6723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 }
6725 }
6726 }
6727
Jeff Brownb09abc12011-01-13 21:08:27 -08006728 public final void showSafeModeOverlay() {
6729 View v = LayoutInflater.from(mContext).inflate(
6730 com.android.internal.R.layout.safe_mode, null);
6731 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6732 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6733 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6734 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6735 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6736 lp.format = v.getBackground().getOpacity();
6737 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6738 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6739 ((WindowManager)mContext.getSystemService(
6740 Context.WINDOW_SERVICE)).addView(v, lp);
6741 }
6742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006743 public void noteWakeupAlarm(IIntentSender sender) {
6744 if (!(sender instanceof PendingIntentRecord)) {
6745 return;
6746 }
6747 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6748 synchronized (stats) {
6749 if (mBatteryStatsService.isOnBattery()) {
6750 mBatteryStatsService.enforceCallingPermission();
6751 PendingIntentRecord rec = (PendingIntentRecord)sender;
6752 int MY_UID = Binder.getCallingUid();
6753 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6754 BatteryStatsImpl.Uid.Pkg pkg =
6755 stats.getPackageStatsLocked(uid, rec.key.packageName);
6756 pkg.incWakeupsLocked();
6757 }
6758 }
6759 }
6760
Dianne Hackborn64825172011-03-02 21:32:58 -08006761 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006762 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006763 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006764 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006765 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 // XXX Note: don't acquire main activity lock here, because the window
6767 // manager calls in with its locks held.
6768
6769 boolean killed = false;
6770 synchronized (mPidsSelfLocked) {
6771 int[] types = new int[pids.length];
6772 int worstType = 0;
6773 for (int i=0; i<pids.length; i++) {
6774 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6775 if (proc != null) {
6776 int type = proc.setAdj;
6777 types[i] = type;
6778 if (type > worstType) {
6779 worstType = type;
6780 }
6781 }
6782 }
6783
Dianne Hackborn64825172011-03-02 21:32:58 -08006784 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006785 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006786 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6787 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006788 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006789 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006790
6791 // If this is not a secure call, don't let it kill processes that
6792 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006793 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6794 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006795 }
6796
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006797 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006798 for (int i=0; i<pids.length; i++) {
6799 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6800 if (proc == null) {
6801 continue;
6802 }
6803 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006804 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006805 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006806 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6807 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006808 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006809 proc.killedBackground = true;
6810 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 }
6812 }
6813 }
6814 return killed;
6815 }
6816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006817 public final void startRunning(String pkg, String cls, String action,
6818 String data) {
6819 synchronized(this) {
6820 if (mStartRunning) {
6821 return;
6822 }
6823 mStartRunning = true;
6824 mTopComponent = pkg != null && cls != null
6825 ? new ComponentName(pkg, cls) : null;
6826 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6827 mTopData = data;
6828 if (!mSystemReady) {
6829 return;
6830 }
6831 }
6832
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006833 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006834 }
6835
6836 private void retrieveSettings() {
6837 final ContentResolver resolver = mContext.getContentResolver();
6838 String debugApp = Settings.System.getString(
6839 resolver, Settings.System.DEBUG_APP);
6840 boolean waitForDebugger = Settings.System.getInt(
6841 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6842 boolean alwaysFinishActivities = Settings.System.getInt(
6843 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6844
6845 Configuration configuration = new Configuration();
6846 Settings.System.getConfiguration(resolver, configuration);
6847
6848 synchronized (this) {
6849 mDebugApp = mOrigDebugApp = debugApp;
6850 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6851 mAlwaysFinishActivities = alwaysFinishActivities;
6852 // This happens before any activities are started, so we can
6853 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08006854 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006855 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006856 }
6857 }
6858
6859 public boolean testIsSystemReady() {
6860 // no need to synchronize(this) just to read & return the value
6861 return mSystemReady;
6862 }
6863
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006864 private static File getCalledPreBootReceiversFile() {
6865 File dataDir = Environment.getDataDirectory();
6866 File systemDir = new File(dataDir, "system");
6867 File fname = new File(systemDir, "called_pre_boots.dat");
6868 return fname;
6869 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07006870
6871 static final int LAST_DONE_VERSION = 10000;
6872
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006873 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6874 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6875 File file = getCalledPreBootReceiversFile();
6876 FileInputStream fis = null;
6877 try {
6878 fis = new FileInputStream(file);
6879 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006880 int fvers = dis.readInt();
6881 if (fvers == LAST_DONE_VERSION) {
6882 String vers = dis.readUTF();
6883 String codename = dis.readUTF();
6884 String build = dis.readUTF();
6885 if (android.os.Build.VERSION.RELEASE.equals(vers)
6886 && android.os.Build.VERSION.CODENAME.equals(codename)
6887 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
6888 int num = dis.readInt();
6889 while (num > 0) {
6890 num--;
6891 String pkg = dis.readUTF();
6892 String cls = dis.readUTF();
6893 lastDoneReceivers.add(new ComponentName(pkg, cls));
6894 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006895 }
6896 }
6897 } catch (FileNotFoundException e) {
6898 } catch (IOException e) {
6899 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6900 } finally {
6901 if (fis != null) {
6902 try {
6903 fis.close();
6904 } catch (IOException e) {
6905 }
6906 }
6907 }
6908 return lastDoneReceivers;
6909 }
6910
6911 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
6912 File file = getCalledPreBootReceiversFile();
6913 FileOutputStream fos = null;
6914 DataOutputStream dos = null;
6915 try {
6916 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
6917 fos = new FileOutputStream(file);
6918 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006919 dos.writeInt(LAST_DONE_VERSION);
6920 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006921 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07006922 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006923 dos.writeInt(list.size());
6924 for (int i=0; i<list.size(); i++) {
6925 dos.writeUTF(list.get(i).getPackageName());
6926 dos.writeUTF(list.get(i).getClassName());
6927 }
6928 } catch (IOException e) {
6929 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
6930 file.delete();
6931 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006932 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006933 if (dos != null) {
6934 try {
6935 dos.close();
6936 } catch (IOException e) {
6937 // TODO Auto-generated catch block
6938 e.printStackTrace();
6939 }
6940 }
6941 }
6942 }
6943
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006944 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006945 synchronized(this) {
6946 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006947 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 return;
6949 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006950
6951 // Check to see if there are any update receivers to run.
6952 if (!mDidUpdate) {
6953 if (mWaitingUpdate) {
6954 return;
6955 }
6956 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6957 List<ResolveInfo> ris = null;
6958 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006959 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006960 intent, null, 0);
6961 } catch (RemoteException e) {
6962 }
6963 if (ris != null) {
6964 for (int i=ris.size()-1; i>=0; i--) {
6965 if ((ris.get(i).activityInfo.applicationInfo.flags
6966 &ApplicationInfo.FLAG_SYSTEM) == 0) {
6967 ris.remove(i);
6968 }
6969 }
6970 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006971
6972 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
6973
6974 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006975 for (int i=0; i<ris.size(); i++) {
6976 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006977 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6978 if (lastDoneReceivers.contains(comp)) {
6979 ris.remove(i);
6980 i--;
6981 }
6982 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07006983
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006984 for (int i=0; i<ris.size(); i++) {
6985 ActivityInfo ai = ris.get(i).activityInfo;
6986 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6987 doneReceivers.add(comp);
6988 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006989 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08006990 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006991 finisher = new IIntentReceiver.Stub() {
6992 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07006993 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006994 boolean sticky) {
6995 // The raw IIntentReceiver interface is called
6996 // with the AM lock held, so redispatch to
6997 // execute our code without the lock.
6998 mHandler.post(new Runnable() {
6999 public void run() {
7000 synchronized (ActivityManagerService.this) {
7001 mDidUpdate = true;
7002 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007003 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007004 showBootMessage(mContext.getText(
7005 R.string.android_upgrading_complete),
7006 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007007 systemReady(goingCallback);
7008 }
7009 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007010 }
7011 };
7012 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007013 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007014 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007015 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007016 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007017 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007018 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007019 mWaitingUpdate = true;
7020 }
7021 }
7022 }
7023 if (mWaitingUpdate) {
7024 return;
7025 }
7026 mDidUpdate = true;
7027 }
7028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007029 mSystemReady = true;
7030 if (!mStartRunning) {
7031 return;
7032 }
7033 }
7034
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007035 ArrayList<ProcessRecord> procsToKill = null;
7036 synchronized(mPidsSelfLocked) {
7037 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7038 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7039 if (!isAllowedWhileBooting(proc.info)){
7040 if (procsToKill == null) {
7041 procsToKill = new ArrayList<ProcessRecord>();
7042 }
7043 procsToKill.add(proc);
7044 }
7045 }
7046 }
7047
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007048 synchronized(this) {
7049 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007050 for (int i=procsToKill.size()-1; i>=0; i--) {
7051 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007052 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007053 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007054 }
7055 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007056
7057 // Now that we have cleaned up any update processes, we
7058 // are ready to start launching real processes and know that
7059 // we won't trample on them any more.
7060 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007061 }
7062
Joe Onorato8a9b2202010-02-26 18:56:32 -08007063 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007064 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007065 SystemClock.uptimeMillis());
7066
7067 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007068 // Make sure we have no pre-ready processes sitting around.
7069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007070 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7071 ResolveInfo ri = mContext.getPackageManager()
7072 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007073 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 CharSequence errorMsg = null;
7075 if (ri != null) {
7076 ActivityInfo ai = ri.activityInfo;
7077 ApplicationInfo app = ai.applicationInfo;
7078 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7079 mTopAction = Intent.ACTION_FACTORY_TEST;
7080 mTopData = null;
7081 mTopComponent = new ComponentName(app.packageName,
7082 ai.name);
7083 } else {
7084 errorMsg = mContext.getResources().getText(
7085 com.android.internal.R.string.factorytest_not_system);
7086 }
7087 } else {
7088 errorMsg = mContext.getResources().getText(
7089 com.android.internal.R.string.factorytest_no_action);
7090 }
7091 if (errorMsg != null) {
7092 mTopAction = null;
7093 mTopData = null;
7094 mTopComponent = null;
7095 Message msg = Message.obtain();
7096 msg.what = SHOW_FACTORY_ERROR_MSG;
7097 msg.getData().putCharSequence("msg", errorMsg);
7098 mHandler.sendMessage(msg);
7099 }
7100 }
7101 }
7102
7103 retrieveSettings();
7104
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007105 if (goingCallback != null) goingCallback.run();
7106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007107 synchronized (this) {
7108 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7109 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007110 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007111 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007112 if (apps != null) {
7113 int N = apps.size();
7114 int i;
7115 for (i=0; i<N; i++) {
7116 ApplicationInfo info
7117 = (ApplicationInfo)apps.get(i);
7118 if (info != null &&
7119 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007120 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007121 }
7122 }
7123 }
7124 } catch (RemoteException ex) {
7125 // pm is in same process, this will never happen.
7126 }
7127 }
7128
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007129 // Start up initial activity.
7130 mBooting = true;
7131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007133 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007134 Message msg = Message.obtain();
7135 msg.what = SHOW_UID_ERROR_MSG;
7136 mHandler.sendMessage(msg);
7137 }
7138 } catch (RemoteException e) {
7139 }
7140
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007141 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007142 }
7143 }
7144
Dan Egnorb7f03672009-12-09 16:22:32 -08007145 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007146 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007147 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007148 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007149 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007150 startAppProblemLocked(app);
7151 app.stopFreezingAllLocked();
7152 return handleAppCrashLocked(app);
7153 }
7154
Dan Egnorb7f03672009-12-09 16:22:32 -08007155 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007156 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007157 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007158 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007159 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7160 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007161 startAppProblemLocked(app);
7162 app.stopFreezingAllLocked();
7163 }
7164
7165 /**
7166 * Generate a process error record, suitable for attachment to a ProcessRecord.
7167 *
7168 * @param app The ProcessRecord in which the error occurred.
7169 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7170 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007171 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007172 * @param shortMsg Short message describing the crash.
7173 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007174 * @param stackTrace Full crash stack trace, may be null.
7175 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007176 * @return Returns a fully-formed AppErrorStateInfo record.
7177 */
7178 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007179 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007180 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 report.condition = condition;
7183 report.processName = app.processName;
7184 report.pid = app.pid;
7185 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007186 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 report.shortMsg = shortMsg;
7188 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007189 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190
7191 return report;
7192 }
7193
Dan Egnor42471dd2010-01-07 17:25:22 -08007194 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007195 synchronized (this) {
7196 app.crashing = false;
7197 app.crashingReport = null;
7198 app.notResponding = false;
7199 app.notRespondingReport = null;
7200 if (app.anrDialog == fromDialog) {
7201 app.anrDialog = null;
7202 }
7203 if (app.waitDialog == fromDialog) {
7204 app.waitDialog = null;
7205 }
7206 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007207 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007208 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007209 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7210 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007211 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007213 }
7214 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007215
Dan Egnorb7f03672009-12-09 16:22:32 -08007216 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007217 long now = SystemClock.uptimeMillis();
7218
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007219 Long crashTime;
7220 if (!app.isolated) {
7221 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7222 } else {
7223 crashTime = null;
7224 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007225 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007226 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007227 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007228 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007229 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007230 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007231 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7232 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007233 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007234 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007235 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007236 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007237 }
7238 }
7239 if (!app.persistent) {
7240 // We don't want to start this process again until the user
7241 // explicitly does so... but for persistent process, we really
7242 // need to keep it running. If a persistent process is actually
7243 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007244 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007245 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007246 if (!app.isolated) {
7247 // XXX We don't have a way to mark isolated processes
7248 // as bad, since they don't have a peristent identity.
7249 mBadProcesses.put(app.info.processName, app.uid, now);
7250 mProcessCrashTimes.remove(app.info.processName, app.uid);
7251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007252 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007253 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007254 // Don't let services in this process be restarted and potentially
7255 // annoy the user repeatedly. Unless it is persistent, since those
7256 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007257 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007258 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007259 return false;
7260 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007261 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007262 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007263 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007264 if (r.app == app) {
7265 // If the top running activity is from this crashing
7266 // process, then terminate it to avoid getting in a loop.
7267 Slog.w(TAG, " Force finishing activity "
7268 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007269 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007270 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007271 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007272 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007273 // stopped, to avoid a situation where one will get
7274 // re-start our crashing activity once it gets resumed again.
7275 index--;
7276 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007277 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007278 if (r.state == ActivityState.RESUMED
7279 || r.state == ActivityState.PAUSING
7280 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007281 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007282 Slog.w(TAG, " Force finishing activity "
7283 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007284 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007285 Activity.RESULT_CANCELED, null, "crashed");
7286 }
7287 }
7288 }
7289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007290 }
7291
7292 // Bump up the crash count of any services currently running in the proc.
7293 if (app.services.size() != 0) {
7294 // Any services running in the application need to be placed
7295 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007296 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007297 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007298 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007299 sr.crashCount++;
7300 }
7301 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007302
7303 // If the crashing process is what we consider to be the "home process" and it has been
7304 // replaced by a third-party app, clear the package preferred activities from packages
7305 // with a home activity running in the process to prevent a repeatedly crashing app
7306 // from blocking the user to manually clear the list.
7307 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7308 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7309 Iterator it = mHomeProcess.activities.iterator();
7310 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007311 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007312 if (r.isHomeActivity) {
7313 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7314 try {
7315 ActivityThread.getPackageManager()
7316 .clearPackagePreferredActivities(r.packageName);
7317 } catch (RemoteException c) {
7318 // pm is in same process, this will never happen.
7319 }
7320 }
7321 }
7322 }
7323
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007324 if (!app.isolated) {
7325 // XXX Can't keep track of crash times for isolated processes,
7326 // because they don't have a perisistent identity.
7327 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7328 }
7329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 return true;
7331 }
7332
7333 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007334 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7335 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007336 skipCurrentReceiverLocked(app);
7337 }
7338
7339 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007340 for (BroadcastQueue queue : mBroadcastQueues) {
7341 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 }
7343 }
7344
Dan Egnor60d87622009-12-16 16:32:58 -08007345 /**
7346 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7347 * The application process will exit immediately after this call returns.
7348 * @param app object of the crashing app, null for the system server
7349 * @param crashInfo describing the exception
7350 */
7351 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007352 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007353 final String processName = app == null ? "system_server"
7354 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007355
7356 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007357 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007358 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007359 crashInfo.exceptionClassName,
7360 crashInfo.exceptionMessage,
7361 crashInfo.throwFileName,
7362 crashInfo.throwLineNumber);
7363
Jeff Sharkeya353d262011-10-28 11:12:06 -07007364 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007365
7366 crashApplication(r, crashInfo);
7367 }
7368
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007369 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007370 IBinder app,
7371 int violationMask,
7372 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007373 ProcessRecord r = findAppProcess(app, "StrictMode");
7374 if (r == null) {
7375 return;
7376 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007377
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007378 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007379 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007380 boolean logIt = true;
7381 synchronized (mAlreadyLoggedViolatedStacks) {
7382 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7383 logIt = false;
7384 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007385 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007386 // the relative pain numbers, without logging all
7387 // the stack traces repeatedly. We'd want to do
7388 // likewise in the client code, which also does
7389 // dup suppression, before the Binder call.
7390 } else {
7391 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7392 mAlreadyLoggedViolatedStacks.clear();
7393 }
7394 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7395 }
7396 }
7397 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007398 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007399 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007400 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007401
7402 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7403 AppErrorResult result = new AppErrorResult();
7404 synchronized (this) {
7405 final long origId = Binder.clearCallingIdentity();
7406
7407 Message msg = Message.obtain();
7408 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7409 HashMap<String, Object> data = new HashMap<String, Object>();
7410 data.put("result", result);
7411 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007412 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007413 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007414 msg.obj = data;
7415 mHandler.sendMessage(msg);
7416
7417 Binder.restoreCallingIdentity(origId);
7418 }
7419 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007420 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007421 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007422 }
7423
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007424 // Depending on the policy in effect, there could be a bunch of
7425 // these in quick succession so we try to batch these together to
7426 // minimize disk writes, number of dropbox entries, and maximize
7427 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007428 private void logStrictModeViolationToDropBox(
7429 ProcessRecord process,
7430 StrictMode.ViolationInfo info) {
7431 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007432 return;
7433 }
7434 final boolean isSystemApp = process == null ||
7435 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7436 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007437 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007438 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7439 final DropBoxManager dbox = (DropBoxManager)
7440 mContext.getSystemService(Context.DROPBOX_SERVICE);
7441
7442 // Exit early if the dropbox isn't configured to accept this report type.
7443 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7444
7445 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007446 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007447 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7448 synchronized (sb) {
7449 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007450 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007451 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7452 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007453 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7454 if (info.violationNumThisLoop != 0) {
7455 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7456 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007457 if (info.numAnimationsRunning != 0) {
7458 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7459 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007460 if (info.broadcastIntentAction != null) {
7461 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7462 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007463 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007464 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007465 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007466 if (info.numInstances != -1) {
7467 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7468 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007469 if (info.tags != null) {
7470 for (String tag : info.tags) {
7471 sb.append("Span-Tag: ").append(tag).append("\n");
7472 }
7473 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007474 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007475 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7476 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007477 }
7478 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007479
7480 // Only buffer up to ~64k. Various logging bits truncate
7481 // things at 128k.
7482 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007483 }
7484
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007485 // Flush immediately if the buffer's grown too large, or this
7486 // is a non-system app. Non-system apps are isolated with a
7487 // different tag & policy and not batched.
7488 //
7489 // Batching is useful during internal testing with
7490 // StrictMode settings turned up high. Without batching,
7491 // thousands of separate files could be created on boot.
7492 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007493 new Thread("Error dump: " + dropboxTag) {
7494 @Override
7495 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007496 String report;
7497 synchronized (sb) {
7498 report = sb.toString();
7499 sb.delete(0, sb.length());
7500 sb.trimToSize();
7501 }
7502 if (report.length() != 0) {
7503 dbox.addText(dropboxTag, report);
7504 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007505 }
7506 }.start();
7507 return;
7508 }
7509
7510 // System app batching:
7511 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007512 // An existing dropbox-writing thread is outstanding, so
7513 // we don't need to start it up. The existing thread will
7514 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007515 return;
7516 }
7517
7518 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7519 // (After this point, we shouldn't access AMS internal data structures.)
7520 new Thread("Error dump: " + dropboxTag) {
7521 @Override
7522 public void run() {
7523 // 5 second sleep to let stacks arrive and be batched together
7524 try {
7525 Thread.sleep(5000); // 5 seconds
7526 } catch (InterruptedException e) {}
7527
7528 String errorReport;
7529 synchronized (mStrictModeBuffer) {
7530 errorReport = mStrictModeBuffer.toString();
7531 if (errorReport.length() == 0) {
7532 return;
7533 }
7534 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7535 mStrictModeBuffer.trimToSize();
7536 }
7537 dbox.addText(dropboxTag, errorReport);
7538 }
7539 }.start();
7540 }
7541
Dan Egnor60d87622009-12-16 16:32:58 -08007542 /**
7543 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7544 * @param app object of the crashing app, null for the system server
7545 * @param tag reported by the caller
7546 * @param crashInfo describing the context of the error
7547 * @return true if the process should exit immediately (WTF is fatal)
7548 */
7549 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007550 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007551 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007552 final String processName = app == null ? "system_server"
7553 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007554
7555 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007556 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007557 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007558 tag, crashInfo.exceptionMessage);
7559
Jeff Sharkeya353d262011-10-28 11:12:06 -07007560 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007561
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007562 if (r != null && r.pid != Process.myPid() &&
7563 Settings.Secure.getInt(mContext.getContentResolver(),
7564 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007565 crashApplication(r, crashInfo);
7566 return true;
7567 } else {
7568 return false;
7569 }
7570 }
7571
7572 /**
7573 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7574 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7575 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007576 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007577 if (app == null) {
7578 return null;
7579 }
7580
7581 synchronized (this) {
7582 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7583 final int NA = apps.size();
7584 for (int ia=0; ia<NA; ia++) {
7585 ProcessRecord p = apps.valueAt(ia);
7586 if (p.thread != null && p.thread.asBinder() == app) {
7587 return p;
7588 }
7589 }
7590 }
7591
Dianne Hackborncb44d962011-03-10 17:02:27 -08007592 Slog.w(TAG, "Can't find mystery application for " + reason
7593 + " from pid=" + Binder.getCallingPid()
7594 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007595 return null;
7596 }
7597 }
7598
7599 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007600 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7601 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007602 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007603 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7604 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007605 // Watchdog thread ends up invoking this function (with
7606 // a null ProcessRecord) to add the stack file to dropbox.
7607 // Do not acquire a lock on this (am) in such cases, as it
7608 // could cause a potential deadlock, if and when watchdog
7609 // is invoked due to unavailability of lock on am and it
7610 // would prevent watchdog from killing system_server.
7611 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007612 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007613 return;
7614 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007615 // Note: ProcessRecord 'process' is guarded by the service
7616 // instance. (notably process.pkgList, which could otherwise change
7617 // concurrently during execution of this method)
7618 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007619 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007620 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007621 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007622 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7623 for (String pkg : process.pkgList) {
7624 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007625 try {
Dan Egnora455d192010-03-12 08:52:28 -08007626 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7627 if (pi != null) {
7628 sb.append(" v").append(pi.versionCode);
7629 if (pi.versionName != null) {
7630 sb.append(" (").append(pi.versionName).append(")");
7631 }
7632 }
7633 } catch (RemoteException e) {
7634 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007635 }
Dan Egnora455d192010-03-12 08:52:28 -08007636 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007637 }
Dan Egnora455d192010-03-12 08:52:28 -08007638 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007639 }
7640
7641 private static String processClass(ProcessRecord process) {
7642 if (process == null || process.pid == MY_PID) {
7643 return "system_server";
7644 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7645 return "system_app";
7646 } else {
7647 return "data_app";
7648 }
7649 }
7650
7651 /**
7652 * Write a description of an error (crash, WTF, ANR) to the drop box.
7653 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7654 * @param process which caused the error, null means the system server
7655 * @param activity which triggered the error, null if unknown
7656 * @param parent activity related to the error, null if unknown
7657 * @param subject line related to the error, null if absent
7658 * @param report in long form describing the error, null if absent
7659 * @param logFile to include in the report, null if none
7660 * @param crashInfo giving an application stack trace, null if absent
7661 */
7662 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007663 ProcessRecord process, String processName, ActivityRecord activity,
7664 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007665 final String report, final File logFile,
7666 final ApplicationErrorReport.CrashInfo crashInfo) {
7667 // NOTE -- this must never acquire the ActivityManagerService lock,
7668 // otherwise the watchdog may be prevented from resetting the system.
7669
7670 final String dropboxTag = processClass(process) + "_" + eventType;
7671 final DropBoxManager dbox = (DropBoxManager)
7672 mContext.getSystemService(Context.DROPBOX_SERVICE);
7673
7674 // Exit early if the dropbox isn't configured to accept this report type.
7675 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7676
7677 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007678 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007679 if (activity != null) {
7680 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7681 }
7682 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7683 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7684 }
7685 if (parent != null && parent != activity) {
7686 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7687 }
7688 if (subject != null) {
7689 sb.append("Subject: ").append(subject).append("\n");
7690 }
7691 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007692 if (Debug.isDebuggerConnected()) {
7693 sb.append("Debugger: Connected\n");
7694 }
Dan Egnora455d192010-03-12 08:52:28 -08007695 sb.append("\n");
7696
7697 // Do the rest in a worker thread to avoid blocking the caller on I/O
7698 // (After this point, we shouldn't access AMS internal data structures.)
7699 Thread worker = new Thread("Error dump: " + dropboxTag) {
7700 @Override
7701 public void run() {
7702 if (report != null) {
7703 sb.append(report);
7704 }
7705 if (logFile != null) {
7706 try {
7707 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7708 } catch (IOException e) {
7709 Slog.e(TAG, "Error reading " + logFile, e);
7710 }
7711 }
7712 if (crashInfo != null && crashInfo.stackTrace != null) {
7713 sb.append(crashInfo.stackTrace);
7714 }
7715
7716 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7717 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7718 if (lines > 0) {
7719 sb.append("\n");
7720
7721 // Merge several logcat streams, and take the last N lines
7722 InputStreamReader input = null;
7723 try {
7724 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7725 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7726 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7727
7728 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7729 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7730 input = new InputStreamReader(logcat.getInputStream());
7731
7732 int num;
7733 char[] buf = new char[8192];
7734 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7735 } catch (IOException e) {
7736 Slog.e(TAG, "Error running logcat", e);
7737 } finally {
7738 if (input != null) try { input.close(); } catch (IOException e) {}
7739 }
7740 }
7741
7742 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007743 }
Dan Egnora455d192010-03-12 08:52:28 -08007744 };
7745
7746 if (process == null || process.pid == MY_PID) {
7747 worker.run(); // We may be about to die -- need to run this synchronously
7748 } else {
7749 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007750 }
7751 }
7752
7753 /**
7754 * Bring up the "unexpected error" dialog box for a crashing app.
7755 * Deal with edge cases (intercepts from instrumented applications,
7756 * ActivityController, error intent receivers, that sort of thing).
7757 * @param r the application crashing
7758 * @param crashInfo describing the failure
7759 */
7760 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007761 long timeMillis = System.currentTimeMillis();
7762 String shortMsg = crashInfo.exceptionClassName;
7763 String longMsg = crashInfo.exceptionMessage;
7764 String stackTrace = crashInfo.stackTrace;
7765 if (shortMsg != null && longMsg != null) {
7766 longMsg = shortMsg + ": " + longMsg;
7767 } else if (shortMsg != null) {
7768 longMsg = shortMsg;
7769 }
7770
Dan Egnor60d87622009-12-16 16:32:58 -08007771 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007773 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 try {
7775 String name = r != null ? r.processName : null;
7776 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007777 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007778 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007779 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 + " at watcher's request");
7781 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007782 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 }
7784 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007785 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786 }
7787 }
7788
7789 final long origId = Binder.clearCallingIdentity();
7790
7791 // If this process is running instrumentation, finish it.
7792 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007793 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007794 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007795 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7796 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 Bundle info = new Bundle();
7798 info.putString("shortMsg", shortMsg);
7799 info.putString("longMsg", longMsg);
7800 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7801 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007802 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803 }
7804
Dan Egnor60d87622009-12-16 16:32:58 -08007805 // If we can't identify the process or it's already exceeded its crash quota,
7806 // quit right away without showing a crash dialog.
7807 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007808 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007809 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007810 }
7811
7812 Message msg = Message.obtain();
7813 msg.what = SHOW_ERROR_MSG;
7814 HashMap data = new HashMap();
7815 data.put("result", result);
7816 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 msg.obj = data;
7818 mHandler.sendMessage(msg);
7819
7820 Binder.restoreCallingIdentity(origId);
7821 }
7822
7823 int res = result.get();
7824
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007825 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007827 if (r != null && !r.isolated) {
7828 // XXX Can't keep track of crash time for isolated processes,
7829 // since they don't have a persistent identity.
7830 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007831 SystemClock.uptimeMillis());
7832 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007833 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007834 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007835 }
7836 }
7837
7838 if (appErrorIntent != null) {
7839 try {
7840 mContext.startActivity(appErrorIntent);
7841 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007842 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007845 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007846
7847 Intent createAppErrorIntentLocked(ProcessRecord r,
7848 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7849 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007850 if (report == null) {
7851 return null;
7852 }
7853 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7854 result.setComponent(r.errorReportReceiver);
7855 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7856 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7857 return result;
7858 }
7859
Dan Egnorb7f03672009-12-09 16:22:32 -08007860 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7861 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007862 if (r.errorReportReceiver == null) {
7863 return null;
7864 }
7865
7866 if (!r.crashing && !r.notResponding) {
7867 return null;
7868 }
7869
Dan Egnorb7f03672009-12-09 16:22:32 -08007870 ApplicationErrorReport report = new ApplicationErrorReport();
7871 report.packageName = r.info.packageName;
7872 report.installerPackageName = r.errorReportReceiver.getPackageName();
7873 report.processName = r.processName;
7874 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007875 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007876
Dan Egnorb7f03672009-12-09 16:22:32 -08007877 if (r.crashing) {
7878 report.type = ApplicationErrorReport.TYPE_CRASH;
7879 report.crashInfo = crashInfo;
7880 } else if (r.notResponding) {
7881 report.type = ApplicationErrorReport.TYPE_ANR;
7882 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007883
Dan Egnorb7f03672009-12-09 16:22:32 -08007884 report.anrInfo.activity = r.notRespondingReport.tag;
7885 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7886 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007887 }
7888
Dan Egnorb7f03672009-12-09 16:22:32 -08007889 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007890 }
7891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007893 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007894 // assume our apps are happy - lazy create the list
7895 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7896
7897 synchronized (this) {
7898
7899 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007900 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7901 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007902 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7903 // This one's in trouble, so we'll generate a report for it
7904 // crashes are higher priority (in case there's a crash *and* an anr)
7905 ActivityManager.ProcessErrorStateInfo report = null;
7906 if (app.crashing) {
7907 report = app.crashingReport;
7908 } else if (app.notResponding) {
7909 report = app.notRespondingReport;
7910 }
7911
7912 if (report != null) {
7913 if (errList == null) {
7914 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
7915 }
7916 errList.add(report);
7917 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007918 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 " crashing = " + app.crashing +
7920 " notResponding = " + app.notResponding);
7921 }
7922 }
7923 }
7924 }
7925
7926 return errList;
7927 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07007928
7929 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007930 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07007931 if (currApp != null) {
7932 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
7933 }
7934 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007935 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
7936 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007937 } else if (adj >= ProcessList.HOME_APP_ADJ) {
7938 if (currApp != null) {
7939 currApp.lru = 0;
7940 }
7941 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007942 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07007943 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
7944 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
7945 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
7946 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
7947 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
7948 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
7949 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
7950 } else {
7951 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
7952 }
7953 }
7954
Dianne Hackborn27ff9132012-03-06 14:57:58 -08007955 private void fillInProcMemInfo(ProcessRecord app,
7956 ActivityManager.RunningAppProcessInfo outInfo) {
7957 outInfo.pid = app.pid;
7958 outInfo.uid = app.info.uid;
7959 if (mHeavyWeightProcess == app) {
7960 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
7961 }
7962 if (app.persistent) {
7963 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
7964 }
7965 outInfo.lastTrimLevel = app.trimMemoryLevel;
7966 int adj = app.curAdj;
7967 outInfo.importance = oomAdjToImportance(adj, outInfo);
7968 outInfo.importanceReasonCode = app.adjTypeCode;
7969 }
7970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007972 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973 // Lazy instantiation of list
7974 List<ActivityManager.RunningAppProcessInfo> runList = null;
7975 synchronized (this) {
7976 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007977 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7978 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
7980 // Generate process state info for running application
7981 ActivityManager.RunningAppProcessInfo currApp =
7982 new ActivityManager.RunningAppProcessInfo(app.processName,
7983 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08007984 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007985 if (app.adjSource instanceof ProcessRecord) {
7986 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007987 currApp.importanceReasonImportance = oomAdjToImportance(
7988 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007989 } else if (app.adjSource instanceof ActivityRecord) {
7990 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007991 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
7992 }
7993 if (app.adjTarget instanceof ComponentName) {
7994 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
7995 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007996 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 // + " lru=" + currApp.lru);
7998 if (runList == null) {
7999 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8000 }
8001 runList.add(currApp);
8002 }
8003 }
8004 }
8005 return runList;
8006 }
8007
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008008 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008009 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008010 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8011 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8012 if (runningApps != null && runningApps.size() > 0) {
8013 Set<String> extList = new HashSet<String>();
8014 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8015 if (app.pkgList != null) {
8016 for (String pkg : app.pkgList) {
8017 extList.add(pkg);
8018 }
8019 }
8020 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008021 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008022 for (String pkg : extList) {
8023 try {
8024 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8025 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8026 retList.add(info);
8027 }
8028 } catch (RemoteException e) {
8029 }
8030 }
8031 }
8032 return retList;
8033 }
8034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008036 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8037 enforceNotIsolatedCaller("getMyMemoryState");
8038 synchronized (this) {
8039 ProcessRecord proc;
8040 synchronized (mPidsSelfLocked) {
8041 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8042 }
8043 fillInProcMemInfo(proc, outInfo);
8044 }
8045 }
8046
8047 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008048 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008049 if (checkCallingPermission(android.Manifest.permission.DUMP)
8050 != PackageManager.PERMISSION_GRANTED) {
8051 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8052 + Binder.getCallingPid()
8053 + ", uid=" + Binder.getCallingUid()
8054 + " without permission "
8055 + android.Manifest.permission.DUMP);
8056 return;
8057 }
8058
8059 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008060 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008061 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008062
8063 int opti = 0;
8064 while (opti < args.length) {
8065 String opt = args[opti];
8066 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8067 break;
8068 }
8069 opti++;
8070 if ("-a".equals(opt)) {
8071 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008072 } else if ("-c".equals(opt)) {
8073 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008074 } else if ("-h".equals(opt)) {
8075 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008076 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008077 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008078 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008079 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8080 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8081 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008082 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008083 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008084 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008085 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008086 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008087 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008088 pw.println(" all: dump all activities");
8089 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008090 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008091 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8092 pw.println(" a partial substring in a component name, a");
8093 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008094 pw.println(" -a: include all available server state.");
8095 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008096 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008097 } else {
8098 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008100 }
8101
8102 // Is the caller requesting to dump a particular piece of data?
8103 if (opti < args.length) {
8104 String cmd = args[opti];
8105 opti++;
8106 if ("activities".equals(cmd) || "a".equals(cmd)) {
8107 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008108 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008110 return;
8111 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008112 String[] newArgs;
8113 String name;
8114 if (opti >= args.length) {
8115 name = null;
8116 newArgs = EMPTY_STRING_ARRAY;
8117 } else {
8118 name = args[opti];
8119 opti++;
8120 newArgs = new String[args.length - opti];
8121 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8122 args.length - opti);
8123 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008124 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008125 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008126 }
8127 return;
8128 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008129 String[] newArgs;
8130 String name;
8131 if (opti >= args.length) {
8132 name = null;
8133 newArgs = EMPTY_STRING_ARRAY;
8134 } else {
8135 name = args[opti];
8136 opti++;
8137 newArgs = new String[args.length - opti];
8138 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8139 args.length - opti);
8140 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008141 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008142 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008143 }
8144 return;
8145 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008146 String[] newArgs;
8147 String name;
8148 if (opti >= args.length) {
8149 name = null;
8150 newArgs = EMPTY_STRING_ARRAY;
8151 } else {
8152 name = args[opti];
8153 opti++;
8154 newArgs = new String[args.length - opti];
8155 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8156 args.length - opti);
8157 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008158 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008159 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008160 }
8161 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008162 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8163 synchronized (this) {
8164 dumpOomLocked(fd, pw, args, opti, true);
8165 }
8166 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008167 } else if ("provider".equals(cmd)) {
8168 String[] newArgs;
8169 String name;
8170 if (opti >= args.length) {
8171 name = null;
8172 newArgs = EMPTY_STRING_ARRAY;
8173 } else {
8174 name = args[opti];
8175 opti++;
8176 newArgs = new String[args.length - opti];
8177 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8178 }
8179 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8180 pw.println("No providers match: " + name);
8181 pw.println("Use -h for help.");
8182 }
8183 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008184 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8185 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008186 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008187 }
8188 return;
8189 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008190 String[] newArgs;
8191 String name;
8192 if (opti >= args.length) {
8193 name = null;
8194 newArgs = EMPTY_STRING_ARRAY;
8195 } else {
8196 name = args[opti];
8197 opti++;
8198 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008199 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8200 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008201 }
8202 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8203 pw.println("No services match: " + name);
8204 pw.println("Use -h for help.");
8205 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008206 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008207 } else if ("package".equals(cmd)) {
8208 String[] newArgs;
8209 if (opti >= args.length) {
8210 pw.println("package: no package name specified");
8211 pw.println("Use -h for help.");
8212 return;
8213 } else {
8214 dumpPackage = args[opti];
8215 opti++;
8216 newArgs = new String[args.length - opti];
8217 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8218 args.length - opti);
8219 args = newArgs;
8220 opti = 0;
8221 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008222 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8223 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008224 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008225 }
8226 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008227 } else {
8228 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008229 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8230 pw.println("Bad activity command, or no activities match: " + cmd);
8231 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008232 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008233 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008234 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008235 }
8236
8237 // No piece of data specified, dump everything.
8238 synchronized (this) {
8239 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008240 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008241 if (needSep) {
8242 pw.println(" ");
8243 }
8244 if (dumpAll) {
8245 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008246 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008247 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008248 if (needSep) {
8249 pw.println(" ");
8250 }
8251 if (dumpAll) {
8252 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008253 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008254 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008255 if (needSep) {
8256 pw.println(" ");
8257 }
8258 if (dumpAll) {
8259 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008260 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008261 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008262 if (needSep) {
8263 pw.println(" ");
8264 }
8265 if (dumpAll) {
8266 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008267 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008268 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008269 if (needSep) {
8270 pw.println(" ");
8271 }
8272 if (dumpAll) {
8273 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008274 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008275 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008276 }
8277 }
8278
8279 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008280 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008281 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8282 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008283 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8284 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008285 pw.println(" ");
8286 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008287 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8288 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008289 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008291 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008292 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008293 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008294 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008295 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008297 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008298 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008299 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008300 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008301 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8302 pw.println(" ");
8303 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008304 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008305 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008306 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008307 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008308 pw.println(" ");
8309 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008310 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008311 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008313
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008314 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008315 if (mMainStack.mPausingActivity != null) {
8316 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008317 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008318 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008319 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008320 if (dumpAll) {
8321 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8322 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008323 pw.println(" mDismissKeyguardOnNextActivity: "
8324 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008326
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008327 if (mRecentTasks.size() > 0) {
8328 pw.println();
8329 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008330
8331 final int N = mRecentTasks.size();
8332 for (int i=0; i<N; i++) {
8333 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008334 if (dumpPackage != null) {
8335 if (tr.realActivity == null ||
8336 !dumpPackage.equals(tr.realActivity)) {
8337 continue;
8338 }
8339 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008340 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8341 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008342 if (dumpAll) {
8343 mRecentTasks.get(i).dump(pw, " ");
8344 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008345 }
8346 }
8347
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008348 if (dumpAll) {
8349 pw.println(" ");
8350 pw.println(" mCurTask: " + mCurTask);
8351 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008352
8353 return true;
8354 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008355
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008356 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008357 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008358 boolean needSep = false;
8359 int numPers = 0;
8360
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008361 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8362
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008363 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008364 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8365 final int NA = procs.size();
8366 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008367 ProcessRecord r = procs.valueAt(ia);
8368 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8369 continue;
8370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008371 if (!needSep) {
8372 pw.println(" All known processes:");
8373 needSep = true;
8374 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008375 pw.print(r.persistent ? " *PERS*" : " *APP*");
8376 pw.print(" UID "); pw.print(procs.keyAt(ia));
8377 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008378 r.dump(pw, " ");
8379 if (r.persistent) {
8380 numPers++;
8381 }
8382 }
8383 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008384 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008385
8386 if (mIsolatedProcesses.size() > 0) {
8387 if (needSep) pw.println(" ");
8388 needSep = true;
8389 pw.println(" Isolated process list (sorted by uid):");
8390 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8391 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8392 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8393 continue;
8394 }
8395 pw.println(String.format("%sIsolated #%2d: %s",
8396 " ", i, r.toString()));
8397 }
8398 }
8399
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008400 if (mLruProcesses.size() > 0) {
8401 if (needSep) pw.println(" ");
8402 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008403 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008404 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008405 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008406 needSep = true;
8407 }
8408
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008409 if (dumpAll) {
8410 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008411 boolean printed = false;
8412 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8413 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8414 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8415 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008416 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008417 if (!printed) {
8418 if (needSep) pw.println(" ");
8419 needSep = true;
8420 pw.println(" PID mappings:");
8421 printed = true;
8422 }
8423 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8424 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008425 }
8426 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008427 }
8428
8429 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008430 synchronized (mPidsSelfLocked) {
8431 boolean printed = false;
8432 for (int i=0; i<mForegroundProcesses.size(); i++) {
8433 ProcessRecord r = mPidsSelfLocked.get(
8434 mForegroundProcesses.valueAt(i).pid);
8435 if (dumpPackage != null && (r == null
8436 || !dumpPackage.equals(r.info.packageName))) {
8437 continue;
8438 }
8439 if (!printed) {
8440 if (needSep) pw.println(" ");
8441 needSep = true;
8442 pw.println(" Foreground Processes:");
8443 printed = true;
8444 }
8445 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8446 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008448 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008449 }
8450
8451 if (mPersistentStartingProcesses.size() > 0) {
8452 if (needSep) pw.println(" ");
8453 needSep = true;
8454 pw.println(" Persisent processes that are starting:");
8455 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008456 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008459 if (mRemovedProcesses.size() > 0) {
8460 if (needSep) pw.println(" ");
8461 needSep = true;
8462 pw.println(" Processes that are being removed:");
8463 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008464 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008465 }
8466
8467 if (mProcessesOnHold.size() > 0) {
8468 if (needSep) pw.println(" ");
8469 needSep = true;
8470 pw.println(" Processes that are on old until the system is ready:");
8471 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008472 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008474
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008475 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008476
8477 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008478 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008479 long now = SystemClock.uptimeMillis();
8480 for (Map.Entry<String, SparseArray<Long>> procs
8481 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008482 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008483 SparseArray<Long> uids = procs.getValue();
8484 final int N = uids.size();
8485 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008486 int puid = uids.keyAt(i);
8487 ProcessRecord r = mProcessNames.get(pname, puid);
8488 if (dumpPackage != null && (r == null
8489 || !dumpPackage.equals(r.info.packageName))) {
8490 continue;
8491 }
8492 if (!printed) {
8493 if (needSep) pw.println(" ");
8494 needSep = true;
8495 pw.println(" Time since processes crashed:");
8496 printed = true;
8497 }
8498 pw.print(" Process "); pw.print(pname);
8499 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008500 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008501 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8502 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008503 }
8504 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008507 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008508 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008509 for (Map.Entry<String, SparseArray<Long>> procs
8510 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008511 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008512 SparseArray<Long> uids = procs.getValue();
8513 final int N = uids.size();
8514 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008515 int puid = uids.keyAt(i);
8516 ProcessRecord r = mProcessNames.get(pname, puid);
8517 if (dumpPackage != null && (r == null
8518 || !dumpPackage.equals(r.info.packageName))) {
8519 continue;
8520 }
8521 if (!printed) {
8522 if (needSep) pw.println(" ");
8523 needSep = true;
8524 pw.println(" Bad processes:");
8525 }
8526 pw.print(" Bad process "); pw.print(pname);
8527 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008528 pw.print(": crashed at time ");
8529 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 }
8531 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008534 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008535 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008536 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008537 if (dumpAll) {
8538 StringBuilder sb = new StringBuilder(128);
8539 sb.append(" mPreviousProcessVisibleTime: ");
8540 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8541 pw.println(sb);
8542 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008543 if (mHeavyWeightProcess != null) {
8544 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8545 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008546 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008547 if (dumpAll) {
8548 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008549 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008550 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008551 for (Map.Entry<String, Integer> entry
8552 : mCompatModePackages.getPackages().entrySet()) {
8553 String pkg = entry.getKey();
8554 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008555 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8556 continue;
8557 }
8558 if (!printed) {
8559 pw.println(" mScreenCompatPackages:");
8560 printed = true;
8561 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008562 pw.print(" "); pw.print(pkg); pw.print(": ");
8563 pw.print(mode); pw.println();
8564 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008565 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008566 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008567 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8568 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8569 || mOrigWaitForDebugger) {
8570 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8571 + " mDebugTransient=" + mDebugTransient
8572 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8573 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008574 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8575 || mProfileFd != null) {
8576 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8577 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8578 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8579 + mAutoStopProfiler);
8580 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008581 if (mAlwaysFinishActivities || mController != null) {
8582 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8583 + " mController=" + mController);
8584 }
8585 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008586 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008588 + " mProcessesReady=" + mProcessesReady
8589 + " mSystemReady=" + mSystemReady);
8590 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 + " mBooted=" + mBooted
8592 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008593 pw.print(" mLastPowerCheckRealtime=");
8594 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8595 pw.println("");
8596 pw.print(" mLastPowerCheckUptime=");
8597 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8598 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008599 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8600 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008601 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008602 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8603 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008604 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008605
8606 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008607 }
8608
Dianne Hackborn287952c2010-09-22 22:34:31 -07008609 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008610 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008611 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008612 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008613 long now = SystemClock.uptimeMillis();
8614 for (int i=0; i<mProcessesToGc.size(); i++) {
8615 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008616 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8617 continue;
8618 }
8619 if (!printed) {
8620 if (needSep) pw.println(" ");
8621 needSep = true;
8622 pw.println(" Processes that are waiting to GC:");
8623 printed = true;
8624 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008625 pw.print(" Process "); pw.println(proc);
8626 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8627 pw.print(", last gced=");
8628 pw.print(now-proc.lastRequestedGc);
8629 pw.print(" ms ago, last lowMem=");
8630 pw.print(now-proc.lastLowMemory);
8631 pw.println(" ms ago");
8632
8633 }
8634 }
8635 return needSep;
8636 }
8637
8638 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8639 int opti, boolean dumpAll) {
8640 boolean needSep = false;
8641
8642 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008643 if (needSep) pw.println(" ");
8644 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008645 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008646 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008647 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008648 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8649 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8650 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8651 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8652 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008653 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008654 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008655 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008656 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008657 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008658 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008659
8660 if (needSep) pw.println(" ");
8661 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008662 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008663 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008664 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008665 needSep = true;
8666 }
8667
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008668 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008669
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008670 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008671 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008672 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008673 if (mHeavyWeightProcess != null) {
8674 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8675 }
8676
8677 return true;
8678 }
8679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 /**
8681 * There are three ways to call this:
8682 * - no service specified: dump all the services
8683 * - a flattened component name that matched an existing service was specified as the
8684 * first arg: dump that one service
8685 * - the first arg isn't the flattened component name of an existing service:
8686 * dump all services whose component contains the first arg as a substring
8687 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008688 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8689 int opti, boolean dumpAll) {
8690 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008691
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008692 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008693 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008694 try {
8695 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8696 for (UserInfo user : users) {
8697 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8698 services.add(r1);
8699 }
8700 }
8701 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008702 }
8703 }
8704 } else {
8705 ComponentName componentName = name != null
8706 ? ComponentName.unflattenFromString(name) : null;
8707 int objectId = 0;
8708 if (componentName == null) {
8709 // Not a '/' separated full component name; maybe an object ID?
8710 try {
8711 objectId = Integer.parseInt(name, 16);
8712 name = null;
8713 componentName = null;
8714 } catch (RuntimeException e) {
8715 }
8716 }
8717
8718 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008719 try {
8720 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8721 for (UserInfo user : users) {
8722 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8723 if (componentName != null) {
8724 if (r1.name.equals(componentName)) {
8725 services.add(r1);
8726 }
8727 } else if (name != null) {
8728 if (r1.name.flattenToString().contains(name)) {
8729 services.add(r1);
8730 }
8731 } else if (System.identityHashCode(r1) == objectId) {
8732 services.add(r1);
8733 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008734 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008735 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008736 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 }
8738 }
8739 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008740
8741 if (services.size() <= 0) {
8742 return false;
8743 }
8744
8745 boolean needSep = false;
8746 for (int i=0; i<services.size(); i++) {
8747 if (needSep) {
8748 pw.println();
8749 }
8750 needSep = true;
8751 dumpService("", fd, pw, services.get(i), args, dumpAll);
8752 }
8753 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008754 }
8755
8756 /**
8757 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8758 * there is a thread associated with the service.
8759 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008760 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8761 final ServiceRecord r, String[] args, boolean dumpAll) {
8762 String innerPrefix = prefix + " ";
8763 synchronized (this) {
8764 pw.print(prefix); pw.print("SERVICE ");
8765 pw.print(r.shortName); pw.print(" ");
8766 pw.print(Integer.toHexString(System.identityHashCode(r)));
8767 pw.print(" pid=");
8768 if (r.app != null) pw.println(r.app.pid);
8769 else pw.println("(not running)");
8770 if (dumpAll) {
8771 r.dump(pw, innerPrefix);
8772 }
8773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008775 pw.print(prefix); pw.println(" Client:");
8776 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008777 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008778 TransferPipe tp = new TransferPipe();
8779 try {
8780 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8781 tp.setBufferPrefix(prefix + " ");
8782 tp.go(fd);
8783 } finally {
8784 tp.kill();
8785 }
8786 } catch (IOException e) {
8787 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008789 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008790 }
8791 }
8792 }
8793
Marco Nelissen18cb2872011-11-15 11:19:53 -08008794 /**
8795 * There are three ways to call this:
8796 * - no provider specified: dump all the providers
8797 * - a flattened component name that matched an existing provider was specified as the
8798 * first arg: dump that one provider
8799 * - the first arg isn't the flattened component name of an existing provider:
8800 * dump all providers whose component contains the first arg as a substring
8801 */
8802 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8803 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008804 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008805 }
8806
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008807 static class ItemMatcher {
8808 ArrayList<ComponentName> components;
8809 ArrayList<String> strings;
8810 ArrayList<Integer> objects;
8811 boolean all;
8812
8813 ItemMatcher() {
8814 all = true;
8815 }
8816
8817 void build(String name) {
8818 ComponentName componentName = ComponentName.unflattenFromString(name);
8819 if (componentName != null) {
8820 if (components == null) {
8821 components = new ArrayList<ComponentName>();
8822 }
8823 components.add(componentName);
8824 all = false;
8825 } else {
8826 int objectId = 0;
8827 // Not a '/' separated full component name; maybe an object ID?
8828 try {
8829 objectId = Integer.parseInt(name, 16);
8830 if (objects == null) {
8831 objects = new ArrayList<Integer>();
8832 }
8833 objects.add(objectId);
8834 all = false;
8835 } catch (RuntimeException e) {
8836 // Not an integer; just do string match.
8837 if (strings == null) {
8838 strings = new ArrayList<String>();
8839 }
8840 strings.add(name);
8841 all = false;
8842 }
8843 }
8844 }
8845
8846 int build(String[] args, int opti) {
8847 for (; opti<args.length; opti++) {
8848 String name = args[opti];
8849 if ("--".equals(name)) {
8850 return opti+1;
8851 }
8852 build(name);
8853 }
8854 return opti;
8855 }
8856
8857 boolean match(Object object, ComponentName comp) {
8858 if (all) {
8859 return true;
8860 }
8861 if (components != null) {
8862 for (int i=0; i<components.size(); i++) {
8863 if (components.get(i).equals(comp)) {
8864 return true;
8865 }
8866 }
8867 }
8868 if (objects != null) {
8869 for (int i=0; i<objects.size(); i++) {
8870 if (System.identityHashCode(object) == objects.get(i)) {
8871 return true;
8872 }
8873 }
8874 }
8875 if (strings != null) {
8876 String flat = comp.flattenToString();
8877 for (int i=0; i<strings.size(); i++) {
8878 if (flat.contains(strings.get(i))) {
8879 return true;
8880 }
8881 }
8882 }
8883 return false;
8884 }
8885 }
8886
Dianne Hackborn625ac272010-09-17 18:29:22 -07008887 /**
8888 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008889 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07008890 * - the cmd arg isn't the flattened component name of an existing activity:
8891 * dump all activity whose component contains the cmd as a substring
8892 * - A hex number of the ActivityRecord object instance.
8893 */
8894 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8895 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008896 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008897
8898 if ("all".equals(name)) {
8899 synchronized (this) {
8900 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008901 activities.add(r1);
8902 }
8903 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07008904 } else if ("top".equals(name)) {
8905 synchronized (this) {
8906 final int N = mMainStack.mHistory.size();
8907 if (N > 0) {
8908 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
8909 }
8910 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008911 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008912 ItemMatcher matcher = new ItemMatcher();
8913 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008914
8915 synchronized (this) {
8916 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008917 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008918 activities.add(r1);
8919 }
8920 }
8921 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008922 }
8923
8924 if (activities.size() <= 0) {
8925 return false;
8926 }
8927
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008928 String[] newArgs = new String[args.length - opti];
8929 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8930
Dianne Hackborn30d71892010-12-11 10:37:55 -08008931 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008932 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08008933 for (int i=activities.size()-1; i>=0; i--) {
8934 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008935 if (needSep) {
8936 pw.println();
8937 }
8938 needSep = true;
8939 synchronized (this) {
8940 if (lastTask != r.task) {
8941 lastTask = r.task;
8942 pw.print("TASK "); pw.print(lastTask.affinity);
8943 pw.print(" id="); pw.println(lastTask.taskId);
8944 if (dumpAll) {
8945 lastTask.dump(pw, " ");
8946 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008947 }
8948 }
8949 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008950 }
8951 return true;
8952 }
8953
8954 /**
8955 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
8956 * there is a thread associated with the activity.
8957 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08008958 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008959 final ActivityRecord r, String[] args, boolean dumpAll) {
8960 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08008961 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008962 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
8963 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
8964 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08008965 if (r.app != null) pw.println(r.app.pid);
8966 else pw.println("(not running)");
8967 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008968 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008969 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008970 }
8971 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008972 // flush anything that is already in the PrintWriter since the thread is going
8973 // to write to the file descriptor directly
8974 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07008975 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008976 TransferPipe tp = new TransferPipe();
8977 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08008978 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
8979 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008980 tp.go(fd);
8981 } finally {
8982 tp.kill();
8983 }
8984 } catch (IOException e) {
8985 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008986 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008987 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008988 }
8989 }
8990 }
8991
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008992 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008993 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008994 boolean needSep = false;
8995
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008996 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008997 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008999 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009000 Iterator it = mRegisteredReceivers.values().iterator();
9001 while (it.hasNext()) {
9002 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009003 if (dumpPackage != null && (r.app == null ||
9004 !dumpPackage.equals(r.app.info.packageName))) {
9005 continue;
9006 }
9007 if (!printed) {
9008 pw.println(" Registered Receivers:");
9009 needSep = true;
9010 printed = true;
9011 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009012 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009013 r.dump(pw, " ");
9014 }
9015 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009016
9017 if (mReceiverResolver.dump(pw, needSep ?
9018 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9019 " ", dumpPackage, false)) {
9020 needSep = true;
9021 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009022 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009023
9024 for (BroadcastQueue q : mBroadcastQueues) {
9025 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009028 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009029
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009030 if (mStickyBroadcasts != null && dumpPackage == null) {
9031 if (needSep) {
9032 pw.println();
9033 }
9034 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009035 pw.println(" Sticky broadcasts:");
9036 StringBuilder sb = new StringBuilder(128);
9037 for (Map.Entry<String, ArrayList<Intent>> ent
9038 : mStickyBroadcasts.entrySet()) {
9039 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009040 if (dumpAll) {
9041 pw.println(":");
9042 ArrayList<Intent> intents = ent.getValue();
9043 final int N = intents.size();
9044 for (int i=0; i<N; i++) {
9045 sb.setLength(0);
9046 sb.append(" Intent: ");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009047 intents.get(i).toShortString(sb, false, true, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009048 pw.println(sb.toString());
9049 Bundle bundle = intents.get(i).getExtras();
9050 if (bundle != null) {
9051 pw.print(" ");
9052 pw.println(bundle.toString());
9053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009054 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009055 } else {
9056 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009057 }
9058 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009059 needSep = true;
9060 }
9061
9062 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009063 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009064 for (BroadcastQueue queue : mBroadcastQueues) {
9065 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9066 + queue.mBroadcastsScheduled);
9067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009068 pw.println(" mHandler:");
9069 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009070 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009071 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009072
9073 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009074 }
9075
Marco Nelissen18cb2872011-11-15 11:19:53 -08009076 /**
9077 * Prints a list of ServiceRecords (dumpsys activity services)
9078 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009079 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009080 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009081 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009082
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009083 ItemMatcher matcher = new ItemMatcher();
9084 matcher.build(args, opti);
9085
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009086 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009087 try {
9088 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9089 for (UserInfo user : users) {
9090 if (mServiceMap.getAllServices(user.id).size() > 0) {
9091 boolean printed = false;
9092 long nowReal = SystemClock.elapsedRealtime();
9093 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9094 user.id).iterator();
9095 needSep = false;
9096 while (it.hasNext()) {
9097 ServiceRecord r = it.next();
9098 if (!matcher.match(r, r.name)) {
9099 continue;
9100 }
9101 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9102 continue;
9103 }
9104 if (!printed) {
9105 pw.println(" Active services:");
9106 printed = true;
9107 }
9108 if (needSep) {
9109 pw.println();
9110 }
9111 pw.print(" * ");
9112 pw.println(r);
9113 if (dumpAll) {
9114 r.dump(pw, " ");
9115 needSep = true;
9116 } else {
9117 pw.print(" app=");
9118 pw.println(r.app);
9119 pw.print(" created=");
9120 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9121 pw.print(" started=");
9122 pw.print(r.startRequested);
9123 pw.print(" connections=");
9124 pw.println(r.connections.size());
9125 if (r.connections.size() > 0) {
9126 pw.println(" Connections:");
9127 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9128 for (int i = 0; i < clist.size(); i++) {
9129 ConnectionRecord conn = clist.get(i);
9130 pw.print(" ");
9131 pw.print(conn.binding.intent.intent.getIntent()
9132 .toShortString(false, false, false));
9133 pw.print(" -> ");
9134 ProcessRecord proc = conn.binding.client;
9135 pw.println(proc != null ? proc.toShortString() : "null");
9136 }
9137 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009138 }
9139 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009140 if (dumpClient && r.app != null && r.app.thread != null) {
9141 pw.println(" Client:");
9142 pw.flush();
9143 try {
9144 TransferPipe tp = new TransferPipe();
9145 try {
9146 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9147 r, args);
9148 tp.setBufferPrefix(" ");
9149 // Short timeout, since blocking here can
9150 // deadlock with the application.
9151 tp.go(fd, 2000);
9152 } finally {
9153 tp.kill();
9154 }
9155 } catch (IOException e) {
9156 pw.println(" Failure while dumping the service: " + e);
9157 } catch (RemoteException e) {
9158 pw.println(" Got a RemoteException while dumping the service");
9159 }
9160 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009161 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009162 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009163 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009165 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009166 } catch (RemoteException re) {
9167
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009170 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009171 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009172 for (int i=0; i<mPendingServices.size(); i++) {
9173 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009174 if (!matcher.match(r, r.name)) {
9175 continue;
9176 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009177 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9178 continue;
9179 }
9180 if (!printed) {
9181 if (needSep) pw.println(" ");
9182 needSep = true;
9183 pw.println(" Pending services:");
9184 printed = true;
9185 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009186 pw.print(" * Pending "); pw.println(r);
9187 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009188 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009189 needSep = true;
9190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009191
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009192 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009193 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009194 for (int i=0; i<mRestartingServices.size(); i++) {
9195 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009196 if (!matcher.match(r, r.name)) {
9197 continue;
9198 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009199 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9200 continue;
9201 }
9202 if (!printed) {
9203 if (needSep) pw.println(" ");
9204 needSep = true;
9205 pw.println(" Restarting services:");
9206 printed = true;
9207 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009208 pw.print(" * Restarting "); pw.println(r);
9209 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009210 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009211 needSep = true;
9212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009213
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009214 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009215 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009216 for (int i=0; i<mStoppingServices.size(); i++) {
9217 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009218 if (!matcher.match(r, r.name)) {
9219 continue;
9220 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009221 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9222 continue;
9223 }
9224 if (!printed) {
9225 if (needSep) pw.println(" ");
9226 needSep = true;
9227 pw.println(" Stopping services:");
9228 printed = true;
9229 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009230 pw.print(" * Stopping "); pw.println(r);
9231 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009232 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009233 needSep = true;
9234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009235
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009236 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009237 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009238 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009239 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009240 = mServiceConnections.values().iterator();
9241 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009242 ArrayList<ConnectionRecord> r = it.next();
9243 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009244 ConnectionRecord cr = r.get(i);
9245 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9246 continue;
9247 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009248 if (dumpPackage != null && (cr.binding.client == null
9249 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9250 continue;
9251 }
9252 if (!printed) {
9253 if (needSep) pw.println(" ");
9254 needSep = true;
9255 pw.println(" Connection bindings to services:");
9256 printed = true;
9257 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009258 pw.print(" * "); pw.println(cr);
9259 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009261 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009262 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009263 }
9264 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009265
9266 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009267 }
9268
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009269 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009270 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009271 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009272
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009273 ItemMatcher matcher = new ItemMatcher();
9274 matcher.build(args, opti);
9275
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009276 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009277
9278 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009279
9280 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009281 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009282 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009283 ContentProviderRecord r = mLaunchingProviders.get(i);
9284 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9285 continue;
9286 }
9287 if (!printed) {
9288 if (needSep) pw.println(" ");
9289 needSep = true;
9290 pw.println(" Launching content providers:");
9291 printed = true;
9292 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009293 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009294 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009295 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009296 }
9297
9298 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009299 if (needSep) pw.println();
9300 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009301 pw.println("Granted Uri Permissions:");
9302 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9303 int uid = mGrantedUriPermissions.keyAt(i);
9304 HashMap<Uri, UriPermission> perms
9305 = mGrantedUriPermissions.valueAt(i);
9306 pw.print(" * UID "); pw.print(uid);
9307 pw.println(" holds:");
9308 for (UriPermission perm : perms.values()) {
9309 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009310 if (dumpAll) {
9311 perm.dump(pw, " ");
9312 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009313 }
9314 }
9315 needSep = true;
9316 }
9317
9318 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009319 }
9320
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009321 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009322 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009323 boolean needSep = false;
9324
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009325 if (mIntentSenderRecords.size() > 0) {
9326 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009327 Iterator<WeakReference<PendingIntentRecord>> it
9328 = mIntentSenderRecords.values().iterator();
9329 while (it.hasNext()) {
9330 WeakReference<PendingIntentRecord> ref = it.next();
9331 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009332 if (dumpPackage != null && (rec == null
9333 || !dumpPackage.equals(rec.key.packageName))) {
9334 continue;
9335 }
9336 if (!printed) {
9337 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9338 printed = true;
9339 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009340 needSep = true;
9341 if (rec != null) {
9342 pw.print(" * "); pw.println(rec);
9343 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009344 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009345 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009346 } else {
9347 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009348 }
9349 }
9350 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009351
9352 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353 }
9354
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009355 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009356 String prefix, String label, boolean complete, boolean brief, boolean client,
9357 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009358 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009359 boolean needNL = false;
9360 final String innerPrefix = prefix + " ";
9361 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009362 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009363 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009364 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9365 continue;
9366 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009367 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009368 if (needNL) {
9369 pw.println(" ");
9370 needNL = false;
9371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009372 if (lastTask != r.task) {
9373 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009374 pw.print(prefix);
9375 pw.print(full ? "* " : " ");
9376 pw.println(lastTask);
9377 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009378 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009379 } else if (complete) {
9380 // Complete + brief == give a summary. Isn't that obvious?!?
9381 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009382 pw.print(prefix); pw.print(" ");
9383 pw.println(lastTask.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009384 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009386 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009387 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9388 pw.print(" #"); pw.print(i); pw.print(": ");
9389 pw.println(r);
9390 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009391 r.dump(pw, innerPrefix);
9392 } else if (complete) {
9393 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009394 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009395 if (r.app != null) {
9396 pw.print(innerPrefix); pw.println(r.app);
9397 }
9398 }
9399 if (client && r.app != null && r.app.thread != null) {
9400 // flush anything that is already in the PrintWriter since the thread is going
9401 // to write to the file descriptor directly
9402 pw.flush();
9403 try {
9404 TransferPipe tp = new TransferPipe();
9405 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009406 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9407 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009408 // Short timeout, since blocking here can
9409 // deadlock with the application.
9410 tp.go(fd, 2000);
9411 } finally {
9412 tp.kill();
9413 }
9414 } catch (IOException e) {
9415 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9416 } catch (RemoteException e) {
9417 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9418 }
9419 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009421 }
9422 }
9423
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009424 private static String buildOomTag(String prefix, String space, int val, int base) {
9425 if (val == base) {
9426 if (space == null) return prefix;
9427 return prefix + " ";
9428 }
9429 return prefix + "+" + Integer.toString(val-base);
9430 }
9431
9432 private static final int dumpProcessList(PrintWriter pw,
9433 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009434 String prefix, String normalLabel, String persistentLabel,
9435 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009437 final int N = list.size()-1;
9438 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009439 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009440 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9441 continue;
9442 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009443 pw.println(String.format("%s%s #%2d: %s",
9444 prefix, (r.persistent ? persistentLabel : normalLabel),
9445 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009446 if (r.persistent) {
9447 numPers++;
9448 }
9449 }
9450 return numPers;
9451 }
9452
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009453 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009454 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009455 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009456 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009457
Dianne Hackborn905577f2011-09-07 18:31:28 -07009458 ArrayList<Pair<ProcessRecord, Integer>> list
9459 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9460 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009461 ProcessRecord r = origList.get(i);
9462 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9463 continue;
9464 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009465 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9466 }
9467
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009468 if (list.size() <= 0) {
9469 return false;
9470 }
9471
Dianne Hackborn905577f2011-09-07 18:31:28 -07009472 Comparator<Pair<ProcessRecord, Integer>> comparator
9473 = new Comparator<Pair<ProcessRecord, Integer>>() {
9474 @Override
9475 public int compare(Pair<ProcessRecord, Integer> object1,
9476 Pair<ProcessRecord, Integer> object2) {
9477 if (object1.first.setAdj != object2.first.setAdj) {
9478 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9479 }
9480 if (object1.second.intValue() != object2.second.intValue()) {
9481 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9482 }
9483 return 0;
9484 }
9485 };
9486
9487 Collections.sort(list, comparator);
9488
Dianne Hackborn287952c2010-09-22 22:34:31 -07009489 final long curRealtime = SystemClock.elapsedRealtime();
9490 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9491 final long curUptime = SystemClock.uptimeMillis();
9492 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9493
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009494 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009495 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009496 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009497 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009498 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009499 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9500 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009501 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9502 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009503 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9504 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009505 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9506 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009507 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009508 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009509 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9510 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9511 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9512 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9513 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9514 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9515 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9516 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009517 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9518 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009519 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9520 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009521 } else {
9522 oomAdj = Integer.toString(r.setAdj);
9523 }
9524 String schedGroup;
9525 switch (r.setSchedGroup) {
9526 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9527 schedGroup = "B";
9528 break;
9529 case Process.THREAD_GROUP_DEFAULT:
9530 schedGroup = "F";
9531 break;
9532 default:
9533 schedGroup = Integer.toString(r.setSchedGroup);
9534 break;
9535 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009536 String foreground;
9537 if (r.foregroundActivities) {
9538 foreground = "A";
9539 } else if (r.foregroundServices) {
9540 foreground = "S";
9541 } else {
9542 foreground = " ";
9543 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009544 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009545 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009546 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9547 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009548 if (r.adjSource != null || r.adjTarget != null) {
9549 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009550 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009551 if (r.adjTarget instanceof ComponentName) {
9552 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9553 } else if (r.adjTarget != null) {
9554 pw.print(r.adjTarget.toString());
9555 } else {
9556 pw.print("{null}");
9557 }
9558 pw.print("<=");
9559 if (r.adjSource instanceof ProcessRecord) {
9560 pw.print("Proc{");
9561 pw.print(((ProcessRecord)r.adjSource).toShortString());
9562 pw.println("}");
9563 } else if (r.adjSource != null) {
9564 pw.println(r.adjSource.toString());
9565 } else {
9566 pw.println("{null}");
9567 }
9568 }
9569 if (inclDetails) {
9570 pw.print(prefix);
9571 pw.print(" ");
9572 pw.print("oom: max="); pw.print(r.maxAdj);
9573 pw.print(" hidden="); pw.print(r.hiddenAdj);
9574 pw.print(" curRaw="); pw.print(r.curRawAdj);
9575 pw.print(" setRaw="); pw.print(r.setRawAdj);
9576 pw.print(" cur="); pw.print(r.curAdj);
9577 pw.print(" set="); pw.println(r.setAdj);
9578 pw.print(prefix);
9579 pw.print(" ");
9580 pw.print("keeping="); pw.print(r.keeping);
9581 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009582 pw.print(" empty="); pw.print(r.empty);
9583 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009584
9585 if (!r.keeping) {
9586 if (r.lastWakeTime != 0) {
9587 long wtime;
9588 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9589 synchronized (stats) {
9590 wtime = stats.getProcessWakeTime(r.info.uid,
9591 r.pid, curRealtime);
9592 }
9593 long timeUsed = wtime - r.lastWakeTime;
9594 pw.print(prefix);
9595 pw.print(" ");
9596 pw.print("keep awake over ");
9597 TimeUtils.formatDuration(realtimeSince, pw);
9598 pw.print(" used ");
9599 TimeUtils.formatDuration(timeUsed, pw);
9600 pw.print(" (");
9601 pw.print((timeUsed*100)/realtimeSince);
9602 pw.println("%)");
9603 }
9604 if (r.lastCpuTime != 0) {
9605 long timeUsed = r.curCpuTime - r.lastCpuTime;
9606 pw.print(prefix);
9607 pw.print(" ");
9608 pw.print("run cpu over ");
9609 TimeUtils.formatDuration(uptimeSince, pw);
9610 pw.print(" used ");
9611 TimeUtils.formatDuration(timeUsed, pw);
9612 pw.print(" (");
9613 pw.print((timeUsed*100)/uptimeSince);
9614 pw.println("%)");
9615 }
9616 }
9617 }
9618 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009619 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009620 }
9621
Dianne Hackbornb437e092011-08-05 17:50:29 -07009622 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009623 ArrayList<ProcessRecord> procs;
9624 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009625 if (args != null && args.length > start
9626 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009627 procs = new ArrayList<ProcessRecord>();
9628 int pid = -1;
9629 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009630 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009631 } catch (NumberFormatException e) {
9632
9633 }
9634 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9635 ProcessRecord proc = mLruProcesses.get(i);
9636 if (proc.pid == pid) {
9637 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009638 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009639 procs.add(proc);
9640 }
9641 }
9642 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009643 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009644 return null;
9645 }
9646 } else {
9647 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9648 }
9649 }
9650 return procs;
9651 }
9652
9653 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9654 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009655 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009656 if (procs == null) {
9657 return;
9658 }
9659
9660 long uptime = SystemClock.uptimeMillis();
9661 long realtime = SystemClock.elapsedRealtime();
9662 pw.println("Applications Graphics Acceleration Info:");
9663 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9664
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009665 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9666 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009667 if (r.thread != null) {
9668 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9669 pw.flush();
9670 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009671 TransferPipe tp = new TransferPipe();
9672 try {
9673 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9674 tp.go(fd);
9675 } finally {
9676 tp.kill();
9677 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009678 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009679 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009680 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009681 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009682 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009683 pw.flush();
9684 }
9685 }
9686 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009687 }
9688
Jeff Brown6754ba22011-12-14 20:20:01 -08009689 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9690 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9691 if (procs == null) {
9692 return;
9693 }
9694
9695 pw.println("Applications Database Info:");
9696
9697 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9698 ProcessRecord r = procs.get(i);
9699 if (r.thread != null) {
9700 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9701 pw.flush();
9702 try {
9703 TransferPipe tp = new TransferPipe();
9704 try {
9705 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9706 tp.go(fd);
9707 } finally {
9708 tp.kill();
9709 }
9710 } catch (IOException e) {
9711 pw.println("Failure while dumping the app: " + r);
9712 pw.flush();
9713 } catch (RemoteException e) {
9714 pw.println("Got a RemoteException while dumping the app " + r);
9715 pw.flush();
9716 }
9717 }
9718 }
9719 }
9720
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009721 final static class MemItem {
9722 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009723 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009724 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009725 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009726 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009727
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009728 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009729 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009730 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009731 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009732 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009733 }
9734 }
9735
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009736 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009737 boolean sort) {
9738 if (sort) {
9739 Collections.sort(items, new Comparator<MemItem>() {
9740 @Override
9741 public int compare(MemItem lhs, MemItem rhs) {
9742 if (lhs.pss < rhs.pss) {
9743 return 1;
9744 } else if (lhs.pss > rhs.pss) {
9745 return -1;
9746 }
9747 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009748 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009749 });
9750 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009751
9752 for (int i=0; i<items.size(); i++) {
9753 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009754 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009755 if (mi.subitems != null) {
9756 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9757 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009758 }
9759 }
9760
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009761 // These are in KB.
9762 static final long[] DUMP_MEM_BUCKETS = new long[] {
9763 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9764 120*1024, 160*1024, 200*1024,
9765 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9766 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9767 };
9768
Dianne Hackborn672342c2011-11-29 11:29:02 -08009769 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9770 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009771 int start = label.lastIndexOf('.');
9772 if (start >= 0) start++;
9773 else start = 0;
9774 int end = label.length();
9775 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9776 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9777 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9778 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009779 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009780 out.append(label, start, end);
9781 return;
9782 }
9783 }
9784 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009785 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009786 out.append(label, start, end);
9787 }
9788
9789 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9790 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9791 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9792 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9793 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9794 };
9795 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9796 "System", "Persistent", "Foreground",
9797 "Visible", "Perceptible", "Heavy Weight",
9798 "Backup", "A Services", "Home", "Previous",
9799 "B Services", "Background"
9800 };
9801
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009802 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009803 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009804 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009805 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009806 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009807
9808 int opti = 0;
9809 while (opti < args.length) {
9810 String opt = args[opti];
9811 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9812 break;
9813 }
9814 opti++;
9815 if ("-a".equals(opt)) {
9816 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009817 } else if ("--oom".equals(opt)) {
9818 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009819 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009820 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009821 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009822 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009823 pw.println("If [process] is specified it can be the name or ");
9824 pw.println("pid of a specific process to dump.");
9825 return;
9826 } else {
9827 pw.println("Unknown argument: " + opt + "; use -h for help");
9828 }
9829 }
9830
9831 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009832 if (procs == null) {
9833 return;
9834 }
9835
Dianne Hackborn6447ca32009-04-07 19:50:08 -07009836 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009837 long uptime = SystemClock.uptimeMillis();
9838 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -07009839
9840 if (procs.size() == 1 || isCheckinRequest) {
9841 dumpAll = true;
9842 }
9843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009844 if (isCheckinRequest) {
9845 // short checkin version
9846 pw.println(uptime + "," + realtime);
9847 pw.flush();
9848 } else {
9849 pw.println("Applications Memory Usage (kB):");
9850 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9851 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009852
Dianne Hackbornb437e092011-08-05 17:50:29 -07009853 String[] innerArgs = new String[args.length-opti];
9854 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
9855
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009856 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
9857 long nativePss=0, dalvikPss=0, otherPss=0;
9858 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
9859
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009860 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
9861 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
9862 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -07009863
9864 long totalPss = 0;
9865
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009866 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9867 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009868 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009869 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009870 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
9871 pw.flush();
9872 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009873 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009874 if (dumpAll) {
9875 try {
9876 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
9877 } catch (RemoteException e) {
9878 if (!isCheckinRequest) {
9879 pw.println("Got RemoteException!");
9880 pw.flush();
9881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009882 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009883 } else {
9884 mi = new Debug.MemoryInfo();
9885 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009886 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009887
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009888 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009889 long myTotalPss = mi.getTotalPss();
9890 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009891 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009892 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009893 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009894
9895 nativePss += mi.nativePss;
9896 dalvikPss += mi.dalvikPss;
9897 otherPss += mi.otherPss;
9898 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
9899 long mem = mi.getOtherPss(j);
9900 miscPss[j] += mem;
9901 otherPss -= mem;
9902 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009903
9904 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009905 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
9906 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009907 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009908 if (oomProcs[oomIndex] == null) {
9909 oomProcs[oomIndex] = new ArrayList<MemItem>();
9910 }
9911 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009912 break;
9913 }
9914 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009916 }
9917 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009918
9919 if (!isCheckinRequest && procs.size() > 1) {
9920 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
9921
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009922 catMems.add(new MemItem("Native", "Native", nativePss, -1));
9923 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
9924 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009925 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009926 String label = Debug.MemoryInfo.getOtherLabel(j);
9927 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009928 }
9929
Dianne Hackbornb437e092011-08-05 17:50:29 -07009930 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
9931 for (int j=0; j<oomPss.length; j++) {
9932 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009933 String label = DUMP_MEM_OOM_LABEL[j];
9934 MemItem item = new MemItem(label, label, oomPss[j],
9935 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009936 item.subitems = oomProcs[j];
9937 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009938 }
9939 }
9940
Dianne Hackborn672342c2011-11-29 11:29:02 -08009941 if (outTag != null || outStack != null) {
9942 if (outTag != null) {
9943 appendMemBucket(outTag, totalPss, "total", false);
9944 }
9945 if (outStack != null) {
9946 appendMemBucket(outStack, totalPss, "total", true);
9947 }
9948 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009949 for (int i=0; i<oomMems.size(); i++) {
9950 MemItem miCat = oomMems.get(i);
9951 if (miCat.subitems == null || miCat.subitems.size() < 1) {
9952 continue;
9953 }
9954 if (miCat.id < ProcessList.SERVICE_ADJ
9955 || miCat.id == ProcessList.HOME_APP_ADJ
9956 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009957 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
9958 outTag.append(" / ");
9959 }
9960 if (outStack != null) {
9961 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
9962 if (firstLine) {
9963 outStack.append(":");
9964 firstLine = false;
9965 }
9966 outStack.append("\n\t at ");
9967 } else {
9968 outStack.append("$");
9969 }
9970 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009971 for (int j=0; j<miCat.subitems.size(); j++) {
9972 MemItem mi = miCat.subitems.get(j);
9973 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009974 if (outTag != null) {
9975 outTag.append(" ");
9976 }
9977 if (outStack != null) {
9978 outStack.append("$");
9979 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009980 }
Dianne Hackborn672342c2011-11-29 11:29:02 -08009981 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
9982 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
9983 }
9984 if (outStack != null) {
9985 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
9986 }
9987 }
9988 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
9989 outStack.append("(");
9990 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
9991 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
9992 outStack.append(DUMP_MEM_OOM_LABEL[k]);
9993 outStack.append(":");
9994 outStack.append(DUMP_MEM_OOM_ADJ[k]);
9995 }
9996 }
9997 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009998 }
9999 }
10000 }
10001 }
10002
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010003 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010004 pw.println();
10005 pw.println("Total PSS by process:");
10006 dumpMemItems(pw, " ", procMems, true);
10007 pw.println();
10008 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010009 pw.println("Total PSS by OOM adjustment:");
10010 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010011 if (!oomOnly) {
10012 PrintWriter out = categoryPw != null ? categoryPw : pw;
10013 out.println();
10014 out.println("Total PSS by category:");
10015 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010016 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010017 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010018 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010020 }
10021
10022 /**
10023 * Searches array of arguments for the specified string
10024 * @param args array of argument strings
10025 * @param value value to search for
10026 * @return true if the value is contained in the array
10027 */
10028 private static boolean scanArgs(String[] args, String value) {
10029 if (args != null) {
10030 for (String arg : args) {
10031 if (value.equals(arg)) {
10032 return true;
10033 }
10034 }
10035 }
10036 return false;
10037 }
10038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010039 private final void killServicesLocked(ProcessRecord app,
10040 boolean allowRestart) {
10041 // Report disconnected services.
10042 if (false) {
10043 // XXX we are letting the client link to the service for
10044 // death notifications.
10045 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010046 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010047 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010048 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010049 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010050 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010051 = r.connections.values().iterator();
10052 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010053 ArrayList<ConnectionRecord> cl = jt.next();
10054 for (int i=0; i<cl.size(); i++) {
10055 ConnectionRecord c = cl.get(i);
10056 if (c.binding.client != app) {
10057 try {
10058 //c.conn.connected(r.className, null);
10059 } catch (Exception e) {
10060 // todo: this should be asynchronous!
10061 Slog.w(TAG, "Exception thrown disconnected servce "
10062 + r.shortName
10063 + " from app " + app.processName, e);
10064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010065 }
10066 }
10067 }
10068 }
10069 }
10070 }
10071 }
10072
10073 // Clean up any connections this application has to other services.
10074 if (app.connections.size() > 0) {
10075 Iterator<ConnectionRecord> it = app.connections.iterator();
10076 while (it.hasNext()) {
10077 ConnectionRecord r = it.next();
10078 removeConnectionLocked(r, app, null);
10079 }
10080 }
10081 app.connections.clear();
10082
10083 if (app.services.size() != 0) {
10084 // Any services running in the application need to be placed
10085 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010086 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010087 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010088 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010089 synchronized (sr.stats.getBatteryStats()) {
10090 sr.stats.stopLaunchedLocked();
10091 }
10092 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010093 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010094 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010095 if (mStoppingServices.remove(sr)) {
10096 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10097 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010098
10099 boolean hasClients = sr.bindings.size() > 0;
10100 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010101 Iterator<IntentBindRecord> bindings
10102 = sr.bindings.values().iterator();
10103 while (bindings.hasNext()) {
10104 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010105 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010106 + ": shouldUnbind=" + b.hasBound);
10107 b.binder = null;
10108 b.requested = b.received = b.hasBound = false;
10109 }
10110 }
10111
Dianne Hackborn070783f2010-12-29 16:46:28 -080010112 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10113 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010114 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010115 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010116 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010117 sr.crashCount, sr.shortName, app.pid);
10118 bringDownServiceLocked(sr, true);
10119 } else if (!allowRestart) {
10120 bringDownServiceLocked(sr, true);
10121 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010122 boolean canceled = scheduleServiceRestartLocked(sr, true);
10123
10124 // Should the service remain running? Note that in the
10125 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010126 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010127 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10128 if (sr.pendingStarts.size() == 0) {
10129 sr.startRequested = false;
10130 if (!hasClients) {
10131 // Whoops, no reason to restart!
10132 bringDownServiceLocked(sr, true);
10133 }
10134 }
10135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010136 }
10137 }
10138
10139 if (!allowRestart) {
10140 app.services.clear();
10141 }
10142 }
10143
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010144 // Make sure we have no more records on the stopping list.
10145 int i = mStoppingServices.size();
10146 while (i > 0) {
10147 i--;
10148 ServiceRecord sr = mStoppingServices.get(i);
10149 if (sr.app == app) {
10150 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010151 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010152 }
10153 }
10154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010155 app.executingServices.clear();
10156 }
10157
10158 private final void removeDyingProviderLocked(ProcessRecord proc,
10159 ContentProviderRecord cpr) {
10160 synchronized (cpr) {
10161 cpr.launchingApp = null;
10162 cpr.notifyAll();
10163 }
10164
Amith Yamasani742a6712011-05-04 14:49:28 -070010165 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010166 String names[] = cpr.info.authority.split(";");
10167 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010168 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010169 }
10170
10171 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10172 while (cit.hasNext()) {
10173 ProcessRecord capp = cit.next();
10174 if (!capp.persistent && capp.thread != null
10175 && capp.pid != 0
10176 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010177 Slog.i(TAG, "Kill " + capp.processName
10178 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010179 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010180 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010181 capp.processName, capp.setAdj, "dying provider "
10182 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010183 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010184 }
10185 }
10186
10187 mLaunchingProviders.remove(cpr);
10188 }
10189
10190 /**
10191 * Main code for cleaning up a process when it has gone away. This is
10192 * called both as a result of the process dying, or directly when stopping
10193 * a process when running in single process mode.
10194 */
10195 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010196 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010197 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010198 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010199 }
10200
Dianne Hackborn36124872009-10-08 16:22:03 -070010201 mProcessesToGc.remove(app);
10202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010203 // Dismiss any open dialogs.
10204 if (app.crashDialog != null) {
10205 app.crashDialog.dismiss();
10206 app.crashDialog = null;
10207 }
10208 if (app.anrDialog != null) {
10209 app.anrDialog.dismiss();
10210 app.anrDialog = null;
10211 }
10212 if (app.waitDialog != null) {
10213 app.waitDialog.dismiss();
10214 app.waitDialog = null;
10215 }
10216
10217 app.crashing = false;
10218 app.notResponding = false;
10219
10220 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010221 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010222 app.thread = null;
10223 app.forcingToForeground = null;
10224 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010225 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010226 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010227 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010228
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010229 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010230
10231 boolean restart = false;
10232
10233 int NL = mLaunchingProviders.size();
10234
10235 // Remove published content providers.
10236 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010237 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010238 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010239 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010240 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010241 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010242
10243 // See if someone is waiting for this provider... in which
10244 // case we don't remove it, but just let it restart.
10245 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010246 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010247 for (; i<NL; i++) {
10248 if (mLaunchingProviders.get(i) == cpr) {
10249 restart = true;
10250 break;
10251 }
10252 }
10253 } else {
10254 i = NL;
10255 }
10256
10257 if (i >= NL) {
10258 removeDyingProviderLocked(app, cpr);
10259 NL = mLaunchingProviders.size();
10260 }
10261 }
10262 app.pubProviders.clear();
10263 }
10264
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010265 // Take care of any launching providers waiting for this process.
10266 if (checkAppInLaunchingProvidersLocked(app, false)) {
10267 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010268 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010270 // Unregister from connected content providers.
10271 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010272 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010273 while (it.hasNext()) {
10274 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10275 cpr.clients.remove(app);
10276 }
10277 app.conProviders.clear();
10278 }
10279
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010280 // At this point there may be remaining entries in mLaunchingProviders
10281 // where we were the only one waiting, so they are no longer of use.
10282 // Look for these and clean up if found.
10283 // XXX Commented out for now. Trying to figure out a way to reproduce
10284 // the actual situation to identify what is actually going on.
10285 if (false) {
10286 for (int i=0; i<NL; i++) {
10287 ContentProviderRecord cpr = (ContentProviderRecord)
10288 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010289 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010290 synchronized (cpr) {
10291 cpr.launchingApp = null;
10292 cpr.notifyAll();
10293 }
10294 }
10295 }
10296 }
10297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010298 skipCurrentReceiverLocked(app);
10299
10300 // Unregister any receivers.
10301 if (app.receivers.size() > 0) {
10302 Iterator<ReceiverList> it = app.receivers.iterator();
10303 while (it.hasNext()) {
10304 removeReceiverLocked(it.next());
10305 }
10306 app.receivers.clear();
10307 }
10308
Christopher Tate181fafa2009-05-14 11:12:14 -070010309 // If the app is undergoing backup, tell the backup manager about it
10310 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010311 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010312 try {
10313 IBackupManager bm = IBackupManager.Stub.asInterface(
10314 ServiceManager.getService(Context.BACKUP_SERVICE));
10315 bm.agentDisconnected(app.info.packageName);
10316 } catch (RemoteException e) {
10317 // can't happen; backup manager is local
10318 }
10319 }
10320
Jeff Sharkey287bd832011-05-28 19:36:26 -070010321 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010323 // If the caller is restarting this app, then leave it in its
10324 // current lists and let the caller take care of it.
10325 if (restarting) {
10326 return;
10327 }
10328
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010329 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010330 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010331 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010332 mProcessNames.remove(app.processName, app.uid);
10333 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010334 if (mHeavyWeightProcess == app) {
10335 mHeavyWeightProcess = null;
10336 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010338 } else if (!app.removed) {
10339 // This app is persistent, so we need to keep its record around.
10340 // If it is not already on the pending app list, add it there
10341 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010342 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10343 mPersistentStartingProcesses.add(app);
10344 restart = true;
10345 }
10346 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010347 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10348 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010349 mProcessesOnHold.remove(app);
10350
The Android Open Source Project4df24232009-03-05 14:34:35 -080010351 if (app == mHomeProcess) {
10352 mHomeProcess = null;
10353 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010354 if (app == mPreviousProcess) {
10355 mPreviousProcess = null;
10356 }
10357
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010358 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010359 // We have components that still need to be running in the
10360 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010361 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010362 startProcessLocked(app, "restart", app.processName);
10363 } else if (app.pid > 0 && app.pid != MY_PID) {
10364 // Goodbye!
10365 synchronized (mPidsSelfLocked) {
10366 mPidsSelfLocked.remove(app.pid);
10367 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10368 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010369 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010370 }
10371 }
10372
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010373 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10374 // Look through the content providers we are waiting to have launched,
10375 // and if any run in this process then either schedule a restart of
10376 // the process or kill the client waiting for it if this process has
10377 // gone bad.
10378 int NL = mLaunchingProviders.size();
10379 boolean restart = false;
10380 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010381 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010382 if (cpr.launchingApp == app) {
10383 if (!alwaysBad && !app.bad) {
10384 restart = true;
10385 } else {
10386 removeDyingProviderLocked(app, cpr);
10387 NL = mLaunchingProviders.size();
10388 }
10389 }
10390 }
10391 return restart;
10392 }
10393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010394 // =========================================================
10395 // SERVICES
10396 // =========================================================
10397
10398 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10399 ActivityManager.RunningServiceInfo info =
10400 new ActivityManager.RunningServiceInfo();
10401 info.service = r.name;
10402 if (r.app != null) {
10403 info.pid = r.app.pid;
10404 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010405 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010406 info.process = r.processName;
10407 info.foreground = r.isForeground;
10408 info.activeSince = r.createTime;
10409 info.started = r.startRequested;
10410 info.clientCount = r.connections.size();
10411 info.crashCount = r.crashCount;
10412 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010413 if (r.isForeground) {
10414 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10415 }
10416 if (r.startRequested) {
10417 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10418 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010419 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010420 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10421 }
10422 if (r.app != null && r.app.persistent) {
10423 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10424 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010425
10426 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10427 for (int i=0; i<connl.size(); i++) {
10428 ConnectionRecord conn = connl.get(i);
10429 if (conn.clientLabel != 0) {
10430 info.clientPackage = conn.binding.client.info.packageName;
10431 info.clientLabel = conn.clientLabel;
10432 return info;
10433 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010434 }
10435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010436 return info;
10437 }
10438
10439 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10440 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010441 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010442 synchronized (this) {
10443 ArrayList<ActivityManager.RunningServiceInfo> res
10444 = new ArrayList<ActivityManager.RunningServiceInfo>();
10445
Amith Yamasani742a6712011-05-04 14:49:28 -070010446 int userId = UserId.getUserId(Binder.getCallingUid());
10447 if (mServiceMap.getAllServices(userId).size() > 0) {
10448 Iterator<ServiceRecord> it
10449 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010450 while (it.hasNext() && res.size() < maxNum) {
10451 res.add(makeRunningServiceInfoLocked(it.next()));
10452 }
10453 }
10454
10455 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10456 ServiceRecord r = mRestartingServices.get(i);
10457 ActivityManager.RunningServiceInfo info =
10458 makeRunningServiceInfoLocked(r);
10459 info.restarting = r.nextRestartTime;
10460 res.add(info);
10461 }
10462
10463 return res;
10464 }
10465 }
10466
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010467 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010468 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010469 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010470 int userId = UserId.getUserId(Binder.getCallingUid());
10471 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010472 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010473 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10474 for (int i=0; i<conn.size(); i++) {
10475 if (conn.get(i).clientIntent != null) {
10476 return conn.get(i).clientIntent;
10477 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010478 }
10479 }
10480 }
10481 }
10482 return null;
10483 }
10484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010485 private final ServiceRecord findServiceLocked(ComponentName name,
10486 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010487 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010488 return r == token ? r : null;
10489 }
10490
10491 private final class ServiceLookupResult {
10492 final ServiceRecord record;
10493 final String permission;
10494
10495 ServiceLookupResult(ServiceRecord _record, String _permission) {
10496 record = _record;
10497 permission = _permission;
10498 }
10499 };
10500
10501 private ServiceLookupResult findServiceLocked(Intent service,
10502 String resolvedType) {
10503 ServiceRecord r = null;
10504 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010505 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010506 }
10507 if (r == null) {
10508 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070010509 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010510 }
10511
10512 if (r == null) {
10513 try {
10514 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010515 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010516 service, resolvedType, 0);
10517 ServiceInfo sInfo =
10518 rInfo != null ? rInfo.serviceInfo : null;
10519 if (sInfo == null) {
10520 return null;
10521 }
10522
10523 ComponentName name = new ComponentName(
10524 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010525 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010526 } catch (RemoteException ex) {
10527 // pm is in same process, this will never happen.
10528 }
10529 }
10530 if (r != null) {
10531 int callingPid = Binder.getCallingPid();
10532 int callingUid = Binder.getCallingUid();
10533 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010534 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010535 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010536 if (!r.exported) {
10537 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10538 + " from pid=" + callingPid
10539 + ", uid=" + callingUid
10540 + " that is not exported from uid " + r.appInfo.uid);
10541 return new ServiceLookupResult(null, "not exported from uid "
10542 + r.appInfo.uid);
10543 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010544 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010545 + " from pid=" + callingPid
10546 + ", uid=" + callingUid
10547 + " requires " + r.permission);
10548 return new ServiceLookupResult(null, r.permission);
10549 }
10550 return new ServiceLookupResult(r, null);
10551 }
10552 return null;
10553 }
10554
10555 private class ServiceRestarter implements Runnable {
10556 private ServiceRecord mService;
10557
10558 void setService(ServiceRecord service) {
10559 mService = service;
10560 }
10561
10562 public void run() {
10563 synchronized(ActivityManagerService.this) {
10564 performServiceRestartLocked(mService);
10565 }
10566 }
10567 }
10568
10569 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010570 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010571 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010572 if (DEBUG_SERVICE)
10573 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010574 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010576 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010577 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010578 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010579 if (r == null) {
10580 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010581 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010583 if (r == null) {
10584 try {
10585 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010586 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010587 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010588 ServiceInfo sInfo =
10589 rInfo != null ? rInfo.serviceInfo : null;
10590 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010591 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010592 ": not found");
10593 return null;
10594 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010595 if (userId > 0) {
10596 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010598 ComponentName name = new ComponentName(
10599 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010600 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010601 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010602 Intent.FilterComparison filter = new Intent.FilterComparison(
10603 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010604 ServiceRestarter res = new ServiceRestarter();
10605 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10606 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10607 synchronized (stats) {
10608 ss = stats.getServiceStatsLocked(
10609 sInfo.applicationInfo.uid, sInfo.packageName,
10610 sInfo.name);
10611 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010612 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010613 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010614 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10615 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010616
10617 // Make sure this component isn't in the pending list.
10618 int N = mPendingServices.size();
10619 for (int i=0; i<N; i++) {
10620 ServiceRecord pr = mPendingServices.get(i);
10621 if (pr.name.equals(name)) {
10622 mPendingServices.remove(i);
10623 i--;
10624 N--;
10625 }
10626 }
10627 }
10628 } catch (RemoteException ex) {
10629 // pm is in same process, this will never happen.
10630 }
10631 }
10632 if (r != null) {
10633 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010634 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010635 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010636 if (!r.exported) {
10637 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10638 + " from pid=" + callingPid
10639 + ", uid=" + callingUid
10640 + " that is not exported from uid " + r.appInfo.uid);
10641 return new ServiceLookupResult(null, "not exported from uid "
10642 + r.appInfo.uid);
10643 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010644 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010645 + " from pid=" + callingPid
10646 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010647 + " requires " + r.permission);
10648 return new ServiceLookupResult(null, r.permission);
10649 }
10650 return new ServiceLookupResult(r, null);
10651 }
10652 return null;
10653 }
10654
Dianne Hackborn287952c2010-09-22 22:34:31 -070010655 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10656 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10657 + why + " of " + r + " in app " + r.app);
10658 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10659 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010660 long now = SystemClock.uptimeMillis();
10661 if (r.executeNesting == 0 && r.app != null) {
10662 if (r.app.executingServices.size() == 0) {
10663 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10664 msg.obj = r.app;
10665 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10666 }
10667 r.app.executingServices.add(r);
10668 }
10669 r.executeNesting++;
10670 r.executingStart = now;
10671 }
10672
10673 private final void sendServiceArgsLocked(ServiceRecord r,
10674 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010675 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010676 if (N == 0) {
10677 return;
10678 }
10679
Dianne Hackborn39792d22010-08-19 18:01:52 -070010680 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010681 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010682 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010683 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10684 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010685 if (si.intent == null && N > 1) {
10686 // If somehow we got a dummy null intent in the middle,
10687 // then skip it. DO NOT skip a null intent when it is
10688 // the only one in the list -- this is to support the
10689 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010690 continue;
10691 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010692 si.deliveredTime = SystemClock.uptimeMillis();
10693 r.deliveredStarts.add(si);
10694 si.deliveryCount++;
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010695 if (si.targetPermissionUid >= 0 && si.intent != null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010696 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -070010697 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010698 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010699 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010700 if (!oomAdjusted) {
10701 oomAdjusted = true;
10702 updateOomAdjLocked(r.app);
10703 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010704 int flags = 0;
10705 if (si.deliveryCount > 0) {
10706 flags |= Service.START_FLAG_RETRY;
10707 }
10708 if (si.doneExecutingCount > 0) {
10709 flags |= Service.START_FLAG_REDELIVERY;
10710 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010711 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010712 } catch (RemoteException e) {
10713 // Remote process gone... we'll let the normal cleanup take
10714 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010715 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010716 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010717 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010718 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010719 break;
10720 }
10721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010722 }
10723
10724 private final boolean requestServiceBindingLocked(ServiceRecord r,
10725 IntentBindRecord i, boolean rebind) {
10726 if (r.app == null || r.app.thread == null) {
10727 // If service is not currently running, can't yet bind.
10728 return false;
10729 }
10730 if ((!i.requested || rebind) && i.apps.size() > 0) {
10731 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010732 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010733 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10734 if (!rebind) {
10735 i.requested = true;
10736 }
10737 i.hasBound = true;
10738 i.doRebind = false;
10739 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010740 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010741 return false;
10742 }
10743 }
10744 return true;
10745 }
10746
10747 private final void requestServiceBindingsLocked(ServiceRecord r) {
10748 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10749 while (bindings.hasNext()) {
10750 IntentBindRecord i = bindings.next();
10751 if (!requestServiceBindingLocked(r, i, false)) {
10752 break;
10753 }
10754 }
10755 }
10756
10757 private final void realStartServiceLocked(ServiceRecord r,
10758 ProcessRecord app) throws RemoteException {
10759 if (app.thread == null) {
10760 throw new RemoteException();
10761 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010762 if (DEBUG_MU)
10763 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010764 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010765 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010766 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010767
10768 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010769 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010770 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771
10772 boolean created = false;
10773 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010774 mStringBuilder.setLength(0);
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010775 r.intent.getIntent().toShortString(mStringBuilder, true, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010776 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010777 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010778 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010779 synchronized (r.stats.getBatteryStats()) {
10780 r.stats.startLaunchedLocked();
10781 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010782 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010783 app.thread.scheduleCreateService(r, r.serviceInfo,
10784 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010785 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010786 created = true;
10787 } finally {
10788 if (!created) {
10789 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010790 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010791 }
10792 }
10793
10794 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010795
10796 // If the service is in the started state, and there are no
10797 // pending arguments, then fake up one so its onStartCommand() will
10798 // be called.
10799 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010800 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
10801 null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010802 }
10803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010804 sendServiceArgsLocked(r, true);
10805 }
10806
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010807 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10808 boolean allowCancel) {
10809 boolean canceled = false;
10810
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010811 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010812 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010813 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010814
Dianne Hackborn070783f2010-12-29 16:46:28 -080010815 if ((r.serviceInfo.applicationInfo.flags
10816 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10817 minDuration /= 4;
10818 }
10819
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010820 // Any delivered but not yet finished starts should be put back
10821 // on the pending list.
10822 final int N = r.deliveredStarts.size();
10823 if (N > 0) {
10824 for (int i=N-1; i>=0; i--) {
10825 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070010826 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010827 if (si.intent == null) {
10828 // We'll generate this again if needed.
10829 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
10830 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
10831 r.pendingStarts.add(0, si);
10832 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
10833 dur *= 2;
10834 if (minDuration < dur) minDuration = dur;
10835 if (resetTime < dur) resetTime = dur;
10836 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010837 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010838 + r.name);
10839 canceled = true;
10840 }
10841 }
10842 r.deliveredStarts.clear();
10843 }
10844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845 r.totalRestartCount++;
10846 if (r.restartDelay == 0) {
10847 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010848 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010849 } else {
10850 // If it has been a "reasonably long time" since the service
10851 // was started, then reset our restart duration back to
10852 // the beginning, so we don't infinitely increase the duration
10853 // on a service that just occasionally gets killed (which is
10854 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010855 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010856 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010857 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010858 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080010859 if ((r.serviceInfo.applicationInfo.flags
10860 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10861 // Services in peristent processes will restart much more
10862 // quickly, since they are pretty important. (Think SystemUI).
10863 r.restartDelay += minDuration/2;
10864 } else {
10865 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
10866 if (r.restartDelay < minDuration) {
10867 r.restartDelay = minDuration;
10868 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010870 }
10871 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010872
10873 r.nextRestartTime = now + r.restartDelay;
10874
10875 // Make sure that we don't end up restarting a bunch of services
10876 // all at the same time.
10877 boolean repeat;
10878 do {
10879 repeat = false;
10880 for (int i=mRestartingServices.size()-1; i>=0; i--) {
10881 ServiceRecord r2 = mRestartingServices.get(i);
10882 if (r2 != r && r.nextRestartTime
10883 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
10884 && r.nextRestartTime
10885 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
10886 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
10887 r.restartDelay = r.nextRestartTime - now;
10888 repeat = true;
10889 break;
10890 }
10891 }
10892 } while (repeat);
10893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 if (!mRestartingServices.contains(r)) {
10895 mRestartingServices.add(r);
10896 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010897
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010898 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010900 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010901 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010902 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010903 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010904 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080010905 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010906 r.shortName, r.restartDelay);
10907
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010908 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010909 }
10910
10911 final void performServiceRestartLocked(ServiceRecord r) {
10912 if (!mRestartingServices.contains(r)) {
10913 return;
10914 }
10915 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
10916 }
10917
10918 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
10919 if (r.restartDelay == 0) {
10920 return false;
10921 }
10922 r.resetRestartCounter();
10923 mRestartingServices.remove(r);
10924 mHandler.removeCallbacks(r.restarter);
10925 return true;
10926 }
10927
10928 private final boolean bringUpServiceLocked(ServiceRecord r,
10929 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010930 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010931 //r.dump(" ");
10932
Dianne Hackborn36124872009-10-08 16:22:03 -070010933 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010934 sendServiceArgsLocked(r, false);
10935 return true;
10936 }
10937
10938 if (!whileRestarting && r.restartDelay > 0) {
10939 // If waiting for a restart, then do nothing.
10940 return true;
10941 }
10942
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010943 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010944
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010945 // We are now bringing the service up, so no longer in the
10946 // restarting state.
10947 mRestartingServices.remove(r);
10948
Dianne Hackborne7f97212011-02-24 14:40:20 -080010949 // Service is now being launched, its package can't be stopped.
10950 try {
10951 AppGlobals.getPackageManager().setPackageStoppedState(
10952 r.packageName, false);
10953 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010954 } catch (IllegalArgumentException e) {
10955 Slog.w(TAG, "Failed trying to unstop package "
10956 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010957 }
10958
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010959 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010961 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010962
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010963 if (!isolated) {
10964 app = getProcessRecordLocked(appName, r.appInfo.uid);
10965 if (DEBUG_MU)
10966 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
10967 if (app != null && app.thread != null) {
10968 try {
10969 app.addPackage(r.appInfo.packageName);
10970 realStartServiceLocked(r, app);
10971 return true;
10972 } catch (RemoteException e) {
10973 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
10974 }
10975
10976 // If a dead object exception was thrown -- fall through to
10977 // restart the application.
10978 }
10979 } else {
10980 // If this service runs in an isolated process, then each time
10981 // we call startProcessLocked() we will get a new isolated
10982 // process, starting another process if we are currently waiting
10983 // for a previous process to come up. To deal with this, we store
10984 // in the service any current isolated process it is running in or
10985 // waiting to have come up.
10986 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010987 }
10988
Dianne Hackborn36124872009-10-08 16:22:03 -070010989 // Not running -- get it started, and enqueue this service record
10990 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010991 if (app == null) {
10992 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
10993 "service", r.name, false, isolated)) == null) {
10994 Slog.w(TAG, "Unable to launch app "
10995 + r.appInfo.packageName + "/"
10996 + r.appInfo.uid + " for service "
10997 + r.intent.getIntent() + ": process is bad");
10998 bringDownServiceLocked(r, true);
10999 return false;
11000 }
11001 if (isolated) {
11002 r.isolatedProc = app;
11003 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011004 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011006 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011007 mPendingServices.add(r);
11008 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011010 return true;
11011 }
11012
11013 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011014 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011015 //r.dump(" ");
11016
11017 // Does it still need to run?
11018 if (!force && r.startRequested) {
11019 return;
11020 }
11021 if (r.connections.size() > 0) {
11022 if (!force) {
11023 // XXX should probably keep a count of the number of auto-create
11024 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011025 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011026 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011027 ArrayList<ConnectionRecord> cr = it.next();
11028 for (int i=0; i<cr.size(); i++) {
11029 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11030 return;
11031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011032 }
11033 }
11034 }
11035
11036 // Report to all of the connections that the service is no longer
11037 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011038 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011040 ArrayList<ConnectionRecord> c = it.next();
11041 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011042 ConnectionRecord cr = c.get(i);
11043 // There is still a connection to the service that is
11044 // being brought down. Mark it as dead.
11045 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011046 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011047 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011048 } catch (Exception e) {
11049 Slog.w(TAG, "Failure disconnecting service " + r.name +
11050 " to connection " + c.get(i).conn.asBinder() +
11051 " (in " + c.get(i).binding.client.processName + ")", e);
11052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011053 }
11054 }
11055 }
11056
11057 // Tell the service that it has been unbound.
11058 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11059 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11060 while (it.hasNext()) {
11061 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011062 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011063 + ": hasBound=" + ibr.hasBound);
11064 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11065 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011066 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011067 updateOomAdjLocked(r.app);
11068 ibr.hasBound = false;
11069 r.app.thread.scheduleUnbindService(r,
11070 ibr.intent.getIntent());
11071 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011072 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011073 + r.shortName, e);
11074 serviceDoneExecutingLocked(r, true);
11075 }
11076 }
11077 }
11078 }
11079
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011080 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011081 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011082 System.identityHashCode(r), r.shortName,
11083 (r.app != null) ? r.app.pid : -1);
11084
Amith Yamasani742a6712011-05-04 14:49:28 -070011085 mServiceMap.removeServiceByName(r.name, r.userId);
11086 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011087 r.totalRestartCount = 0;
11088 unscheduleServiceRestartLocked(r);
11089
11090 // Also make sure it is not on the pending list.
11091 int N = mPendingServices.size();
11092 for (int i=0; i<N; i++) {
11093 if (mPendingServices.get(i) == r) {
11094 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011095 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011096 i--;
11097 N--;
11098 }
11099 }
11100
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011101 r.cancelNotification();
11102 r.isForeground = false;
11103 r.foregroundId = 0;
11104 r.foregroundNoti = null;
11105
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011106 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011107 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011108 r.pendingStarts.clear();
11109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011110 if (r.app != null) {
11111 synchronized (r.stats.getBatteryStats()) {
11112 r.stats.stopLaunchedLocked();
11113 }
11114 r.app.services.remove(r);
11115 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011116 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011117 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011118 mStoppingServices.add(r);
11119 updateOomAdjLocked(r.app);
11120 r.app.thread.scheduleStopService(r);
11121 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011122 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011123 + r.shortName, e);
11124 serviceDoneExecutingLocked(r, true);
11125 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011126 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011127 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011128 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011129 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011130 }
11131 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011132 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011133 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011134 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011135
11136 if (r.bindings.size() > 0) {
11137 r.bindings.clear();
11138 }
11139
11140 if (r.restarter instanceof ServiceRestarter) {
11141 ((ServiceRestarter)r.restarter).setService(null);
11142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011143 }
11144
11145 ComponentName startServiceLocked(IApplicationThread caller,
11146 Intent service, String resolvedType,
11147 int callingPid, int callingUid) {
11148 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011149 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011150 + " type=" + resolvedType + " args=" + service.getExtras());
11151
11152 if (caller != null) {
11153 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11154 if (callerApp == null) {
11155 throw new SecurityException(
11156 "Unable to find app for caller " + caller
11157 + " (pid=" + Binder.getCallingPid()
11158 + ") when starting service " + service);
11159 }
11160 }
11161
11162 ServiceLookupResult res =
11163 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011164 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 if (res == null) {
11166 return null;
11167 }
11168 if (res.record == null) {
11169 return new ComponentName("!", res.permission != null
11170 ? res.permission : "private to package");
11171 }
11172 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -070011173 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
11174 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011175 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011176 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011177 }
11178 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011179 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011180 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn39792d22010-08-19 18:01:52 -070011181 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011182 r.lastActivity = SystemClock.uptimeMillis();
11183 synchronized (r.stats.getBatteryStats()) {
11184 r.stats.startRunningLocked();
11185 }
11186 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11187 return new ComponentName("!", "Service process is bad");
11188 }
11189 return r.name;
11190 }
11191 }
11192
11193 public ComponentName startService(IApplicationThread caller, Intent service,
11194 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011195 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011196 // Refuse possible leaked file descriptors
11197 if (service != null && service.hasFileDescriptors() == true) {
11198 throw new IllegalArgumentException("File descriptors passed in Intent");
11199 }
11200
Amith Yamasani742a6712011-05-04 14:49:28 -070011201 if (DEBUG_SERVICE)
11202 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011203 synchronized(this) {
11204 final int callingPid = Binder.getCallingPid();
11205 final int callingUid = Binder.getCallingUid();
11206 final long origId = Binder.clearCallingIdentity();
11207 ComponentName res = startServiceLocked(caller, service,
11208 resolvedType, callingPid, callingUid);
11209 Binder.restoreCallingIdentity(origId);
11210 return res;
11211 }
11212 }
11213
11214 ComponentName startServiceInPackage(int uid,
11215 Intent service, String resolvedType) {
11216 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011217 if (DEBUG_SERVICE)
11218 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011219 final long origId = Binder.clearCallingIdentity();
11220 ComponentName res = startServiceLocked(null, service,
11221 resolvedType, -1, uid);
11222 Binder.restoreCallingIdentity(origId);
11223 return res;
11224 }
11225 }
11226
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011227 private void stopServiceLocked(ServiceRecord service) {
11228 synchronized (service.stats.getBatteryStats()) {
11229 service.stats.stopRunningLocked();
11230 }
11231 service.startRequested = false;
11232 service.callStart = false;
11233 bringDownServiceLocked(service, false);
11234 }
11235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011236 public int stopService(IApplicationThread caller, Intent service,
11237 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011238 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011239 // Refuse possible leaked file descriptors
11240 if (service != null && service.hasFileDescriptors() == true) {
11241 throw new IllegalArgumentException("File descriptors passed in Intent");
11242 }
11243
11244 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011245 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011246 + " type=" + resolvedType);
11247
11248 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11249 if (caller != null && callerApp == null) {
11250 throw new SecurityException(
11251 "Unable to find app for caller " + caller
11252 + " (pid=" + Binder.getCallingPid()
11253 + ") when stopping service " + service);
11254 }
11255
11256 // If this service is active, make sure it is stopped.
11257 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11258 if (r != null) {
11259 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011260 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011261 try {
11262 stopServiceLocked(r.record);
11263 } finally {
11264 Binder.restoreCallingIdentity(origId);
11265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011266 return 1;
11267 }
11268 return -1;
11269 }
11270 }
11271
11272 return 0;
11273 }
11274
11275 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011276 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011277 // Refuse possible leaked file descriptors
11278 if (service != null && service.hasFileDescriptors() == true) {
11279 throw new IllegalArgumentException("File descriptors passed in Intent");
11280 }
11281
11282 IBinder ret = null;
11283
11284 synchronized(this) {
11285 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11286
11287 if (r != null) {
11288 // r.record is null if findServiceLocked() failed the caller permission check
11289 if (r.record == null) {
11290 throw new SecurityException(
11291 "Permission Denial: Accessing service " + r.record.name
11292 + " from pid=" + Binder.getCallingPid()
11293 + ", uid=" + Binder.getCallingUid()
11294 + " requires " + r.permission);
11295 }
11296 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11297 if (ib != null) {
11298 ret = ib.binder;
11299 }
11300 }
11301 }
11302
11303 return ret;
11304 }
11305
11306 public boolean stopServiceToken(ComponentName className, IBinder token,
11307 int startId) {
11308 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011309 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011310 + " " + token + " startId=" + startId);
11311 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011312 if (r != null) {
11313 if (startId >= 0) {
11314 // Asked to only stop if done with all work. Note that
11315 // to avoid leaks, we will take this as dropping all
11316 // start items up to and including this one.
11317 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11318 if (si != null) {
11319 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011320 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11321 cur.removeUriPermissionsLocked();
11322 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011323 break;
11324 }
11325 }
11326 }
11327
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011328 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011329 return false;
11330 }
11331
11332 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011333 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011334 + " is last, but have " + r.deliveredStarts.size()
11335 + " remaining args");
11336 }
11337 }
11338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011339 synchronized (r.stats.getBatteryStats()) {
11340 r.stats.stopRunningLocked();
11341 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011342 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011343 }
11344 final long origId = Binder.clearCallingIdentity();
11345 bringDownServiceLocked(r, false);
11346 Binder.restoreCallingIdentity(origId);
11347 return true;
11348 }
11349 }
11350 return false;
11351 }
11352
11353 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011354 int id, Notification notification, boolean removeNotification) {
11355 final long origId = Binder.clearCallingIdentity();
11356 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011357 synchronized(this) {
11358 ServiceRecord r = findServiceLocked(className, token);
11359 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011360 if (id != 0) {
11361 if (notification == null) {
11362 throw new IllegalArgumentException("null notification");
11363 }
11364 if (r.foregroundId != id) {
11365 r.cancelNotification();
11366 r.foregroundId = id;
11367 }
11368 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11369 r.foregroundNoti = notification;
11370 r.isForeground = true;
11371 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011372 if (r.app != null) {
11373 updateServiceForegroundLocked(r.app, true);
11374 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011375 } else {
11376 if (r.isForeground) {
11377 r.isForeground = false;
11378 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011379 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011380 updateServiceForegroundLocked(r.app, true);
11381 }
11382 }
11383 if (removeNotification) {
11384 r.cancelNotification();
11385 r.foregroundId = 0;
11386 r.foregroundNoti = null;
11387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011388 }
11389 }
11390 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011391 } finally {
11392 Binder.restoreCallingIdentity(origId);
11393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011394 }
11395
11396 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11397 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011398 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011399 if (sr.isForeground) {
11400 anyForeground = true;
11401 break;
11402 }
11403 }
11404 if (anyForeground != proc.foregroundServices) {
11405 proc.foregroundServices = anyForeground;
11406 if (oomAdj) {
11407 updateOomAdjLocked();
11408 }
11409 }
11410 }
11411
11412 public int bindService(IApplicationThread caller, IBinder token,
11413 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011414 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011415 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011416 // Refuse possible leaked file descriptors
11417 if (service != null && service.hasFileDescriptors() == true) {
11418 throw new IllegalArgumentException("File descriptors passed in Intent");
11419 }
11420
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011421 checkValidCaller(Binder.getCallingUid(), userId);
11422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011423 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011424 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011425 + " type=" + resolvedType + " conn=" + connection.asBinder()
11426 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011427 if (DEBUG_MU)
11428 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11429 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011430 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11431 if (callerApp == null) {
11432 throw new SecurityException(
11433 "Unable to find app for caller " + caller
11434 + " (pid=" + Binder.getCallingPid()
11435 + ") when binding service " + service);
11436 }
11437
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011438 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011439 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011440 activity = mMainStack.isInStackLocked(token);
11441 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011442 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011443 return 0;
11444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011445 }
11446
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011447 int clientLabel = 0;
11448 PendingIntent clientIntent = null;
11449
11450 if (callerApp.info.uid == Process.SYSTEM_UID) {
11451 // Hacky kind of thing -- allow system stuff to tell us
11452 // what they are, so we can report this elsewhere for
11453 // others to know why certain services are running.
11454 try {
11455 clientIntent = (PendingIntent)service.getParcelableExtra(
11456 Intent.EXTRA_CLIENT_INTENT);
11457 } catch (RuntimeException e) {
11458 }
11459 if (clientIntent != null) {
11460 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11461 if (clientLabel != 0) {
11462 // There are no useful extras in the intent, trash them.
11463 // System code calling with this stuff just needs to know
11464 // this will happen.
11465 service = service.cloneFilter();
11466 }
11467 }
11468 }
11469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011470 ServiceLookupResult res =
11471 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011472 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 if (res == null) {
11474 return 0;
11475 }
11476 if (res.record == null) {
11477 return -1;
11478 }
11479 ServiceRecord s = res.record;
11480
11481 final long origId = Binder.clearCallingIdentity();
11482
11483 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011484 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011485 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011486 }
11487
11488 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11489 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011490 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011491
11492 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011493 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11494 if (clist == null) {
11495 clist = new ArrayList<ConnectionRecord>();
11496 s.connections.put(binder, clist);
11497 }
11498 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011499 b.connections.add(c);
11500 if (activity != null) {
11501 if (activity.connections == null) {
11502 activity.connections = new HashSet<ConnectionRecord>();
11503 }
11504 activity.connections.add(c);
11505 }
11506 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011507 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11508 b.client.hasAboveClient = true;
11509 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011510 clist = mServiceConnections.get(binder);
11511 if (clist == null) {
11512 clist = new ArrayList<ConnectionRecord>();
11513 mServiceConnections.put(binder, clist);
11514 }
11515 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011516
11517 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11518 s.lastActivity = SystemClock.uptimeMillis();
11519 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11520 return 0;
11521 }
11522 }
11523
11524 if (s.app != null) {
11525 // This could have made the service more important.
11526 updateOomAdjLocked(s.app);
11527 }
11528
Joe Onorato8a9b2202010-02-26 18:56:32 -080011529 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011530 + ": received=" + b.intent.received
11531 + " apps=" + b.intent.apps.size()
11532 + " doRebind=" + b.intent.doRebind);
11533
11534 if (s.app != null && b.intent.received) {
11535 // Service is already running, so we can immediately
11536 // publish the connection.
11537 try {
11538 c.conn.connected(s.name, b.intent.binder);
11539 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011540 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011541 + " to connection " + c.conn.asBinder()
11542 + " (in " + c.binding.client.processName + ")", e);
11543 }
11544
11545 // If this is the first app connected back to this binding,
11546 // and the service had previously asked to be told when
11547 // rebound, then do so.
11548 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11549 requestServiceBindingLocked(s, b.intent, true);
11550 }
11551 } else if (!b.intent.requested) {
11552 requestServiceBindingLocked(s, b.intent, false);
11553 }
11554
11555 Binder.restoreCallingIdentity(origId);
11556 }
11557
11558 return 1;
11559 }
11560
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011561 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011562 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011563 IBinder binder = c.conn.asBinder();
11564 AppBindRecord b = c.binding;
11565 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011566 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11567 if (clist != null) {
11568 clist.remove(c);
11569 if (clist.size() == 0) {
11570 s.connections.remove(binder);
11571 }
11572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011573 b.connections.remove(c);
11574 if (c.activity != null && c.activity != skipAct) {
11575 if (c.activity.connections != null) {
11576 c.activity.connections.remove(c);
11577 }
11578 }
11579 if (b.client != skipApp) {
11580 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011581 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11582 b.client.updateHasAboveClientLocked();
11583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011584 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011585 clist = mServiceConnections.get(binder);
11586 if (clist != null) {
11587 clist.remove(c);
11588 if (clist.size() == 0) {
11589 mServiceConnections.remove(binder);
11590 }
11591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011592
11593 if (b.connections.size() == 0) {
11594 b.intent.apps.remove(b.client);
11595 }
11596
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011597 if (!c.serviceDead) {
11598 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11599 + ": shouldUnbind=" + b.intent.hasBound);
11600 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11601 && b.intent.hasBound) {
11602 try {
11603 bumpServiceExecutingLocked(s, "unbind");
11604 updateOomAdjLocked(s.app);
11605 b.intent.hasBound = false;
11606 // Assume the client doesn't want to know about a rebind;
11607 // we will deal with that later if it asks for one.
11608 b.intent.doRebind = false;
11609 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11610 } catch (Exception e) {
11611 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11612 serviceDoneExecutingLocked(s, true);
11613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011614 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011615
11616 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11617 bringDownServiceLocked(s, false);
11618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011619 }
11620 }
11621
11622 public boolean unbindService(IServiceConnection connection) {
11623 synchronized (this) {
11624 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011625 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011626 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11627 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011628 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011629 + connection.asBinder());
11630 return false;
11631 }
11632
11633 final long origId = Binder.clearCallingIdentity();
11634
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011635 while (clist.size() > 0) {
11636 ConnectionRecord r = clist.get(0);
11637 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011638
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011639 if (r.binding.service.app != null) {
11640 // This could have made the service less important.
11641 updateOomAdjLocked(r.binding.service.app);
11642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011643 }
11644
11645 Binder.restoreCallingIdentity(origId);
11646 }
11647
11648 return true;
11649 }
11650
11651 public void publishService(IBinder token, Intent intent, IBinder service) {
11652 // Refuse possible leaked file descriptors
11653 if (intent != null && intent.hasFileDescriptors() == true) {
11654 throw new IllegalArgumentException("File descriptors passed in Intent");
11655 }
11656
11657 synchronized(this) {
11658 if (!(token instanceof ServiceRecord)) {
11659 throw new IllegalArgumentException("Invalid service token");
11660 }
11661 ServiceRecord r = (ServiceRecord)token;
11662
11663 final long origId = Binder.clearCallingIdentity();
11664
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011665 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011666 + " " + intent + ": " + service);
11667 if (r != null) {
11668 Intent.FilterComparison filter
11669 = new Intent.FilterComparison(intent);
11670 IntentBindRecord b = r.bindings.get(filter);
11671 if (b != null && !b.received) {
11672 b.binder = service;
11673 b.requested = true;
11674 b.received = true;
11675 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011676 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011677 = r.connections.values().iterator();
11678 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011679 ArrayList<ConnectionRecord> clist = it.next();
11680 for (int i=0; i<clist.size(); i++) {
11681 ConnectionRecord c = clist.get(i);
11682 if (!filter.equals(c.binding.intent.intent)) {
11683 if (DEBUG_SERVICE) Slog.v(
11684 TAG, "Not publishing to: " + c);
11685 if (DEBUG_SERVICE) Slog.v(
11686 TAG, "Bound intent: " + c.binding.intent.intent);
11687 if (DEBUG_SERVICE) Slog.v(
11688 TAG, "Published intent: " + intent);
11689 continue;
11690 }
11691 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11692 try {
11693 c.conn.connected(r.name, service);
11694 } catch (Exception e) {
11695 Slog.w(TAG, "Failure sending service " + r.name +
11696 " to connection " + c.conn.asBinder() +
11697 " (in " + c.binding.client.processName + ")", e);
11698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011699 }
11700 }
11701 }
11702 }
11703
11704 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11705
11706 Binder.restoreCallingIdentity(origId);
11707 }
11708 }
11709 }
11710
11711 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11712 // Refuse possible leaked file descriptors
11713 if (intent != null && intent.hasFileDescriptors() == true) {
11714 throw new IllegalArgumentException("File descriptors passed in Intent");
11715 }
11716
11717 synchronized(this) {
11718 if (!(token instanceof ServiceRecord)) {
11719 throw new IllegalArgumentException("Invalid service token");
11720 }
11721 ServiceRecord r = (ServiceRecord)token;
11722
11723 final long origId = Binder.clearCallingIdentity();
11724
11725 if (r != null) {
11726 Intent.FilterComparison filter
11727 = new Intent.FilterComparison(intent);
11728 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011729 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011730 + " at " + b + ": apps="
11731 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011732
11733 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011734 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011735 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011736 // Applications have already bound since the last
11737 // unbind, so just rebind right here.
11738 requestServiceBindingLocked(r, b, true);
11739 } else {
11740 // Note to tell the service the next time there is
11741 // a new client.
11742 b.doRebind = true;
11743 }
11744 }
11745
Per Edelberg78f9fff2010-08-30 20:01:35 +020011746 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011747
11748 Binder.restoreCallingIdentity(origId);
11749 }
11750 }
11751 }
11752
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011753 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011754 synchronized(this) {
11755 if (!(token instanceof ServiceRecord)) {
11756 throw new IllegalArgumentException("Invalid service token");
11757 }
11758 ServiceRecord r = (ServiceRecord)token;
11759 boolean inStopping = mStoppingServices.contains(token);
11760 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011761 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011762 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011763 + " with incorrect token: given " + token
11764 + ", expected " + r);
11765 return;
11766 }
11767
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011768 if (type == 1) {
11769 // This is a call from a service start... take care of
11770 // book-keeping.
11771 r.callStart = true;
11772 switch (res) {
11773 case Service.START_STICKY_COMPATIBILITY:
11774 case Service.START_STICKY: {
11775 // We are done with the associated start arguments.
11776 r.findDeliveredStart(startId, true);
11777 // Don't stop if killed.
11778 r.stopIfKilled = false;
11779 break;
11780 }
11781 case Service.START_NOT_STICKY: {
11782 // We are done with the associated start arguments.
11783 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011784 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011785 // There is no more work, and this service
11786 // doesn't want to hang around if killed.
11787 r.stopIfKilled = true;
11788 }
11789 break;
11790 }
11791 case Service.START_REDELIVER_INTENT: {
11792 // We'll keep this item until they explicitly
11793 // call stop for it, but keep track of the fact
11794 // that it was delivered.
11795 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11796 if (si != null) {
11797 si.deliveryCount = 0;
11798 si.doneExecutingCount++;
11799 // Don't stop if killed.
11800 r.stopIfKilled = true;
11801 }
11802 break;
11803 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011804 case Service.START_TASK_REMOVED_COMPLETE: {
11805 // Special processing for onTaskRemoved(). Don't
11806 // impact normal onStartCommand() processing.
11807 r.findDeliveredStart(startId, true);
11808 break;
11809 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011810 default:
11811 throw new IllegalArgumentException(
11812 "Unknown service start result: " + res);
11813 }
11814 if (res == Service.START_STICKY_COMPATIBILITY) {
11815 r.callStart = false;
11816 }
11817 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011818 if (DEBUG_MU)
11819 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
11820 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821 final long origId = Binder.clearCallingIdentity();
11822 serviceDoneExecutingLocked(r, inStopping);
11823 Binder.restoreCallingIdentity(origId);
11824 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011825 Slog.w(TAG, "Done executing unknown service from pid "
11826 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 }
11828 }
11829 }
11830
11831 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011832 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
11833 + ": nesting=" + r.executeNesting
11834 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011835 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011836 r.executeNesting--;
11837 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011838 if (DEBUG_SERVICE) Slog.v(TAG,
11839 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011840 r.app.executingServices.remove(r);
11841 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011842 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
11843 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011844 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
11845 }
11846 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011847 if (DEBUG_SERVICE) Slog.v(TAG,
11848 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011849 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020011850 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011851 }
11852 updateOomAdjLocked(r.app);
11853 }
11854 }
11855
11856 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011857 String anrMessage = null;
11858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011859 synchronized(this) {
11860 if (proc.executingServices.size() == 0 || proc.thread == null) {
11861 return;
11862 }
11863 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
11864 Iterator<ServiceRecord> it = proc.executingServices.iterator();
11865 ServiceRecord timeout = null;
11866 long nextTime = 0;
11867 while (it.hasNext()) {
11868 ServiceRecord sr = it.next();
11869 if (sr.executingStart < maxTime) {
11870 timeout = sr;
11871 break;
11872 }
11873 if (sr.executingStart > nextTime) {
11874 nextTime = sr.executingStart;
11875 }
11876 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011877 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011878 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011879 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011880 } else {
11881 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11882 msg.obj = proc;
11883 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
11884 }
11885 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011886
11887 if (anrMessage != null) {
11888 appNotResponding(proc, null, null, anrMessage);
11889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011890 }
11891
11892 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011893 // BACKUP AND RESTORE
11894 // =========================================================
11895
11896 // Cause the target app to be launched if necessary and its backup agent
11897 // instantiated. The backup agent will invoke backupAgentCreated() on the
11898 // activity manager to announce its creation.
11899 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011900 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011901 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11902
11903 synchronized(this) {
11904 // !!! TODO: currently no check here that we're already bound
11905 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11906 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11907 synchronized (stats) {
11908 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11909 }
11910
Dianne Hackborne7f97212011-02-24 14:40:20 -080011911 // Backup agent is now in use, its package can't be stopped.
11912 try {
11913 AppGlobals.getPackageManager().setPackageStoppedState(
11914 app.packageName, false);
11915 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011916 } catch (IllegalArgumentException e) {
11917 Slog.w(TAG, "Failed trying to unstop package "
11918 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011919 }
11920
Christopher Tate181fafa2009-05-14 11:12:14 -070011921 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011922 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11923 ? new ComponentName(app.packageName, app.backupAgentName)
11924 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011925 // startProcessLocked() returns existing proc's record if it's already running
11926 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011927 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011928 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011929 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011930 return false;
11931 }
11932
11933 r.app = proc;
11934 mBackupTarget = r;
11935 mBackupAppName = app.packageName;
11936
Christopher Tate6fa95972009-06-05 18:43:55 -070011937 // Try not to kill the process during backup
11938 updateOomAdjLocked(proc);
11939
Christopher Tate181fafa2009-05-14 11:12:14 -070011940 // If the process is already attached, schedule the creation of the backup agent now.
11941 // If it is not yet live, this will be done when it attaches to the framework.
11942 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011943 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011944 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011945 proc.thread.scheduleCreateBackupAgent(app,
11946 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011947 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011948 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011949 }
11950 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011951 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011952 }
11953 // Invariants: at this point, the target app process exists and the application
11954 // is either already running or in the process of coming up. mBackupTarget and
11955 // mBackupAppName describe the app, so that when it binds back to the AM we
11956 // know that it's scheduled for a backup-agent operation.
11957 }
11958
11959 return true;
11960 }
11961
11962 // A backup agent has just come up
11963 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011964 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011965 + " = " + agent);
11966
11967 synchronized(this) {
11968 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011969 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011970 return;
11971 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011972 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011973
Dianne Hackborn06740692010-09-22 22:46:21 -070011974 long oldIdent = Binder.clearCallingIdentity();
11975 try {
11976 IBackupManager bm = IBackupManager.Stub.asInterface(
11977 ServiceManager.getService(Context.BACKUP_SERVICE));
11978 bm.agentConnected(agentPackageName, agent);
11979 } catch (RemoteException e) {
11980 // can't happen; the backup manager service is local
11981 } catch (Exception e) {
11982 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11983 e.printStackTrace();
11984 } finally {
11985 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011986 }
11987 }
11988
11989 // done with this agent
11990 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011991 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011992 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011993 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011994 return;
11995 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011996
11997 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011998 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011999 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012000 return;
12001 }
12002
Christopher Tate181fafa2009-05-14 11:12:14 -070012003 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012004 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012005 return;
12006 }
12007
Christopher Tate6fa95972009-06-05 18:43:55 -070012008 ProcessRecord proc = mBackupTarget.app;
12009 mBackupTarget = null;
12010 mBackupAppName = null;
12011
12012 // Not backing this app up any more; reset its OOM adjustment
12013 updateOomAdjLocked(proc);
12014
Christopher Tatec7b31e32009-06-10 15:49:30 -070012015 // If the app crashed during backup, 'thread' will be null here
12016 if (proc.thread != null) {
12017 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012018 proc.thread.scheduleDestroyBackupAgent(appInfo,
12019 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012020 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012021 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012022 e.printStackTrace();
12023 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012024 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012025 }
12026 }
12027 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012028 // BROADCASTS
12029 // =========================================================
12030
Josh Bartel7f208742010-02-25 11:01:44 -060012031 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012032 List cur) {
12033 final ContentResolver resolver = mContext.getContentResolver();
12034 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12035 if (list == null) {
12036 return cur;
12037 }
12038 int N = list.size();
12039 for (int i=0; i<N; i++) {
12040 Intent intent = list.get(i);
12041 if (filter.match(resolver, intent, true, TAG) >= 0) {
12042 if (cur == null) {
12043 cur = new ArrayList<Intent>();
12044 }
12045 cur.add(intent);
12046 }
12047 }
12048 return cur;
12049 }
12050
Christopher Tatef46723b2012-01-26 14:19:24 -080012051 boolean isPendingBroadcastProcessLocked(int pid) {
12052 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12053 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012055
Christopher Tatef46723b2012-01-26 14:19:24 -080012056 void skipPendingBroadcastLocked(int pid) {
12057 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12058 for (BroadcastQueue queue : mBroadcastQueues) {
12059 queue.skipPendingBroadcastLocked(pid);
12060 }
12061 }
12062
12063 // The app just attached; send any pending broadcasts that it should receive
12064 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12065 boolean didSomething = false;
12066 for (BroadcastQueue queue : mBroadcastQueues) {
12067 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012068 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012069 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012070 }
12071
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012072 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012073 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012074 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075 synchronized(this) {
12076 ProcessRecord callerApp = null;
12077 if (caller != null) {
12078 callerApp = getRecordForAppLocked(caller);
12079 if (callerApp == null) {
12080 throw new SecurityException(
12081 "Unable to find app for caller " + caller
12082 + " (pid=" + Binder.getCallingPid()
12083 + ") when registering receiver " + receiver);
12084 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012085 if (callerApp.info.uid != Process.SYSTEM_UID &&
12086 !callerApp.pkgList.contains(callerPackage)) {
12087 throw new SecurityException("Given caller package " + callerPackage
12088 + " is not running in process " + callerApp);
12089 }
12090 } else {
12091 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012092 }
12093
12094 List allSticky = null;
12095
12096 // Look for any matching sticky broadcasts...
12097 Iterator actions = filter.actionsIterator();
12098 if (actions != null) {
12099 while (actions.hasNext()) {
12100 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012101 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012102 }
12103 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012104 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012105 }
12106
12107 // The first sticky in the list is returned directly back to
12108 // the client.
12109 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12110
Joe Onorato8a9b2202010-02-26 18:56:32 -080012111 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012112 + ": " + sticky);
12113
12114 if (receiver == null) {
12115 return sticky;
12116 }
12117
12118 ReceiverList rl
12119 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12120 if (rl == null) {
12121 rl = new ReceiverList(this, callerApp,
12122 Binder.getCallingPid(),
12123 Binder.getCallingUid(), receiver);
12124 if (rl.app != null) {
12125 rl.app.receivers.add(rl);
12126 } else {
12127 try {
12128 receiver.asBinder().linkToDeath(rl, 0);
12129 } catch (RemoteException e) {
12130 return sticky;
12131 }
12132 rl.linkedToDeath = true;
12133 }
12134 mRegisteredReceivers.put(receiver.asBinder(), rl);
12135 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012136 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012137 rl.add(bf);
12138 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012139 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012140 }
12141 mReceiverResolver.addFilter(bf);
12142
12143 // Enqueue broadcasts for all existing stickies that match
12144 // this filter.
12145 if (allSticky != null) {
12146 ArrayList receivers = new ArrayList();
12147 receivers.add(bf);
12148
12149 int N = allSticky.size();
12150 for (int i=0; i<N; i++) {
12151 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012152 BroadcastQueue queue = broadcastQueueForIntent(intent);
12153 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012154 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012155 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012156 queue.enqueueParallelBroadcastLocked(r);
12157 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012158 }
12159 }
12160
12161 return sticky;
12162 }
12163 }
12164
12165 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012166 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012167
Christopher Tatef46723b2012-01-26 14:19:24 -080012168 final long origId = Binder.clearCallingIdentity();
12169 try {
12170 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012171
Christopher Tatef46723b2012-01-26 14:19:24 -080012172 synchronized(this) {
12173 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012174 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012175 if (rl != null) {
12176 if (rl.curBroadcast != null) {
12177 BroadcastRecord r = rl.curBroadcast;
12178 final boolean doNext = finishReceiverLocked(
12179 receiver.asBinder(), r.resultCode, r.resultData,
12180 r.resultExtras, r.resultAbort, true);
12181 if (doNext) {
12182 doTrim = true;
12183 r.queue.processNextBroadcast(false);
12184 }
12185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012186
Christopher Tatef46723b2012-01-26 14:19:24 -080012187 if (rl.app != null) {
12188 rl.app.receivers.remove(rl);
12189 }
12190 removeReceiverLocked(rl);
12191 if (rl.linkedToDeath) {
12192 rl.linkedToDeath = false;
12193 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012195 }
12196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012197
Christopher Tatef46723b2012-01-26 14:19:24 -080012198 // If we actually concluded any broadcasts, we might now be able
12199 // to trim the recipients' apps from our working set
12200 if (doTrim) {
12201 trimApplications();
12202 return;
12203 }
12204
12205 } finally {
12206 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012208 }
12209
12210 void removeReceiverLocked(ReceiverList rl) {
12211 mRegisteredReceivers.remove(rl.receiver.asBinder());
12212 int N = rl.size();
12213 for (int i=0; i<N; i++) {
12214 mReceiverResolver.removeFilter(rl.get(i));
12215 }
12216 }
12217
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012218 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12219 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12220 ProcessRecord r = mLruProcesses.get(i);
12221 if (r.thread != null) {
12222 try {
12223 r.thread.dispatchPackageBroadcast(cmd, packages);
12224 } catch (RemoteException ex) {
12225 }
12226 }
12227 }
12228 }
12229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012230 private final int broadcastIntentLocked(ProcessRecord callerApp,
12231 String callerPackage, Intent intent, String resolvedType,
12232 IIntentReceiver resultTo, int resultCode, String resultData,
12233 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012234 boolean ordered, boolean sticky, int callingPid, int callingUid,
12235 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012236 intent = new Intent(intent);
12237
Dianne Hackborne7f97212011-02-24 14:40:20 -080012238 // By default broadcasts do not go to stopped apps.
12239 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12240
Joe Onorato8a9b2202010-02-26 18:56:32 -080012241 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012242 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12243 + " ordered=" + ordered);
12244 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012245 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012246 }
12247
12248 // Handle special intents: if this broadcast is from the package
12249 // manager about a package being removed, we need to remove all of
12250 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012251 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012252 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012253 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12254 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012255 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012256 || uidRemoved) {
12257 if (checkComponentPermission(
12258 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012259 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012260 == PackageManager.PERMISSION_GRANTED) {
12261 if (uidRemoved) {
12262 final Bundle intentExtras = intent.getExtras();
12263 final int uid = intentExtras != null
12264 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12265 if (uid >= 0) {
12266 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12267 synchronized (bs) {
12268 bs.removeUidStatsLocked(uid);
12269 }
12270 }
12271 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012272 // If resources are unvailble just force stop all
12273 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012274 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012275 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12276 if (list != null && (list.length > 0)) {
12277 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070012278 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012279 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012280 sendPackageBroadcastLocked(
12281 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012282 }
12283 } else {
12284 Uri data = intent.getData();
12285 String ssp;
12286 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12287 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12288 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070012289 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012290 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012291 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012292 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12293 new String[] {ssp});
12294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012295 }
12296 }
12297 }
12298 } else {
12299 String msg = "Permission Denial: " + intent.getAction()
12300 + " broadcast from " + callerPackage + " (pid=" + callingPid
12301 + ", uid=" + callingUid + ")"
12302 + " requires "
12303 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012304 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012305 throw new SecurityException(msg);
12306 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012307
12308 // Special case for adding a package: by default turn on compatibility
12309 // mode.
12310 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012311 Uri data = intent.getData();
12312 String ssp;
12313 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12314 mCompatModePackages.handlePackageAddedLocked(ssp,
12315 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012317 }
12318
12319 /*
12320 * If this is the time zone changed action, queue up a message that will reset the timezone
12321 * of all currently running processes. This message will get queued up before the broadcast
12322 * happens.
12323 */
12324 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12325 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12326 }
12327
Robert Greenwalt03595d02010-11-02 14:08:23 -070012328 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12329 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12330 }
12331
Robert Greenwalt434203a2010-10-11 16:00:27 -070012332 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12333 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12334 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12335 }
12336
Dianne Hackborn854060af2009-07-09 18:14:31 -070012337 /*
12338 * Prevent non-system code (defined here to be non-persistent
12339 * processes) from sending protected broadcasts.
12340 */
12341 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12342 || callingUid == Process.SHELL_UID || callingUid == 0) {
12343 // Always okay.
12344 } else if (callerApp == null || !callerApp.persistent) {
12345 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012346 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012347 intent.getAction())) {
12348 String msg = "Permission Denial: not allowed to send broadcast "
12349 + intent.getAction() + " from pid="
12350 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012351 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012352 throw new SecurityException(msg);
12353 }
12354 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012355 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012356 return BROADCAST_SUCCESS;
12357 }
12358 }
12359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012360 // Add to the sticky list if requested.
12361 if (sticky) {
12362 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12363 callingPid, callingUid)
12364 != PackageManager.PERMISSION_GRANTED) {
12365 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12366 + callingPid + ", uid=" + callingUid
12367 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012368 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012369 throw new SecurityException(msg);
12370 }
12371 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012372 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012373 + " and enforce permission " + requiredPermission);
12374 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
12375 }
12376 if (intent.getComponent() != null) {
12377 throw new SecurityException(
12378 "Sticky broadcasts can't target a specific component");
12379 }
12380 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12381 if (list == null) {
12382 list = new ArrayList<Intent>();
12383 mStickyBroadcasts.put(intent.getAction(), list);
12384 }
12385 int N = list.size();
12386 int i;
12387 for (i=0; i<N; i++) {
12388 if (intent.filterEquals(list.get(i))) {
12389 // This sticky already exists, replace it.
12390 list.set(i, new Intent(intent));
12391 break;
12392 }
12393 }
12394 if (i >= N) {
12395 list.add(new Intent(intent));
12396 }
12397 }
12398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012399 // Figure out who all will receive this broadcast.
12400 List receivers = null;
12401 List<BroadcastFilter> registeredReceivers = null;
12402 try {
12403 if (intent.getComponent() != null) {
12404 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012405 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012406 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012407 if (ai != null) {
12408 receivers = new ArrayList();
12409 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012410 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012411 receivers.add(ri);
12412 }
12413 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070012414 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012415 // Need to resolve the intent to interested receivers...
12416 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12417 == 0) {
12418 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012419 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012420 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012421 }
Mihai Preda074edef2009-05-18 17:13:31 +020012422 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012423 }
12424 } catch (RemoteException ex) {
12425 // pm is in same process, this will never happen.
12426 }
12427
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012428 final boolean replacePending =
12429 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12430
Joe Onorato8a9b2202010-02-26 18:56:32 -080012431 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012432 + " replacePending=" + replacePending);
12433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012434 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12435 if (!ordered && NR > 0) {
12436 // If we are not serializing this broadcast, then send the
12437 // registered receivers separately so they don't wait for the
12438 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012439 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12440 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012441 callerPackage, callingPid, callingUid, requiredPermission,
12442 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012443 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012444 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012445 TAG, "Enqueueing parallel broadcast " + r);
12446 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012447 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012448 queue.enqueueParallelBroadcastLocked(r);
12449 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012451 registeredReceivers = null;
12452 NR = 0;
12453 }
12454
12455 // Merge into one list.
12456 int ir = 0;
12457 if (receivers != null) {
12458 // A special case for PACKAGE_ADDED: do not allow the package
12459 // being added to see this broadcast. This prevents them from
12460 // using this as a back door to get run as soon as they are
12461 // installed. Maybe in the future we want to have a special install
12462 // broadcast or such for apps, but we'd like to deliberately make
12463 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012464 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012465 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12466 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12467 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012468 Uri data = intent.getData();
12469 if (data != null) {
12470 String pkgName = data.getSchemeSpecificPart();
12471 if (pkgName != null) {
12472 skipPackages = new String[] { pkgName };
12473 }
12474 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012475 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012476 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012477 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012478 if (skipPackages != null && (skipPackages.length > 0)) {
12479 for (String skipPackage : skipPackages) {
12480 if (skipPackage != null) {
12481 int NT = receivers.size();
12482 for (int it=0; it<NT; it++) {
12483 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12484 if (curt.activityInfo.packageName.equals(skipPackage)) {
12485 receivers.remove(it);
12486 it--;
12487 NT--;
12488 }
12489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012490 }
12491 }
12492 }
12493
12494 int NT = receivers != null ? receivers.size() : 0;
12495 int it = 0;
12496 ResolveInfo curt = null;
12497 BroadcastFilter curr = null;
12498 while (it < NT && ir < NR) {
12499 if (curt == null) {
12500 curt = (ResolveInfo)receivers.get(it);
12501 }
12502 if (curr == null) {
12503 curr = registeredReceivers.get(ir);
12504 }
12505 if (curr.getPriority() >= curt.priority) {
12506 // Insert this broadcast record into the final list.
12507 receivers.add(it, curr);
12508 ir++;
12509 curr = null;
12510 it++;
12511 NT++;
12512 } else {
12513 // Skip to the next ResolveInfo in the final list.
12514 it++;
12515 curt = null;
12516 }
12517 }
12518 }
12519 while (ir < NR) {
12520 if (receivers == null) {
12521 receivers = new ArrayList();
12522 }
12523 receivers.add(registeredReceivers.get(ir));
12524 ir++;
12525 }
12526
12527 if ((receivers != null && receivers.size() > 0)
12528 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012529 BroadcastQueue queue = broadcastQueueForIntent(intent);
12530 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012531 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012532 receivers, resultTo, resultCode, resultData, map, ordered,
12533 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012534 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012535 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012536 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012537 if (DEBUG_BROADCAST) {
12538 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012539 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012540 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012541 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012542 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012543 queue.enqueueOrderedBroadcastLocked(r);
12544 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012546 }
12547
12548 return BROADCAST_SUCCESS;
12549 }
12550
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012551 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012552 // Refuse possible leaked file descriptors
12553 if (intent != null && intent.hasFileDescriptors() == true) {
12554 throw new IllegalArgumentException("File descriptors passed in Intent");
12555 }
12556
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012557 int flags = intent.getFlags();
12558
12559 if (!mProcessesReady) {
12560 // if the caller really truly claims to know what they're doing, go
12561 // ahead and allow the broadcast without launching any receivers
12562 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12563 intent = new Intent(intent);
12564 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12565 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12566 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12567 + " before boot completion");
12568 throw new IllegalStateException("Cannot broadcast before boot completed");
12569 }
12570 }
12571
12572 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12573 throw new IllegalArgumentException(
12574 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12575 }
12576
12577 return intent;
12578 }
12579
12580 public final int broadcastIntent(IApplicationThread caller,
12581 Intent intent, String resolvedType, IIntentReceiver resultTo,
12582 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012583 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012584 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012586 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012588 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12589 final int callingPid = Binder.getCallingPid();
12590 final int callingUid = Binder.getCallingUid();
12591 final long origId = Binder.clearCallingIdentity();
12592 int res = broadcastIntentLocked(callerApp,
12593 callerApp != null ? callerApp.info.packageName : null,
12594 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012595 resultCode, resultData, map, requiredPermission, serialized, sticky,
12596 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012597 Binder.restoreCallingIdentity(origId);
12598 return res;
12599 }
12600 }
12601
12602 int broadcastIntentInPackage(String packageName, int uid,
12603 Intent intent, String resolvedType, IIntentReceiver resultTo,
12604 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012605 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012606 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012607 intent = verifyBroadcastLocked(intent);
12608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012609 final long origId = Binder.clearCallingIdentity();
12610 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12611 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012612 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012613 Binder.restoreCallingIdentity(origId);
12614 return res;
12615 }
12616 }
12617
Amith Yamasani742a6712011-05-04 14:49:28 -070012618 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12619 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012620 // Refuse possible leaked file descriptors
12621 if (intent != null && intent.hasFileDescriptors() == true) {
12622 throw new IllegalArgumentException("File descriptors passed in Intent");
12623 }
12624
12625 synchronized(this) {
12626 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12627 != PackageManager.PERMISSION_GRANTED) {
12628 String msg = "Permission Denial: unbroadcastIntent() from pid="
12629 + Binder.getCallingPid()
12630 + ", uid=" + Binder.getCallingUid()
12631 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012632 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012633 throw new SecurityException(msg);
12634 }
12635 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12636 if (list != null) {
12637 int N = list.size();
12638 int i;
12639 for (i=0; i<N; i++) {
12640 if (intent.filterEquals(list.get(i))) {
12641 list.remove(i);
12642 break;
12643 }
12644 }
12645 }
12646 }
12647 }
12648
12649 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12650 String resultData, Bundle resultExtras, boolean resultAbort,
12651 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012652 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12653 if (r == null) {
12654 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012655 return false;
12656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012657
Christopher Tatef46723b2012-01-26 14:19:24 -080012658 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12659 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012660 }
12661
12662 public void finishReceiver(IBinder who, int resultCode, String resultData,
12663 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012664 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012665
12666 // Refuse possible leaked file descriptors
12667 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12668 throw new IllegalArgumentException("File descriptors passed in Bundle");
12669 }
12670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012671 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012672 try {
12673 boolean doNext = false;
12674 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012675
Christopher Tatef46723b2012-01-26 14:19:24 -080012676 synchronized(this) {
12677 r = broadcastRecordForReceiverLocked(who);
12678 if (r != null) {
12679 doNext = r.queue.finishReceiverLocked(r, resultCode,
12680 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012682 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012683
Christopher Tatef46723b2012-01-26 14:19:24 -080012684 if (doNext) {
12685 r.queue.processNextBroadcast(false);
12686 }
12687 trimApplications();
12688 } finally {
12689 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012693 // =========================================================
12694 // INSTRUMENTATION
12695 // =========================================================
12696
12697 public boolean startInstrumentation(ComponentName className,
12698 String profileFile, int flags, Bundle arguments,
12699 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012700 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012701 // Refuse possible leaked file descriptors
12702 if (arguments != null && arguments.hasFileDescriptors()) {
12703 throw new IllegalArgumentException("File descriptors passed in Bundle");
12704 }
12705
12706 synchronized(this) {
12707 InstrumentationInfo ii = null;
12708 ApplicationInfo ai = null;
12709 try {
12710 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012711 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012712 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012713 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012714 } catch (PackageManager.NameNotFoundException e) {
12715 }
12716 if (ii == null) {
12717 reportStartInstrumentationFailure(watcher, className,
12718 "Unable to find instrumentation info for: " + className);
12719 return false;
12720 }
12721 if (ai == null) {
12722 reportStartInstrumentationFailure(watcher, className,
12723 "Unable to find instrumentation target package: " + ii.targetPackage);
12724 return false;
12725 }
12726
12727 int match = mContext.getPackageManager().checkSignatures(
12728 ii.targetPackage, ii.packageName);
12729 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12730 String msg = "Permission Denial: starting instrumentation "
12731 + className + " from pid="
12732 + Binder.getCallingPid()
12733 + ", uid=" + Binder.getCallingPid()
12734 + " not allowed because package " + ii.packageName
12735 + " does not have a signature matching the target "
12736 + ii.targetPackage;
12737 reportStartInstrumentationFailure(watcher, className, msg);
12738 throw new SecurityException(msg);
12739 }
12740
12741 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012742 // Instrumentation can kill and relaunch even persistent processes
12743 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012744 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012745 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012746 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012747 app.instrumentationProfileFile = profileFile;
12748 app.instrumentationArguments = arguments;
12749 app.instrumentationWatcher = watcher;
12750 app.instrumentationResultClass = className;
12751 Binder.restoreCallingIdentity(origId);
12752 }
12753
12754 return true;
12755 }
12756
12757 /**
12758 * Report errors that occur while attempting to start Instrumentation. Always writes the
12759 * error to the logs, but if somebody is watching, send the report there too. This enables
12760 * the "am" command to report errors with more information.
12761 *
12762 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12763 * @param cn The component name of the instrumentation.
12764 * @param report The error report.
12765 */
12766 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12767 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012768 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012769 try {
12770 if (watcher != null) {
12771 Bundle results = new Bundle();
12772 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12773 results.putString("Error", report);
12774 watcher.instrumentationStatus(cn, -1, results);
12775 }
12776 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012777 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012778 }
12779 }
12780
12781 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12782 if (app.instrumentationWatcher != null) {
12783 try {
12784 // NOTE: IInstrumentationWatcher *must* be oneway here
12785 app.instrumentationWatcher.instrumentationFinished(
12786 app.instrumentationClass,
12787 resultCode,
12788 results);
12789 } catch (RemoteException e) {
12790 }
12791 }
12792 app.instrumentationWatcher = null;
12793 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012794 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012795 app.instrumentationProfileFile = null;
12796 app.instrumentationArguments = null;
12797
Christopher Tate3dacd842011-08-19 14:56:15 -070012798 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012799 }
12800
12801 public void finishInstrumentation(IApplicationThread target,
12802 int resultCode, Bundle results) {
12803 // Refuse possible leaked file descriptors
12804 if (results != null && results.hasFileDescriptors()) {
12805 throw new IllegalArgumentException("File descriptors passed in Intent");
12806 }
12807
12808 synchronized(this) {
12809 ProcessRecord app = getRecordForAppLocked(target);
12810 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012811 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012812 return;
12813 }
12814 final long origId = Binder.clearCallingIdentity();
12815 finishInstrumentationLocked(app, resultCode, results);
12816 Binder.restoreCallingIdentity(origId);
12817 }
12818 }
12819
12820 // =========================================================
12821 // CONFIGURATION
12822 // =========================================================
12823
12824 public ConfigurationInfo getDeviceConfigurationInfo() {
12825 ConfigurationInfo config = new ConfigurationInfo();
12826 synchronized (this) {
12827 config.reqTouchScreen = mConfiguration.touchscreen;
12828 config.reqKeyboardType = mConfiguration.keyboard;
12829 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012830 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12831 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012832 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12833 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012834 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12835 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012836 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12837 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012838 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012839 }
12840 return config;
12841 }
12842
12843 public Configuration getConfiguration() {
12844 Configuration ci;
12845 synchronized(this) {
12846 ci = new Configuration(mConfiguration);
12847 }
12848 return ci;
12849 }
12850
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012851 public void updatePersistentConfiguration(Configuration values) {
12852 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12853 "updateConfiguration()");
12854 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12855 "updateConfiguration()");
12856 if (values == null) {
12857 throw new NullPointerException("Configuration must not be null");
12858 }
12859
12860 synchronized(this) {
12861 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012862 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012863 Binder.restoreCallingIdentity(origId);
12864 }
12865 }
12866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012867 public void updateConfiguration(Configuration values) {
12868 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12869 "updateConfiguration()");
12870
12871 synchronized(this) {
12872 if (values == null && mWindowManager != null) {
12873 // sentinel: fetch the current configuration from the window manager
12874 values = mWindowManager.computeNewConfiguration();
12875 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012876
12877 if (mWindowManager != null) {
12878 mProcessList.applyDisplaySize(mWindowManager);
12879 }
12880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012881 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012882 if (values != null) {
12883 Settings.System.clearConfiguration(values);
12884 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012885 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012886 Binder.restoreCallingIdentity(origId);
12887 }
12888 }
12889
12890 /**
12891 * Do either or both things: (1) change the current configuration, and (2)
12892 * make sure the given activity is running with the (now) current
12893 * configuration. Returns true if the activity has been left running, or
12894 * false if <var>starting</var> is being destroyed to match the new
12895 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012896 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012897 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012898 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012899 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012900 // do nothing if we are headless
12901 if (mHeadless) return true;
12902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012903 int changes = 0;
12904
12905 boolean kept = true;
12906
12907 if (values != null) {
12908 Configuration newConfig = new Configuration(mConfiguration);
12909 changes = newConfig.updateFrom(values);
12910 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012911 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012912 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012913 }
12914
Doug Zongker2bec3d42009-12-04 12:52:44 -080012915 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012916
Dianne Hackborn813075a62011-11-14 17:45:19 -080012917 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012918 saveLocaleLocked(values.locale,
12919 !values.locale.equals(mConfiguration.locale),
12920 values.userSetLocale);
12921 }
12922
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012923 mConfigurationSeq++;
12924 if (mConfigurationSeq <= 0) {
12925 mConfigurationSeq = 1;
12926 }
12927 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012929 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012930
12931 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012932
12933 // TODO: If our config changes, should we auto dismiss any currently
12934 // showing dialogs?
12935 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012936
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012937 AttributeCache ac = AttributeCache.instance();
12938 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012939 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012941
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012942 // Make sure all resources in our process are updated
12943 // right now, so that anyone who is going to retrieve
12944 // resource values after we return will be sure to get
12945 // the new ones. This is especially important during
12946 // boot, where the first config change needs to guarantee
12947 // all resources have that config before following boot
12948 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012949 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012950
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012951 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012952 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012953 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012954 mHandler.sendMessage(msg);
12955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012956
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012957 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12958 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 try {
12960 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012961 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012962 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012963 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012964 }
12965 } catch (Exception e) {
12966 }
12967 }
12968 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012969 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12970 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012971 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070012972 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012973 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12974 broadcastIntentLocked(null, null,
12975 new Intent(Intent.ACTION_LOCALE_CHANGED),
12976 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070012977 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012979 }
12980 }
12981
12982 if (changes != 0 && starting == null) {
12983 // If the configuration changed, and the caller is not already
12984 // in the process of starting an activity, then find the top
12985 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012986 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012987 }
12988
12989 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012990 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012991 // And we need to make sure at this point that all other activities
12992 // are made visible with the correct configuration.
12993 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012994 }
12995
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012996 if (values != null && mWindowManager != null) {
12997 mWindowManager.setNewConfiguration(mConfiguration);
12998 }
12999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013000 return kept;
13001 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013002
13003 /**
13004 * Decide based on the configuration whether we should shouw the ANR,
13005 * crash, etc dialogs. The idea is that if there is no affordnace to
13006 * press the on-screen buttons, we shouldn't show the dialog.
13007 *
13008 * A thought: SystemUI might also want to get told about this, the Power
13009 * dialog / global actions also might want different behaviors.
13010 */
13011 private static final boolean shouldShowDialogs(Configuration config) {
13012 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13013 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013015
13016 /**
13017 * Save the locale. You must be inside a synchronized (this) block.
13018 */
13019 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13020 if(isDiff) {
13021 SystemProperties.set("user.language", l.getLanguage());
13022 SystemProperties.set("user.region", l.getCountry());
13023 }
13024
13025 if(isPersist) {
13026 SystemProperties.set("persist.sys.language", l.getLanguage());
13027 SystemProperties.set("persist.sys.country", l.getCountry());
13028 SystemProperties.set("persist.sys.localevar", l.getVariant());
13029 }
13030 }
13031
13032 // =========================================================
13033 // LIFETIME MANAGEMENT
13034 // =========================================================
13035
Christopher Tatef46723b2012-01-26 14:19:24 -080013036 // Returns which broadcast queue the app is the current [or imminent] receiver
13037 // on, or 'null' if the app is not an active broadcast recipient.
13038 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13039 BroadcastRecord r = app.curReceiver;
13040 if (r != null) {
13041 return r.queue;
13042 }
13043
13044 // It's not the current receiver, but it might be starting up to become one
13045 synchronized (this) {
13046 for (BroadcastQueue queue : mBroadcastQueues) {
13047 r = queue.mPendingBroadcast;
13048 if (r != null && r.curApp == app) {
13049 // found it; report which queue it's in
13050 return queue;
13051 }
13052 }
13053 }
13054
13055 return null;
13056 }
13057
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013058 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013059 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013060 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013061 // This adjustment has already been computed. If we are calling
13062 // from the top, we may have already computed our adjustment with
13063 // an earlier hidden adjustment that isn't really for us... if
13064 // so, use the new hidden adjustment.
13065 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013066 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013067 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013068 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013069 }
13070
13071 if (app.thread == null) {
13072 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013073 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013074 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013075 }
13076
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013077 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13078 app.adjSource = null;
13079 app.adjTarget = null;
13080 app.empty = false;
13081 app.hidden = false;
13082
13083 final int activitiesSize = app.activities.size();
13084
Dianne Hackborn7d608422011-08-07 16:24:18 -070013085 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013086 // The max adjustment doesn't allow this app to be anything
13087 // below foreground, so it is not worth doing work for it.
13088 app.adjType = "fixed";
13089 app.adjSeq = mAdjSeq;
13090 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013091 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013092 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013093 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013094 // System process can do UI, and when they do we want to have
13095 // them trim their memory after the user leaves the UI. To
13096 // facilitate this, here we need to determine whether or not it
13097 // is currently showing UI.
13098 app.systemNoUi = true;
13099 if (app == TOP_APP) {
13100 app.systemNoUi = false;
13101 } else if (activitiesSize > 0) {
13102 for (int j = 0; j < activitiesSize; j++) {
13103 final ActivityRecord r = app.activities.get(j);
13104 if (r.visible) {
13105 app.systemNoUi = false;
13106 break;
13107 }
13108 }
13109 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013110 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013111 }
13112
13113 final boolean hadForegroundActivities = app.foregroundActivities;
13114
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013115 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013116 app.keeping = false;
13117 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013118
The Android Open Source Project4df24232009-03-05 14:34:35 -080013119 // Determine the importance of the process, starting with most
13120 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013121 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013122 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013123 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013124 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013125 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013126 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013127 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013128 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013129 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013130 } else if (app.instrumentationClass != null) {
13131 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013132 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013133 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013134 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013135 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013136 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013137 // counts as being in the foreground for OOM killer purposes.
13138 // It's placed in a sched group based on the nature of the
13139 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013140 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013141 schedGroup = (queue == mFgBroadcastQueue)
13142 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013143 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013144 } else if (app.executingServices.size() > 0) {
13145 // An app that is currently executing a service callback also
13146 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013147 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013148 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013149 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013150 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013151 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013152 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013153 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013154 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013155 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013156 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013157 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013158 // A very not-needed process. If this is lower in the lru list,
13159 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013160 adj = hiddenAdj;
13161 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013162 app.hidden = true;
13163 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013164 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013165 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013166
13167 // Examine all activities if not already foreground.
13168 if (!app.foregroundActivities && activitiesSize > 0) {
13169 for (int j = 0; j < activitiesSize; j++) {
13170 final ActivityRecord r = app.activities.get(j);
13171 if (r.visible) {
13172 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013173 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13174 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013175 app.adjType = "visible";
13176 }
13177 schedGroup = Process.THREAD_GROUP_DEFAULT;
13178 app.hidden = false;
13179 app.foregroundActivities = true;
13180 break;
13181 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13182 || r.state == ActivityState.STOPPING) {
13183 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013184 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13185 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013186 app.adjType = "stopping";
13187 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013188 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013189 app.foregroundActivities = true;
13190 }
13191 }
13192 }
13193
Dianne Hackborn7d608422011-08-07 16:24:18 -070013194 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013195 if (app.foregroundServices) {
13196 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013197 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013198 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013199 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013200 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013201 } else if (app.forcingToForeground != null) {
13202 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013203 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013204 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013205 app.adjType = "force-foreground";
13206 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013207 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013208 }
13209 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013210
Dianne Hackborn7d608422011-08-07 16:24:18 -070013211 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013212 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013213 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013214 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013215 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013216 app.adjType = "heavy";
13217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013218
Dianne Hackborn7d608422011-08-07 16:24:18 -070013219 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013220 // This process is hosting what we currently consider to be the
13221 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013222 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013223 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013224 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013225 app.adjType = "home";
13226 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013227
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013228 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13229 && app.activities.size() > 0) {
13230 // This was the previous process that showed UI to the user.
13231 // We want to try to keep it around more aggressively, to give
13232 // a good experience around switching between two apps.
13233 adj = ProcessList.PREVIOUS_APP_ADJ;
13234 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13235 app.hidden = false;
13236 app.adjType = "previous";
13237 }
13238
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013239 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13240 + " reason=" + app.adjType);
13241
The Android Open Source Project4df24232009-03-05 14:34:35 -080013242 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013243 // there are applications dependent on our services or providers, but
13244 // this gives us a baseline and makes sure we don't get into an
13245 // infinite recursion.
13246 app.adjSeq = mAdjSeq;
13247 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013248
Christopher Tate6fa95972009-06-05 18:43:55 -070013249 if (mBackupTarget != null && app == mBackupTarget.app) {
13250 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013251 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013252 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013253 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013254 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013255 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013256 }
13257 }
13258
Dianne Hackborn7d608422011-08-07 16:24:18 -070013259 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013260 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013261 final long now = SystemClock.uptimeMillis();
13262 // This process is more important if the top activity is
13263 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013264 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013265 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013266 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013267 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013268 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013269 // If this process has shown some UI, let it immediately
13270 // go to the LRU list because it may be pretty heavy with
13271 // UI stuff. We'll tag it with a label just to help
13272 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013273 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013274 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013275 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013276 } else {
13277 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13278 // This service has seen some activity within
13279 // recent memory, so we will keep its process ahead
13280 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013281 if (adj > ProcessList.SERVICE_ADJ) {
13282 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013283 app.adjType = "started-services";
13284 app.hidden = false;
13285 }
13286 }
13287 // If we have let the service slide into the background
13288 // state, still have some text describing what it is doing
13289 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013290 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013291 app.adjType = "started-bg-services";
13292 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013293 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013294 // Don't kill this process because it is doing work; it
13295 // has said it is doing work.
13296 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013297 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013298 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013299 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013300 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013301 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013302 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013303 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013304 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013305 // XXX should compute this based on the max of
13306 // all connected clients.
13307 ConnectionRecord cr = clist.get(i);
13308 if (cr.binding.client == app) {
13309 // Binding to ourself is not interesting.
13310 continue;
13311 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013312 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013313 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013314 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013315 int myHiddenAdj = hiddenAdj;
13316 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013317 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013318 myHiddenAdj = client.hiddenAdj;
13319 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013320 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013321 }
13322 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013323 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013324 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013325 String adjType = null;
13326 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13327 // Not doing bind OOM management, so treat
13328 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013329 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013330 // If this process has shown some UI, let it immediately
13331 // go to the LRU list because it may be pretty heavy with
13332 // UI stuff. We'll tag it with a label just to help
13333 // debug and understand what is going on.
13334 if (adj > clientAdj) {
13335 adjType = "bound-bg-ui-services";
13336 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013337 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013338 clientAdj = adj;
13339 } else {
13340 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13341 // This service has not seen activity within
13342 // recent memory, so allow it to drop to the
13343 // LRU list if there is no other reason to keep
13344 // it around. We'll also tag it with a label just
13345 // to help debug and undertand what is going on.
13346 if (adj > clientAdj) {
13347 adjType = "bound-bg-services";
13348 }
13349 clientAdj = adj;
13350 }
13351 }
13352 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013353 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013354 // If this process has recently shown UI, and
13355 // the process that is binding to it is less
13356 // important than being visible, then we don't
13357 // care about the binding as much as we care
13358 // about letting this process get into the LRU
13359 // list to be killed and restarted if needed for
13360 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013361 if (app.hasShownUi && app != mHomeProcess
13362 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013363 adjType = "bound-bg-ui-services";
13364 } else {
13365 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13366 |Context.BIND_IMPORTANT)) != 0) {
13367 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013368 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13369 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13370 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13371 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13372 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013373 adj = clientAdj;
13374 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013375 app.pendingUiClean = true;
13376 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13377 adj = ProcessList.VISIBLE_APP_ADJ;
13378 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013379 }
13380 if (!client.hidden) {
13381 app.hidden = false;
13382 }
13383 if (client.keeping) {
13384 app.keeping = true;
13385 }
13386 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013387 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013388 }
13389 if (adjType != null) {
13390 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013391 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13392 .REASON_SERVICE_IN_USE;
13393 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013394 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013395 app.adjTarget = s.name;
13396 }
13397 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13398 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13399 schedGroup = Process.THREAD_GROUP_DEFAULT;
13400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013401 }
13402 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013403 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13404 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013405 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013406 (a.visible || a.state == ActivityState.RESUMED
13407 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013408 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013409 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13410 schedGroup = Process.THREAD_GROUP_DEFAULT;
13411 }
13412 app.hidden = false;
13413 app.adjType = "service";
13414 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13415 .REASON_SERVICE_IN_USE;
13416 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013417 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013418 app.adjTarget = s.name;
13419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013421 }
13422 }
13423 }
13424 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013425
Dianne Hackborn287952c2010-09-22 22:34:31 -070013426 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013427 // would like to avoid killing it unless it would prevent the current
13428 // application from running. By default we put the process in
13429 // with the rest of the background processes; as we scan through
13430 // its services we may bump it up from there.
13431 if (adj > hiddenAdj) {
13432 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013433 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013434 app.adjType = "bg-services";
13435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013436 }
13437
Dianne Hackborn7d608422011-08-07 16:24:18 -070013438 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013439 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013440 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013441 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013442 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013443 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013444 if (cpr.clients.size() != 0) {
13445 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013446 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013447 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013448 if (client == app) {
13449 // Being our own client is not interesting.
13450 continue;
13451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013452 int myHiddenAdj = hiddenAdj;
13453 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013454 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013455 myHiddenAdj = client.hiddenAdj;
13456 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013457 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013458 }
13459 }
13460 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013461 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013462 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013463 if (app.hasShownUi && app != mHomeProcess
13464 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013465 app.adjType = "bg-ui-provider";
13466 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013467 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13468 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013469 app.adjType = "provider";
13470 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013471 if (!client.hidden) {
13472 app.hidden = false;
13473 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013474 if (client.keeping) {
13475 app.keeping = true;
13476 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013477 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13478 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013479 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013480 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013481 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013482 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013483 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13484 schedGroup = Process.THREAD_GROUP_DEFAULT;
13485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013486 }
13487 }
13488 // If the provider has external (non-framework) process
13489 // dependencies, ensure that its adjustment is at least
13490 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013491 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013492 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13493 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013494 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013495 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013496 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013497 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013498 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013499 }
13500 }
13501 }
13502 }
13503
13504 app.curRawAdj = adj;
13505
Joe Onorato8a9b2202010-02-26 18:56:32 -080013506 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013507 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13508 if (adj > app.maxAdj) {
13509 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013510 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013511 schedGroup = Process.THREAD_GROUP_DEFAULT;
13512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013513 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013514 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013515 app.keeping = true;
13516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013517
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013518 if (app.hasAboveClient) {
13519 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13520 // then we need to drop its adjustment to be lower than the service's
13521 // in order to honor the request. We want to drop it by one adjustment
13522 // level... but there is special meaning applied to various levels so
13523 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013524 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013525 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013526 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13527 adj = ProcessList.VISIBLE_APP_ADJ;
13528 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13529 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13530 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13531 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013532 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013533 adj++;
13534 }
13535 }
13536
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013537 if (adj == ProcessList.SERVICE_ADJ) {
13538 if (doingAll) {
13539 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13540 mNewNumServiceProcs++;
13541 }
13542 if (app.serviceb) {
13543 adj = ProcessList.SERVICE_B_ADJ;
13544 }
13545 } else {
13546 app.serviceb = false;
13547 }
13548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013549 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013550 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013551
13552 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013553 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13554 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013555 }
13556
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013557 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013558 }
13559
13560 /**
13561 * Ask a given process to GC right now.
13562 */
13563 final void performAppGcLocked(ProcessRecord app) {
13564 try {
13565 app.lastRequestedGc = SystemClock.uptimeMillis();
13566 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013567 if (app.reportLowMemory) {
13568 app.reportLowMemory = false;
13569 app.thread.scheduleLowMemory();
13570 } else {
13571 app.thread.processInBackground();
13572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013573 }
13574 } catch (Exception e) {
13575 // whatever.
13576 }
13577 }
13578
13579 /**
13580 * Returns true if things are idle enough to perform GCs.
13581 */
Josh Bartel7f208742010-02-25 11:01:44 -060013582 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013583 boolean processingBroadcasts = false;
13584 for (BroadcastQueue q : mBroadcastQueues) {
13585 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13586 processingBroadcasts = true;
13587 }
13588 }
13589 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013590 && (mSleeping || (mMainStack.mResumedActivity != null &&
13591 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013592 }
13593
13594 /**
13595 * Perform GCs on all processes that are waiting for it, but only
13596 * if things are idle.
13597 */
13598 final void performAppGcsLocked() {
13599 final int N = mProcessesToGc.size();
13600 if (N <= 0) {
13601 return;
13602 }
Josh Bartel7f208742010-02-25 11:01:44 -060013603 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013604 while (mProcessesToGc.size() > 0) {
13605 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013606 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013607 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13608 <= SystemClock.uptimeMillis()) {
13609 // To avoid spamming the system, we will GC processes one
13610 // at a time, waiting a few seconds between each.
13611 performAppGcLocked(proc);
13612 scheduleAppGcsLocked();
13613 return;
13614 } else {
13615 // It hasn't been long enough since we last GCed this
13616 // process... put it in the list to wait for its time.
13617 addProcessToGcListLocked(proc);
13618 break;
13619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013620 }
13621 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013622
13623 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013624 }
13625 }
13626
13627 /**
13628 * If all looks good, perform GCs on all processes waiting for them.
13629 */
13630 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013631 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013632 performAppGcsLocked();
13633 return;
13634 }
13635 // Still not idle, wait some more.
13636 scheduleAppGcsLocked();
13637 }
13638
13639 /**
13640 * Schedule the execution of all pending app GCs.
13641 */
13642 final void scheduleAppGcsLocked() {
13643 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013644
13645 if (mProcessesToGc.size() > 0) {
13646 // Schedule a GC for the time to the next process.
13647 ProcessRecord proc = mProcessesToGc.get(0);
13648 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13649
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013650 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013651 long now = SystemClock.uptimeMillis();
13652 if (when < (now+GC_TIMEOUT)) {
13653 when = now + GC_TIMEOUT;
13654 }
13655 mHandler.sendMessageAtTime(msg, when);
13656 }
13657 }
13658
13659 /**
13660 * Add a process to the array of processes waiting to be GCed. Keeps the
13661 * list in sorted order by the last GC time. The process can't already be
13662 * on the list.
13663 */
13664 final void addProcessToGcListLocked(ProcessRecord proc) {
13665 boolean added = false;
13666 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13667 if (mProcessesToGc.get(i).lastRequestedGc <
13668 proc.lastRequestedGc) {
13669 added = true;
13670 mProcessesToGc.add(i+1, proc);
13671 break;
13672 }
13673 }
13674 if (!added) {
13675 mProcessesToGc.add(0, proc);
13676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013677 }
13678
13679 /**
13680 * Set up to ask a process to GC itself. This will either do it
13681 * immediately, or put it on the list of processes to gc the next
13682 * time things are idle.
13683 */
13684 final void scheduleAppGcLocked(ProcessRecord app) {
13685 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013686 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013687 return;
13688 }
13689 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013690 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013691 scheduleAppGcsLocked();
13692 }
13693 }
13694
Dianne Hackborn287952c2010-09-22 22:34:31 -070013695 final void checkExcessivePowerUsageLocked(boolean doKills) {
13696 updateCpuStatsNow();
13697
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013698 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013699 boolean doWakeKills = doKills;
13700 boolean doCpuKills = doKills;
13701 if (mLastPowerCheckRealtime == 0) {
13702 doWakeKills = false;
13703 }
13704 if (mLastPowerCheckUptime == 0) {
13705 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013706 }
13707 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013708 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013709 }
13710 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013711 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13712 final long curUptime = SystemClock.uptimeMillis();
13713 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13714 mLastPowerCheckRealtime = curRealtime;
13715 mLastPowerCheckUptime = curUptime;
13716 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13717 doWakeKills = false;
13718 }
13719 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13720 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013721 }
13722 int i = mLruProcesses.size();
13723 while (i > 0) {
13724 i--;
13725 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013726 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013727 long wtime;
13728 synchronized (stats) {
13729 wtime = stats.getProcessWakeTime(app.info.uid,
13730 app.pid, curRealtime);
13731 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013732 long wtimeUsed = wtime - app.lastWakeTime;
13733 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13734 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013735 StringBuilder sb = new StringBuilder(128);
13736 sb.append("Wake for ");
13737 app.toShortString(sb);
13738 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013739 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013740 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013741 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013742 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013743 sb.append((wtimeUsed*100)/realtimeSince);
13744 sb.append("%)");
13745 Slog.i(TAG, sb.toString());
13746 sb.setLength(0);
13747 sb.append("CPU for ");
13748 app.toShortString(sb);
13749 sb.append(": over ");
13750 TimeUtils.formatDuration(uptimeSince, sb);
13751 sb.append(" used ");
13752 TimeUtils.formatDuration(cputimeUsed, sb);
13753 sb.append(" (");
13754 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013755 sb.append("%)");
13756 Slog.i(TAG, sb.toString());
13757 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013758 // If a process has held a wake lock for more
13759 // than 50% of the time during this period,
13760 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013761 if (doWakeKills && realtimeSince > 0
13762 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13763 synchronized (stats) {
13764 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13765 realtimeSince, wtimeUsed);
13766 }
13767 Slog.w(TAG, "Excessive wake lock in " + app.processName
13768 + " (pid " + app.pid + "): held " + wtimeUsed
13769 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013770 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13771 app.processName, app.setAdj, "excessive wake lock");
13772 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013773 } else if (doCpuKills && uptimeSince > 0
13774 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13775 synchronized (stats) {
13776 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13777 uptimeSince, cputimeUsed);
13778 }
13779 Slog.w(TAG, "Excessive CPU in " + app.processName
13780 + " (pid " + app.pid + "): used " + cputimeUsed
13781 + " during " + uptimeSince);
13782 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13783 app.processName, app.setAdj, "excessive cpu");
13784 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013785 } else {
13786 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013787 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013788 }
13789 }
13790 }
13791 }
13792
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013793 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013794 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013795 app.hiddenAdj = hiddenAdj;
13796
13797 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013798 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013799 }
13800
Dianne Hackborn287952c2010-09-22 22:34:31 -070013801 final boolean wasKeeping = app.keeping;
13802
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013803 boolean success = true;
13804
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013805 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013806
Jeff Brown10e89712011-07-08 18:52:57 -070013807 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013808 if (false) {
13809 // Removing for now. Forcing GCs is not so useful anymore
13810 // with Dalvik, and the new memory level hint facility is
13811 // better for what we need to do these days.
13812 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
13813 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13814 // If this app is transitioning from foreground to
13815 // non-foreground, have it do a gc.
13816 scheduleAppGcLocked(app);
13817 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13818 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13819 // Likewise do a gc when an app is moving in to the
13820 // background (such as a service stopping).
13821 scheduleAppGcLocked(app);
13822 }
Jeff Brown10e89712011-07-08 18:52:57 -070013823 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013824
Jeff Brown10e89712011-07-08 18:52:57 -070013825 if (wasKeeping && !app.keeping) {
13826 // This app is no longer something we want to keep. Note
13827 // its current wake lock time to later know to kill it if
13828 // it is not behaving well.
13829 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13830 synchronized (stats) {
13831 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13832 app.pid, SystemClock.elapsedRealtime());
13833 }
13834 app.lastCpuTime = app.curCpuTime;
13835 }
13836
13837 app.setRawAdj = app.curRawAdj;
13838 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013839
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013840 if (app.curAdj != app.setAdj) {
13841 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013842 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013843 TAG, "Set " + app.pid + " " + app.processName +
13844 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013845 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013846 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013847 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013848 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013849 }
13850 }
13851 if (app.setSchedGroup != app.curSchedGroup) {
13852 app.setSchedGroup = app.curSchedGroup;
13853 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13854 "Setting process group of " + app.processName
13855 + " to " + app.curSchedGroup);
13856 if (app.waitingToKill != null &&
13857 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13858 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13859 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13860 app.processName, app.setAdj, app.waitingToKill);
13861 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013862 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013863 } else {
13864 if (true) {
13865 long oldId = Binder.clearCallingIdentity();
13866 try {
13867 Process.setProcessGroup(app.pid, app.curSchedGroup);
13868 } catch (Exception e) {
13869 Slog.w(TAG, "Failed setting process group of " + app.pid
13870 + " to " + app.curSchedGroup);
13871 e.printStackTrace();
13872 } finally {
13873 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013874 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013875 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013876 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013877 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013878 app.thread.setSchedulingGroup(app.curSchedGroup);
13879 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013880 }
13881 }
13882 }
13883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013884 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013885 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013886 }
13887
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013888 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013889 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013890 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013891 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013892 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013893 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013894 }
13895 }
13896 return resumedActivity;
13897 }
13898
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013899 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013900 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013901 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13902 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013903 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13904 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013905
13906 mAdjSeq++;
13907
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013908 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013909 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13910 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013911 if (nowHidden != wasHidden) {
13912 // Changed to/from hidden state, so apps after it in the LRU
13913 // list may also be changed.
13914 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013915 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013916 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013917 }
13918
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013919 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013920 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013921 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13922
13923 if (false) {
13924 RuntimeException e = new RuntimeException();
13925 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013926 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013927 }
13928
13929 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013930 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013931
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013932 // Let's determine how many processes we have running vs.
13933 // how many slots we have for background processes; we may want
13934 // to put multiple processes in a slot of there are enough of
13935 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013936 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013937 int factor = (mLruProcesses.size()-4)/numSlots;
13938 if (factor < 1) factor = 1;
13939 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013940 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013941
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013942 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013943 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013944 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013945 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013946 while (i > 0) {
13947 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013948 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013949 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013950 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
13951 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013952 && app.curAdj == curHiddenAdj) {
13953 step++;
13954 if (step >= factor) {
13955 step = 0;
13956 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013957 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013958 }
13959 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013960 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013961 numHidden++;
13962 if (numHidden > mProcessLimit) {
13963 Slog.i(TAG, "No longer want " + app.processName
13964 + " (pid " + app.pid + "): hidden #" + numHidden);
13965 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13966 app.processName, app.setAdj, "too many background");
13967 app.killedBackground = true;
13968 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013969 }
13970 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013971 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
13972 // If this is an isolated process, and there are no
13973 // services running in it, then the process is no longer
13974 // needed. We agressively kill these because we can by
13975 // definition not re-use the same process again, and it is
13976 // good to avoid having whatever code was running in them
13977 // left sitting around after no longer needed.
13978 Slog.i(TAG, "Isolated process " + app.processName
13979 + " (pid " + app.pid + ") no longer needed");
13980 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13981 app.processName, app.setAdj, "isolated not needed");
13982 app.killedBackground = true;
13983 Process.killProcessQuiet(app.pid);
13984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013985 }
13986 }
13987
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013988 mNumServiceProcs = mNewNumServiceProcs;
13989
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013990 // Now determine the memory trimming level of background processes.
13991 // Unfortunately we need to start at the back of the list to do this
13992 // properly. We only do this if the number of background apps we
13993 // are managing to keep around is less than half the maximum we desire;
13994 // if we are keeping a good number around, we'll let them use whatever
13995 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013996 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013997 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013998 factor = numHidden/3;
13999 int minFactor = 2;
14000 if (mHomeProcess != null) minFactor++;
14001 if (mPreviousProcess != null) minFactor++;
14002 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014003 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014004 int fgTrimLevel;
14005 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14006 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14007 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14008 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14009 } else {
14010 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14011 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014012 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014013 for (i=0; i<N; i++) {
14014 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014015 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14016 && app.curAdj != ProcessList.SERVICE_B_ADJ
14017 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014018 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14019 try {
14020 app.thread.scheduleTrimMemory(curLevel);
14021 } catch (RemoteException e) {
14022 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014023 if (false) {
14024 // For now we won't do this; our memory trimming seems
14025 // to be good enough at this point that destroying
14026 // activities causes more harm than good.
14027 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14028 && app != mHomeProcess && app != mPreviousProcess) {
14029 // For these apps we will also finish their activities
14030 // to help them free memory.
14031 mMainStack.destroyActivitiesLocked(app, false, "trim");
14032 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014033 }
14034 }
14035 app.trimMemoryLevel = curLevel;
14036 step++;
14037 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014038 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014039 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014040 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14041 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014042 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014043 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14044 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014045 break;
14046 }
14047 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014048 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014049 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014050 && app.thread != null) {
14051 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014052 app.thread.scheduleTrimMemory(
14053 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014054 } catch (RemoteException e) {
14055 }
14056 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014057 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014058 } else {
14059 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14060 && app.pendingUiClean) {
14061 // If this application is now in the background and it
14062 // had done UI, then give it the special trim level to
14063 // have it free UI resources.
14064 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14065 if (app.trimMemoryLevel < level && app.thread != null) {
14066 try {
14067 app.thread.scheduleTrimMemory(level);
14068 } catch (RemoteException e) {
14069 }
14070 }
14071 app.pendingUiClean = false;
14072 }
14073 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014074 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014075 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014076 } catch (RemoteException e) {
14077 }
14078 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014079 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014080 }
14081 }
14082 } else {
14083 final int N = mLruProcesses.size();
14084 for (i=0; i<N; i++) {
14085 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014086 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014087 && app.pendingUiClean) {
14088 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14089 && app.thread != null) {
14090 try {
14091 app.thread.scheduleTrimMemory(
14092 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14093 } catch (RemoteException e) {
14094 }
14095 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014096 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014097 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014098 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014099 }
14100 }
14101
14102 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014103 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014105 }
14106
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014107 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014108 synchronized (this) {
14109 int i;
14110
14111 // First remove any unused application processes whose package
14112 // has been removed.
14113 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14114 final ProcessRecord app = mRemovedProcesses.get(i);
14115 if (app.activities.size() == 0
14116 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014117 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014118 TAG, "Exiting empty application process "
14119 + app.processName + " ("
14120 + (app.thread != null ? app.thread.asBinder() : null)
14121 + ")\n");
14122 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014123 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14124 app.processName, app.setAdj, "empty");
14125 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014126 } else {
14127 try {
14128 app.thread.scheduleExit();
14129 } catch (Exception e) {
14130 // Ignore exceptions.
14131 }
14132 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014133 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014134 mRemovedProcesses.remove(i);
14135
14136 if (app.persistent) {
14137 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014138 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014139 }
14140 }
14141 }
14142 }
14143
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014144 // Now update the oom adj for all processes.
14145 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014146 }
14147 }
14148
14149 /** This method sends the specified signal to each of the persistent apps */
14150 public void signalPersistentProcesses(int sig) throws RemoteException {
14151 if (sig != Process.SIGNAL_USR1) {
14152 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14153 }
14154
14155 synchronized (this) {
14156 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14157 != PackageManager.PERMISSION_GRANTED) {
14158 throw new SecurityException("Requires permission "
14159 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14160 }
14161
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014162 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14163 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014164 if (r.thread != null && r.persistent) {
14165 Process.sendSignal(r.pid, sig);
14166 }
14167 }
14168 }
14169 }
14170
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014171 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14172 if (proc == null || proc == mProfileProc) {
14173 proc = mProfileProc;
14174 path = mProfileFile;
14175 profileType = mProfileType;
14176 clearProfilerLocked();
14177 }
14178 if (proc == null) {
14179 return;
14180 }
14181 try {
14182 proc.thread.profilerControl(false, path, null, profileType);
14183 } catch (RemoteException e) {
14184 throw new IllegalStateException("Process disappeared");
14185 }
14186 }
14187
14188 private void clearProfilerLocked() {
14189 if (mProfileFd != null) {
14190 try {
14191 mProfileFd.close();
14192 } catch (IOException e) {
14193 }
14194 }
14195 mProfileApp = null;
14196 mProfileProc = null;
14197 mProfileFile = null;
14198 mProfileType = 0;
14199 mAutoStopProfiler = false;
14200 }
14201
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014202 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014203 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014204
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014205 try {
14206 synchronized (this) {
14207 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14208 // its own permission.
14209 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14210 != PackageManager.PERMISSION_GRANTED) {
14211 throw new SecurityException("Requires permission "
14212 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014213 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014214
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014215 if (start && fd == null) {
14216 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014217 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014218
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014219 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014220 if (process != null) {
14221 try {
14222 int pid = Integer.parseInt(process);
14223 synchronized (mPidsSelfLocked) {
14224 proc = mPidsSelfLocked.get(pid);
14225 }
14226 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014227 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014228
14229 if (proc == null) {
14230 HashMap<String, SparseArray<ProcessRecord>> all
14231 = mProcessNames.getMap();
14232 SparseArray<ProcessRecord> procs = all.get(process);
14233 if (procs != null && procs.size() > 0) {
14234 proc = procs.valueAt(0);
14235 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014236 }
14237 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014238
14239 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014240 throw new IllegalArgumentException("Unknown process: " + process);
14241 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014242
14243 if (start) {
14244 stopProfilerLocked(null, null, 0);
14245 setProfileApp(proc.info, proc.processName, path, fd, false);
14246 mProfileProc = proc;
14247 mProfileType = profileType;
14248 try {
14249 fd = fd.dup();
14250 } catch (IOException e) {
14251 fd = null;
14252 }
14253 proc.thread.profilerControl(start, path, fd, profileType);
14254 fd = null;
14255 mProfileFd = null;
14256 } else {
14257 stopProfilerLocked(proc, path, profileType);
14258 if (fd != null) {
14259 try {
14260 fd.close();
14261 } catch (IOException e) {
14262 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014263 }
14264 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014265
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014266 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014267 }
14268 } catch (RemoteException e) {
14269 throw new IllegalStateException("Process disappeared");
14270 } finally {
14271 if (fd != null) {
14272 try {
14273 fd.close();
14274 } catch (IOException e) {
14275 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014276 }
14277 }
14278 }
Andy McFadden824c5102010-07-09 16:26:57 -070014279
14280 public boolean dumpHeap(String process, boolean managed,
14281 String path, ParcelFileDescriptor fd) throws RemoteException {
14282
14283 try {
14284 synchronized (this) {
14285 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14286 // its own permission (same as profileControl).
14287 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14288 != PackageManager.PERMISSION_GRANTED) {
14289 throw new SecurityException("Requires permission "
14290 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14291 }
14292
14293 if (fd == null) {
14294 throw new IllegalArgumentException("null fd");
14295 }
14296
14297 ProcessRecord proc = null;
14298 try {
14299 int pid = Integer.parseInt(process);
14300 synchronized (mPidsSelfLocked) {
14301 proc = mPidsSelfLocked.get(pid);
14302 }
14303 } catch (NumberFormatException e) {
14304 }
14305
14306 if (proc == null) {
14307 HashMap<String, SparseArray<ProcessRecord>> all
14308 = mProcessNames.getMap();
14309 SparseArray<ProcessRecord> procs = all.get(process);
14310 if (procs != null && procs.size() > 0) {
14311 proc = procs.valueAt(0);
14312 }
14313 }
14314
14315 if (proc == null || proc.thread == null) {
14316 throw new IllegalArgumentException("Unknown process: " + process);
14317 }
14318
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014319 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14320 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014321 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14322 throw new SecurityException("Process not debuggable: " + proc);
14323 }
14324 }
14325
14326 proc.thread.dumpHeap(managed, path, fd);
14327 fd = null;
14328 return true;
14329 }
14330 } catch (RemoteException e) {
14331 throw new IllegalStateException("Process disappeared");
14332 } finally {
14333 if (fd != null) {
14334 try {
14335 fd.close();
14336 } catch (IOException e) {
14337 }
14338 }
14339 }
14340 }
14341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014342 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14343 public void monitor() {
14344 synchronized (this) { }
14345 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014346
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014347 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014348 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14349 ProcessRecord processRecord = mLruProcesses.get(i);
14350 try {
14351 if (processRecord.thread != null) {
14352 processRecord.thread.setCoreSettings(settings);
14353 }
14354 } catch (RemoteException re) {
14355 /* ignore */
14356 }
14357 }
14358 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014359
14360 // Multi-user methods
14361
Amith Yamasani742a6712011-05-04 14:49:28 -070014362 private int mCurrentUserId;
14363 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014364 private ArrayList<UserListener> mUserListeners = new ArrayList<UserListener>(3);
14365
14366 public interface UserListener {
14367 public void onUserChanged(int userId);
14368
14369 public void onUserAdded(int userId);
14370
14371 public void onUserRemoved(int userId);
14372
14373 public void onUserLoggedOut(int userId);
14374 }
14375
14376 public void addUserListener(UserListener listener) {
14377 synchronized (this) {
14378 if (!mUserListeners.contains(listener)) {
14379 mUserListeners.add(listener);
14380 }
14381 }
14382 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014383
14384 public boolean switchUser(int userId) {
14385 final int callingUid = Binder.getCallingUid();
14386 if (callingUid != 0 && callingUid != Process.myUid()) {
14387 Slog.e(TAG, "Trying to switch user from unauthorized app");
14388 return false;
14389 }
14390 if (mCurrentUserId == userId)
14391 return true;
14392
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014393 ArrayList<UserListener> listeners;
14394
Amith Yamasani742a6712011-05-04 14:49:28 -070014395 synchronized (this) {
14396 // Check if user is already logged in, otherwise check if user exists first before
14397 // adding to the list of logged in users.
14398 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14399 if (!userExists(userId)) {
14400 return false;
14401 }
14402 mLoggedInUsers.append(userId, userId);
14403 }
14404
14405 mCurrentUserId = userId;
14406 boolean haveActivities = mMainStack.switchUser(userId);
14407 if (!haveActivities) {
14408 startHomeActivityLocked(userId);
14409 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014410
14411 listeners = (ArrayList<UserListener>) mUserListeners.clone();
14412 }
14413 // Inform the listeners
14414 for (UserListener listener : listeners) {
14415 listener.onUserChanged(userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070014416 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014417 return true;
14418 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014419
14420 private boolean userExists(int userId) {
14421 try {
14422 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14423 for (UserInfo user : users) {
14424 if (user.id == userId) {
14425 return true;
14426 }
14427 }
14428 } catch (RemoteException re) {
14429 // Won't happen, in same process
14430 }
14431
14432 return false;
14433 }
14434
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014435 private void checkValidCaller(int uid, int userId) {
14436 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14437
14438 throw new SecurityException("Caller uid=" + uid
14439 + " is not privileged to communicate with user=" + userId);
14440 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014441
14442 private int applyUserId(int uid, int userId) {
14443 return UserId.getUid(userId, uid);
14444 }
14445
14446 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014447 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014448 ApplicationInfo newInfo = new ApplicationInfo(info);
14449 newInfo.uid = applyUserId(info.uid, userId);
14450 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14451 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14452 + info.packageName;
14453 }
14454 return newInfo;
14455 }
14456
14457 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014458 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014459 || userId < 1) {
14460 return aInfo;
14461 }
14462
14463 ActivityInfo info = new ActivityInfo(aInfo);
14464 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14465 return info;
14466 }
14467
14468 static class ServiceMap {
14469
14470 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14471 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14472 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14473 mServicesByIntentPerUser = new SparseArray<
14474 HashMap<Intent.FilterComparison, ServiceRecord>>();
14475
14476 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14477 // TODO: Deal with global services
14478 if (DEBUG_MU)
14479 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14480 return getServices(callingUser).get(name);
14481 }
14482
14483 ServiceRecord getServiceByName(ComponentName name) {
14484 return getServiceByName(name, -1);
14485 }
14486
14487 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14488 // TODO: Deal with global services
14489 if (DEBUG_MU)
14490 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14491 return getServicesByIntent(callingUser).get(filter);
14492 }
14493
14494 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14495 return getServiceByIntent(filter, -1);
14496 }
14497
14498 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14499 // TODO: Deal with global services
14500 getServices(callingUser).put(name, value);
14501 }
14502
14503 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14504 ServiceRecord value) {
14505 // TODO: Deal with global services
14506 getServicesByIntent(callingUser).put(filter, value);
14507 }
14508
14509 void removeServiceByName(ComponentName name, int callingUser) {
14510 // TODO: Deal with global services
14511 ServiceRecord removed = getServices(callingUser).remove(name);
14512 if (DEBUG_MU)
14513 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14514 + " removed=" + removed);
14515 }
14516
14517 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14518 // TODO: Deal with global services
14519 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14520 if (DEBUG_MU)
14521 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14522 + " removed=" + removed);
14523 }
14524
14525 Collection<ServiceRecord> getAllServices(int callingUser) {
14526 // TODO: Deal with global services
14527 return getServices(callingUser).values();
14528 }
14529
14530 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14531 HashMap map = mServicesByNamePerUser.get(callingUser);
14532 if (map == null) {
14533 map = new HashMap<ComponentName, ServiceRecord>();
14534 mServicesByNamePerUser.put(callingUser, map);
14535 }
14536 return map;
14537 }
14538
14539 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14540 int callingUser) {
14541 HashMap map = mServicesByIntentPerUser.get(callingUser);
14542 if (map == null) {
14543 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14544 mServicesByIntentPerUser.put(callingUser, map);
14545 }
14546 return map;
14547 }
14548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014549}