blob: 8a5e7fc84a7bf83d034e99d73d01f8abc542fd54 [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 Hackborn94cb2eb2011-01-13 21:09:44 -08002795 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002796 mMainStack.mHistory.remove(i);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002797 r.takeFromHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002798 mWindowManager.removeAppToken(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002800 mMainStack.validateAppTokensLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002802 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803
2804 } else {
2805 // We have the current state for this activity, so
2806 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002807 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 TAG, "Keeping entry, setting app to null");
2809 if (r.visible) {
2810 hasVisibleActivities = true;
2811 }
2812 r.app = null;
2813 r.nowVisible = false;
2814 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002815 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2816 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 r.icicle = null;
2818 }
2819 }
2820
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002821 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 }
2823 atTop = false;
2824 }
2825
2826 app.activities.clear();
2827
2828 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002829 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 + " running instrumentation " + app.instrumentationClass);
2831 Bundle info = new Bundle();
2832 info.putString("shortMsg", "Process crashed.");
2833 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2834 }
2835
2836 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002837 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 // If there was nothing to resume, and we are not already
2839 // restarting this process, but there is a visible activity that
2840 // is hosted by the process... then make sure all visible
2841 // activities are running, taking care of restarting this
2842 // process.
2843 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002844 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 }
2846 }
2847 }
2848 }
2849
2850 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2851 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002853 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2854 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2856 return i;
2857 }
2858 }
2859 return -1;
2860 }
2861
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002862 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 IApplicationThread thread) {
2864 if (thread == null) {
2865 return null;
2866 }
2867
2868 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002869 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 }
2871
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002872 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 IApplicationThread thread) {
2874
2875 mProcDeaths[0]++;
2876
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002877 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2878 synchronized (stats) {
2879 stats.noteProcessDiedLocked(app.info.uid, pid);
2880 }
2881
Magnus Edlund7bb25812010-02-24 15:45:06 +01002882 // Clean up already done if the process has been re-started.
2883 if (app.pid == pid && app.thread != null &&
2884 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002885 if (!app.killedBackground) {
2886 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2887 + ") has died.");
2888 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002889 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002890 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 TAG, "Dying app: " + app + ", pid: " + pid
2892 + ", thread: " + thread.asBinder());
2893 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002894 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895
2896 if (doLowMem) {
2897 // If there are no longer any background processes running,
2898 // and the app that died was not running instrumentation,
2899 // then tell everyone we are now low on memory.
2900 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002901 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2902 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002903 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 haveBg = true;
2905 break;
2906 }
2907 }
2908
2909 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002910 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002911 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002912 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2913 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002914 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002915 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2916 // The low memory report is overriding any current
2917 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002918 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002919 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002920 rec.lastRequestedGc = 0;
2921 } else {
2922 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002924 rec.reportLowMemory = true;
2925 rec.lastLowMemory = now;
2926 mProcessesToGc.remove(rec);
2927 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 }
2929 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002930 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002931 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 }
2933 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002934 } else if (app.pid != pid) {
2935 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002936 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002937 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002938 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002939 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002940 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 + thread.asBinder());
2942 }
2943 }
2944
Dan Egnor42471dd2010-01-07 17:25:22 -08002945 /**
2946 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002947 * @param clearTraces causes the dump file to be erased prior to the new
2948 * traces being written, if true; when false, the new traces will be
2949 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002950 * @param firstPids of dalvik VM processes to dump stack traces for first
2951 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002952 * @return file containing stack traces, or null if no dump file is configured
2953 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002954 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2955 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002956 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2957 if (tracesPath == null || tracesPath.length() == 0) {
2958 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002960
2961 File tracesFile = new File(tracesPath);
2962 try {
2963 File tracesDir = tracesFile.getParentFile();
2964 if (!tracesDir.exists()) tracesFile.mkdirs();
2965 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2966
Christopher Tate6ee412d2010-05-28 12:01:56 -07002967 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002968 tracesFile.createNewFile();
2969 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2970 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002971 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002972 return null;
2973 }
2974
2975 // Use a FileObserver to detect when traces finish writing.
2976 // The order of traces is considered important to maintain for legibility.
2977 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2978 public synchronized void onEvent(int event, String path) { notify(); }
2979 };
2980
2981 try {
2982 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002983
2984 // First collect all of the stacks of the most important pids.
2985 try {
2986 int num = firstPids.size();
2987 for (int i = 0; i < num; i++) {
2988 synchronized (observer) {
2989 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2990 observer.wait(200); // Wait for write-close, give up after 200msec
2991 }
2992 }
2993 } catch (InterruptedException e) {
2994 Log.wtf(TAG, e);
2995 }
2996
2997 // Next measure CPU usage.
2998 if (processStats != null) {
2999 processStats.init();
3000 System.gc();
3001 processStats.update();
3002 try {
3003 synchronized (processStats) {
3004 processStats.wait(500); // measure over 1/2 second.
3005 }
3006 } catch (InterruptedException e) {
3007 }
3008 processStats.update();
3009
3010 // We'll take the stack crawls of just the top apps using CPU.
3011 final int N = processStats.countWorkingStats();
3012 int numProcs = 0;
3013 for (int i=0; i<N && numProcs<5; i++) {
3014 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3015 if (lastPids.indexOfKey(stats.pid) >= 0) {
3016 numProcs++;
3017 try {
3018 synchronized (observer) {
3019 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3020 observer.wait(200); // Wait for write-close, give up after 200msec
3021 }
3022 } catch (InterruptedException e) {
3023 Log.wtf(TAG, e);
3024 }
3025
3026 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003027 }
3028 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003029
3030 return tracesFile;
3031
Dan Egnor42471dd2010-01-07 17:25:22 -08003032 } finally {
3033 observer.stopWatching();
3034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 }
3036
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003037 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3038 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003039 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3040 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3041
Dianne Hackborn287952c2010-09-22 22:34:31 -07003042 if (mController != null) {
3043 try {
3044 // 0 == continue, -1 = kill process immediately
3045 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3046 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3047 } catch (RemoteException e) {
3048 mController = null;
3049 }
3050 }
3051
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003052 long anrTime = SystemClock.uptimeMillis();
3053 if (MONITOR_CPU_USAGE) {
3054 updateCpuStatsNow();
3055 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003056
3057 synchronized (this) {
3058 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3059 if (mShuttingDown) {
3060 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3061 return;
3062 } else if (app.notResponding) {
3063 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3064 return;
3065 } else if (app.crashing) {
3066 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3067 return;
3068 }
3069
3070 // In case we come through here for the same app before completing
3071 // this one, mark as anring now so we will bail out.
3072 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003073
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003074 // Log the ANR to the event log.
3075 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3076 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003077
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003078 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003079 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003080
3081 int parentPid = app.pid;
3082 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003083 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003084
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003085 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003086
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003087 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3088 ProcessRecord r = mLruProcesses.get(i);
3089 if (r != null && r.thread != null) {
3090 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003091 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3092 if (r.persistent) {
3093 firstPids.add(pid);
3094 } else {
3095 lastPids.put(pid, Boolean.TRUE);
3096 }
3097 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 }
3100 }
3101
Dan Egnor42471dd2010-01-07 17:25:22 -08003102 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003103 StringBuilder info = mStringBuilder;
3104 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003105 info.append("ANR in ").append(app.processName);
3106 if (activity != null && activity.shortComponentName != null) {
3107 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003108 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003109 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003111 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003113 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003114 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116
Dianne Hackborn287952c2010-09-22 22:34:31 -07003117 final ProcessStats processStats = new ProcessStats(true);
3118
3119 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3120
Dan Egnor42471dd2010-01-07 17:25:22 -08003121 String cpuInfo = null;
3122 if (MONITOR_CPU_USAGE) {
3123 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003124 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003125 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003126 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003127 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003128 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 }
3130
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003131 info.append(processStats.printCurrentState(anrTime));
3132
Joe Onorato8a9b2202010-02-26 18:56:32 -08003133 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003134 if (tracesFile == null) {
3135 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3136 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3137 }
3138
Jeff Sharkeya353d262011-10-28 11:12:06 -07003139 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3140 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003141
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003142 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003144 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3145 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003147 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3148 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 }
3150 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003151 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152 }
3153 }
3154
Dan Egnor42471dd2010-01-07 17:25:22 -08003155 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3156 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3157 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003158
3159 synchronized (this) {
3160 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003161 Slog.w(TAG, "Killing " + app + ": background ANR");
3162 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3163 app.processName, app.setAdj, "background ANR");
3164 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003165 return;
3166 }
3167
3168 // Set the app's notResponding state, and look up the errorReportReceiver
3169 makeAppNotRespondingLocked(app,
3170 activity != null ? activity.shortComponentName : null,
3171 annotation != null ? "ANR " + annotation : "ANR",
3172 info.toString());
3173
3174 // Bring up the infamous App Not Responding dialog
3175 Message msg = Message.obtain();
3176 HashMap map = new HashMap();
3177 msg.what = SHOW_NOT_RESPONDING_MSG;
3178 msg.obj = map;
3179 map.put("app", app);
3180 if (activity != null) {
3181 map.put("activity", activity);
3182 }
3183
3184 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 }
3187
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003188 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3189 if (!mLaunchWarningShown) {
3190 mLaunchWarningShown = true;
3191 mHandler.post(new Runnable() {
3192 @Override
3193 public void run() {
3194 synchronized (ActivityManagerService.this) {
3195 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3196 d.show();
3197 mHandler.postDelayed(new Runnable() {
3198 @Override
3199 public void run() {
3200 synchronized (ActivityManagerService.this) {
3201 d.dismiss();
3202 mLaunchWarningShown = false;
3203 }
3204 }
3205 }, 4000);
3206 }
3207 }
3208 });
3209 }
3210 }
3211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003213 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003214 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 int uid = Binder.getCallingUid();
3216 int pid = Binder.getCallingPid();
3217 long callingId = Binder.clearCallingIdentity();
3218 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003219 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 int pkgUid = -1;
3221 synchronized(this) {
3222 try {
3223 pkgUid = pm.getPackageUid(packageName);
3224 } catch (RemoteException e) {
3225 }
3226 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003227 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 return false;
3229 }
3230 if (uid == pkgUid || checkComponentPermission(
3231 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003232 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003234 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235 } else {
3236 throw new SecurityException(pid+" does not have permission:"+
3237 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3238 "for process:"+packageName);
3239 }
3240 }
3241
3242 try {
3243 //clear application user data
3244 pm.clearApplicationUserData(packageName, observer);
3245 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3246 Uri.fromParts("package", packageName, null));
3247 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003248 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003249 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 } catch (RemoteException e) {
3251 }
3252 } finally {
3253 Binder.restoreCallingIdentity(callingId);
3254 }
3255 return true;
3256 }
3257
Dianne Hackborn03abb812010-01-04 18:43:19 -08003258 public void killBackgroundProcesses(final String packageName) {
3259 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3260 != PackageManager.PERMISSION_GRANTED &&
3261 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3262 != PackageManager.PERMISSION_GRANTED) {
3263 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 + Binder.getCallingPid()
3265 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003266 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003267 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 throw new SecurityException(msg);
3269 }
3270
3271 long callingId = Binder.clearCallingIdentity();
3272 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003273 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 int pkgUid = -1;
3275 synchronized(this) {
3276 try {
3277 pkgUid = pm.getPackageUid(packageName);
3278 } catch (RemoteException e) {
3279 }
3280 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003281 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 return;
3283 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003284 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003285 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3286 }
3287 } finally {
3288 Binder.restoreCallingIdentity(callingId);
3289 }
3290 }
3291
3292 public void killAllBackgroundProcesses() {
3293 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3294 != PackageManager.PERMISSION_GRANTED) {
3295 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3296 + Binder.getCallingPid()
3297 + ", uid=" + Binder.getCallingUid()
3298 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3299 Slog.w(TAG, msg);
3300 throw new SecurityException(msg);
3301 }
3302
3303 long callingId = Binder.clearCallingIdentity();
3304 try {
3305 synchronized(this) {
3306 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3307 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3308 final int NA = apps.size();
3309 for (int ia=0; ia<NA; ia++) {
3310 ProcessRecord app = apps.valueAt(ia);
3311 if (app.persistent) {
3312 // we don't kill persistent processes
3313 continue;
3314 }
3315 if (app.removed) {
3316 procs.add(app);
3317 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3318 app.removed = true;
3319 procs.add(app);
3320 }
3321 }
3322 }
3323
3324 int N = procs.size();
3325 for (int i=0; i<N; i++) {
3326 removeProcessLocked(procs.get(i), false, true, "kill all background");
3327 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003328 }
3329 } finally {
3330 Binder.restoreCallingIdentity(callingId);
3331 }
3332 }
3333
3334 public void forceStopPackage(final String packageName) {
3335 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3336 != PackageManager.PERMISSION_GRANTED) {
3337 String msg = "Permission Denial: forceStopPackage() from pid="
3338 + Binder.getCallingPid()
3339 + ", uid=" + Binder.getCallingUid()
3340 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003341 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003342 throw new SecurityException(msg);
3343 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003344 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003345 long callingId = Binder.clearCallingIdentity();
3346 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003347 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003348 int pkgUid = -1;
3349 synchronized(this) {
3350 try {
3351 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07003352 // Convert the uid to the one for the calling user
3353 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003354 } catch (RemoteException e) {
3355 }
3356 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003357 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003358 return;
3359 }
3360 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003361 try {
3362 pm.setPackageStoppedState(packageName, true);
3363 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003364 } catch (IllegalArgumentException e) {
3365 Slog.w(TAG, "Failed trying to unstop package "
3366 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 }
3369 } finally {
3370 Binder.restoreCallingIdentity(callingId);
3371 }
3372 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003373
3374 /*
3375 * The pkg name and uid have to be specified.
3376 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3377 */
3378 public void killApplicationWithUid(String pkg, int uid) {
3379 if (pkg == null) {
3380 return;
3381 }
3382 // Make sure the uid is valid.
3383 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003384 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003385 return;
3386 }
3387 int callerUid = Binder.getCallingUid();
3388 // Only the system server can kill an application
3389 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003390 // Post an aysnc message to kill the application
3391 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3392 msg.arg1 = uid;
3393 msg.arg2 = 0;
3394 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003395 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003396 } else {
3397 throw new SecurityException(callerUid + " cannot kill pkg: " +
3398 pkg);
3399 }
3400 }
3401
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003402 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003403 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003404 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003405 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003406 if (reason != null) {
3407 intent.putExtra("reason", reason);
3408 }
3409
3410 final int uid = Binder.getCallingUid();
3411 final long origId = Binder.clearCallingIdentity();
3412 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003413 mWindowManager.closeSystemDialogs(reason);
3414
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003415 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003416 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003417 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003418 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003419 Activity.RESULT_CANCELED, null, "close-sys");
3420 }
3421 }
3422
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003423 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003424 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003425 }
3426 Binder.restoreCallingIdentity(origId);
3427 }
3428
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003429 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003430 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003431 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003432 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3433 for (int i=pids.length-1; i>=0; i--) {
3434 infos[i] = new Debug.MemoryInfo();
3435 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003436 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003437 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003438 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003439
Dianne Hackbornb437e092011-08-05 17:50:29 -07003440 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003441 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003442 long[] pss = new long[pids.length];
3443 for (int i=pids.length-1; i>=0; i--) {
3444 pss[i] = Debug.getPss(pids[i]);
3445 }
3446 return pss;
3447 }
3448
Christopher Tate5e1ab332009-09-01 20:32:49 -07003449 public void killApplicationProcess(String processName, int uid) {
3450 if (processName == null) {
3451 return;
3452 }
3453
3454 int callerUid = Binder.getCallingUid();
3455 // Only the system server can kill an application
3456 if (callerUid == Process.SYSTEM_UID) {
3457 synchronized (this) {
3458 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003459 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003460 try {
3461 app.thread.scheduleSuicide();
3462 } catch (RemoteException e) {
3463 // If the other end already died, then our work here is done.
3464 }
3465 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003466 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003467 + processName + " / " + uid);
3468 }
3469 }
3470 } else {
3471 throw new SecurityException(callerUid + " cannot kill app process: " +
3472 processName);
3473 }
3474 }
3475
Dianne Hackborn03abb812010-01-04 18:43:19 -08003476 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07003477 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3479 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003480 if (!mProcessesReady) {
3481 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 intent.putExtra(Intent.EXTRA_UID, uid);
3484 broadcastIntentLocked(null, null, intent,
3485 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003486 false, false,
3487 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 }
3489
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003490 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003491 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003492 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003493 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494
Dianne Hackborn03abb812010-01-04 18:43:19 -08003495 // Remove all processes this package may have touched: all with the
3496 // same UID (except for the system or root user), and all whose name
3497 // matches the package name.
3498 final String procNamePrefix = packageName + ":";
3499 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3500 final int NA = apps.size();
3501 for (int ia=0; ia<NA; ia++) {
3502 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003503 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003504 // we don't kill persistent processes
3505 continue;
3506 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003507 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003508 if (doit) {
3509 procs.add(app);
3510 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003511 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3512 || app.processName.equals(packageName)
3513 || app.processName.startsWith(procNamePrefix)) {
3514 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003515 if (!doit) {
3516 return true;
3517 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003518 app.removed = true;
3519 procs.add(app);
3520 }
3521 }
3522 }
3523 }
3524
3525 int N = procs.size();
3526 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003527 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003528 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003529 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003530 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003531
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003532 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003533 boolean callerWillRestart, boolean purgeCache, boolean doit,
3534 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003535 int i;
3536 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 if (uid < 0) {
3539 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003540 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 } catch (RemoteException e) {
3542 }
3543 }
3544
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003545 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003546 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003547
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003548 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3549 while (badApps.hasNext()) {
3550 SparseArray<Long> ba = badApps.next();
3551 if (ba.get(uid) != null) {
3552 badApps.remove();
3553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554 }
3555 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003556
3557 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003558 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003560 TaskRecord lastTask = null;
3561 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003562 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003563 final boolean samePackage = r.packageName.equals(name);
3564 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003565 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003566 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003567 if (r.finishing) {
3568 // If this activity is just finishing, then it is not
3569 // interesting as far as something to stop.
3570 continue;
3571 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003572 return true;
3573 }
3574 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003575 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003576 if (samePackage) {
3577 if (r.app != null) {
3578 r.app.removed = true;
3579 }
3580 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003582 lastTask = r.task;
3583 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3584 null, "force-stop")) {
3585 i--;
3586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 }
3588 }
3589
3590 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003591 int userId = UserId.getUserId(uid);
3592 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003593 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003594 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003595 if (!doit) {
3596 return true;
3597 }
3598 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003599 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600 if (service.app != null) {
3601 service.app.removed = true;
3602 }
3603 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003604 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003605 services.add(service);
3606 }
3607 }
3608
3609 N = services.size();
3610 for (i=0; i<N; i++) {
3611 bringDownServiceLocked(services.get(i), true);
3612 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003613
3614 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani37ce3a82012-02-06 12:04:42 -08003615 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(-1).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003616 if (provider.info.packageName.equals(name)
3617 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3618 if (!doit) {
3619 return true;
3620 }
3621 didSomething = true;
3622 providers.add(provider);
3623 }
3624 }
3625
3626 N = providers.size();
3627 for (i=0; i<N; i++) {
3628 removeDyingProviderLocked(null, providers.get(i));
3629 }
3630
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003631 if (doit) {
3632 if (purgeCache) {
3633 AttributeCache ac = AttributeCache.instance();
3634 if (ac != null) {
3635 ac.removePackage(name);
3636 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003637 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003638 if (mBooted) {
3639 mMainStack.resumeTopActivityLocked(null);
3640 mMainStack.scheduleIdleLocked();
3641 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003642 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003643
3644 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 }
3646
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003647 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003648 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003650 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003651 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003652 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 + "/" + uid + ")");
3654
3655 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003656 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003657 if (mHeavyWeightProcess == app) {
3658 mHeavyWeightProcess = null;
3659 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 boolean needRestart = false;
3662 if (app.pid > 0 && app.pid != MY_PID) {
3663 int pid = app.pid;
3664 synchronized (mPidsSelfLocked) {
3665 mPidsSelfLocked.remove(pid);
3666 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3667 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003668 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003669 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003670 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003671 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003673 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003675 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 } else {
3677 needRestart = true;
3678 }
3679 }
3680 } else {
3681 mRemovedProcesses.add(app);
3682 }
3683
3684 return needRestart;
3685 }
3686
3687 private final void processStartTimedOutLocked(ProcessRecord app) {
3688 final int pid = app.pid;
3689 boolean gone = false;
3690 synchronized (mPidsSelfLocked) {
3691 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3692 if (knownApp != null && knownApp.thread == null) {
3693 mPidsSelfLocked.remove(pid);
3694 gone = true;
3695 }
3696 }
3697
3698 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003699 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003700 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003701 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003702 mProcessNames.remove(app.processName, app.uid);
3703 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003704 if (mHeavyWeightProcess == app) {
3705 mHeavyWeightProcess = null;
3706 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3707 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003708 // Take care of any launching providers waiting for this process.
3709 checkAppInLaunchingProvidersLocked(app, true);
3710 // Take care of any services that are waiting for the process.
3711 for (int i=0; i<mPendingServices.size(); i++) {
3712 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003713 if ((app.uid == sr.appInfo.uid
3714 && app.processName.equals(sr.processName))
3715 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003716 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003717 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003718 mPendingServices.remove(i);
3719 i--;
3720 bringDownServiceLocked(sr, true);
3721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003723 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3724 app.processName, app.setAdj, "start timeout");
3725 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003726 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003727 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003728 try {
3729 IBackupManager bm = IBackupManager.Stub.asInterface(
3730 ServiceManager.getService(Context.BACKUP_SERVICE));
3731 bm.agentDisconnected(app.info.packageName);
3732 } catch (RemoteException e) {
3733 // Can't happen; the backup manager is local
3734 }
3735 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003736 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003737 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003738 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003741 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742 }
3743 }
3744
3745 private final boolean attachApplicationLocked(IApplicationThread thread,
3746 int pid) {
3747
3748 // Find the application record that is being attached... either via
3749 // the pid if we are running in multiple processes, or just pull the
3750 // next app record if we are emulating process with anonymous threads.
3751 ProcessRecord app;
3752 if (pid != MY_PID && pid >= 0) {
3753 synchronized (mPidsSelfLocked) {
3754 app = mPidsSelfLocked.get(pid);
3755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 } else {
3757 app = null;
3758 }
3759
3760 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003761 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003763 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003765 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 } else {
3767 try {
3768 thread.scheduleExit();
3769 } catch (Exception e) {
3770 // Ignore exceptions.
3771 }
3772 }
3773 return false;
3774 }
3775
3776 // If this application record is still attached to a previous
3777 // process, clean it up now.
3778 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003779 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780 }
3781
3782 // Tell the process all about itself.
3783
Joe Onorato8a9b2202010-02-26 18:56:32 -08003784 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785 TAG, "Binding process pid " + pid + " to record " + app);
3786
3787 String processName = app.processName;
3788 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003789 AppDeathRecipient adr = new AppDeathRecipient(
3790 app, pid, thread);
3791 thread.asBinder().linkToDeath(adr, 0);
3792 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 } catch (RemoteException e) {
3794 app.resetPackageList();
3795 startProcessLocked(app, "link fail", processName);
3796 return false;
3797 }
3798
Doug Zongker2bec3d42009-12-04 12:52:44 -08003799 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800
3801 app.thread = thread;
3802 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003803 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3804 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 app.forcingToForeground = null;
3806 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003807 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 app.debugging = false;
3809
3810 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3811
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003812 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003813 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003815 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003816 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003817 }
3818
Joe Onorato8a9b2202010-02-26 18:56:32 -08003819 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 TAG, "New app record " + app
3821 + " thread=" + thread.asBinder() + " pid=" + pid);
3822 try {
3823 int testMode = IApplicationThread.DEBUG_OFF;
3824 if (mDebugApp != null && mDebugApp.equals(processName)) {
3825 testMode = mWaitForDebugger
3826 ? IApplicationThread.DEBUG_WAIT
3827 : IApplicationThread.DEBUG_ON;
3828 app.debugging = true;
3829 if (mDebugTransient) {
3830 mDebugApp = mOrigDebugApp;
3831 mWaitForDebugger = mOrigWaitForDebugger;
3832 }
3833 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003834 String profileFile = app.instrumentationProfileFile;
3835 ParcelFileDescriptor profileFd = null;
3836 boolean profileAutoStop = false;
3837 if (mProfileApp != null && mProfileApp.equals(processName)) {
3838 mProfileProc = app;
3839 profileFile = mProfileFile;
3840 profileFd = mProfileFd;
3841 profileAutoStop = mAutoStopProfiler;
3842 }
3843
Christopher Tate181fafa2009-05-14 11:12:14 -07003844 // If the app is being launched for restore or full backup, set it up specially
3845 boolean isRestrictedBackupMode = false;
3846 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3847 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003848 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003849 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3850 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003851
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003852 ensurePackageDexOpt(app.instrumentationInfo != null
3853 ? app.instrumentationInfo.packageName
3854 : app.info.packageName);
3855 if (app.instrumentationClass != null) {
3856 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003857 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003858 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003859 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003860 ApplicationInfo appInfo = app.instrumentationInfo != null
3861 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003862 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003863 if (profileFd != null) {
3864 profileFd = profileFd.dup();
3865 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003866 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003867 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003869 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003870 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003871 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003872 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003873 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 } catch (Exception e) {
3875 // todo: Yikes! What should we do? For now we will try to
3876 // start another process, but that could easily get us in
3877 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003878 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879
3880 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003881 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 startProcessLocked(app, "bind fail", processName);
3883 return false;
3884 }
3885
3886 // Remove this record from the list of starting applications.
3887 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003888 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3889 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 mProcessesOnHold.remove(app);
3891
3892 boolean badApp = false;
3893 boolean didSomething = false;
3894
3895 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003896 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003897 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003898 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 && processName.equals(hr.processName)) {
3900 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003901 if (mHeadless) {
3902 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3903 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 didSomething = true;
3905 }
3906 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003907 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 + hr.intent.getComponent().flattenToShortString(), e);
3909 badApp = true;
3910 }
3911 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003912 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 }
3914 }
3915
3916 // Find any services that should be running in this process...
3917 if (!badApp && mPendingServices.size() > 0) {
3918 ServiceRecord sr = null;
3919 try {
3920 for (int i=0; i<mPendingServices.size(); i++) {
3921 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003922 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
3923 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 continue;
3925 }
3926
3927 mPendingServices.remove(i);
3928 i--;
3929 realStartServiceLocked(sr, app);
3930 didSomething = true;
3931 }
3932 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003933 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 + sr.shortName, e);
3935 badApp = true;
3936 }
3937 }
3938
Christopher Tatef46723b2012-01-26 14:19:24 -08003939 // Check if a next-broadcast receiver is in this process...
3940 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08003942 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08003944 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 }
3947 }
3948
Christopher Tate181fafa2009-05-14 11:12:14 -07003949 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003950 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003951 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003952 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003953 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003954 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
3955 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
3956 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07003957 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003958 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003959 e.printStackTrace();
3960 }
3961 }
3962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 if (badApp) {
3964 // todo: Also need to kill application to deal with all
3965 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003966 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 return false;
3968 }
3969
3970 if (!didSomething) {
3971 updateOomAdjLocked();
3972 }
3973
3974 return true;
3975 }
3976
3977 public final void attachApplication(IApplicationThread thread) {
3978 synchronized (this) {
3979 int callingPid = Binder.getCallingPid();
3980 final long origId = Binder.clearCallingIdentity();
3981 attachApplicationLocked(thread, callingPid);
3982 Binder.restoreCallingIdentity(origId);
3983 }
3984 }
3985
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003986 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003988 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
3989 if (stopProfiling) {
3990 synchronized (this) {
3991 if (mProfileProc == r.app) {
3992 if (mProfileFd != null) {
3993 try {
3994 mProfileFd.close();
3995 } catch (IOException e) {
3996 }
3997 clearProfilerLocked();
3998 }
3999 }
4000 }
4001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 Binder.restoreCallingIdentity(origId);
4003 }
4004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004006 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004007 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 mWindowManager.enableScreenAfterBoot();
4009 }
4010
Dianne Hackborn661cd522011-08-22 00:26:20 -07004011 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004012 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004013 mWindowManager.showBootMessage(msg, always);
4014 }
4015
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004016 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004017 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004018 synchronized (this) {
4019 mMainStack.dismissKeyguardOnNextActivityLocked();
4020 }
4021 }
4022
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004023 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004024 IntentFilter pkgFilter = new IntentFilter();
4025 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4026 pkgFilter.addDataScheme("package");
4027 mContext.registerReceiver(new BroadcastReceiver() {
4028 @Override
4029 public void onReceive(Context context, Intent intent) {
4030 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4031 if (pkgs != null) {
4032 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004033 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004034 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004035 setResultCode(Activity.RESULT_OK);
4036 return;
4037 }
4038 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004039 }
4040 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004041 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004042 }, pkgFilter);
4043
4044 synchronized (this) {
4045 // Ensure that any processes we had put on hold are now started
4046 // up.
4047 final int NP = mProcessesOnHold.size();
4048 if (NP > 0) {
4049 ArrayList<ProcessRecord> procs =
4050 new ArrayList<ProcessRecord>(mProcessesOnHold);
4051 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004052 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4053 + procs.get(ip));
4054 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004055 }
4056 }
4057
4058 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004059 // Start looking for apps that are abusing wake locks.
4060 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004061 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004062 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004063 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004064 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004065 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004066 broadcastIntentLocked(null, null,
4067 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4068 null, null, 0, null, null,
4069 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004070 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004071 }
4072 }
4073 }
4074
4075 final void ensureBootCompleted() {
4076 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004077 boolean enableScreen;
4078 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004079 booting = mBooting;
4080 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004081 enableScreen = !mBooted;
4082 mBooted = true;
4083 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004084
4085 if (booting) {
4086 finishBooting();
4087 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004088
4089 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004090 enableScreenAfterBoot();
4091 }
4092 }
4093
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004094 public final void activityPaused(IBinder token) {
4095 final long origId = Binder.clearCallingIdentity();
4096 mMainStack.activityPaused(token, false);
4097 Binder.restoreCallingIdentity(origId);
4098 }
4099
4100 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4101 CharSequence description) {
4102 if (localLOGV) Slog.v(
4103 TAG, "Activity stopped: token=" + token);
4104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 // Refuse possible leaked file descriptors
4106 if (icicle != null && icicle.hasFileDescriptors()) {
4107 throw new IllegalArgumentException("File descriptors passed in Bundle");
4108 }
4109
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004110 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111
4112 final long origId = Binder.clearCallingIdentity();
4113
4114 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004115 r = mMainStack.isInStackLocked(token);
4116 if (r != null) {
4117 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 }
4119 }
4120
4121 if (r != null) {
4122 sendPendingThumbnail(r, null, null, null, false);
4123 }
4124
4125 trimApplications();
4126
4127 Binder.restoreCallingIdentity(origId);
4128 }
4129
4130 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004131 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004132 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 }
4134
4135 public String getCallingPackage(IBinder token) {
4136 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004137 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004138 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 }
4140 }
4141
4142 public ComponentName getCallingActivity(IBinder token) {
4143 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004144 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 return r != null ? r.intent.getComponent() : null;
4146 }
4147 }
4148
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004149 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004150 ActivityRecord r = mMainStack.isInStackLocked(token);
4151 if (r == null) {
4152 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004154 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 }
4156
4157 public ComponentName getActivityClassForToken(IBinder token) {
4158 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004159 ActivityRecord r = mMainStack.isInStackLocked(token);
4160 if (r == null) {
4161 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004163 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 }
4165 }
4166
4167 public String getPackageForToken(IBinder token) {
4168 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004169 ActivityRecord r = mMainStack.isInStackLocked(token);
4170 if (r == null) {
4171 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004173 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 }
4175 }
4176
4177 public IIntentSender getIntentSender(int type,
4178 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004179 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004180 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004182 if (intents != null) {
4183 if (intents.length < 1) {
4184 throw new IllegalArgumentException("Intents array length must be >= 1");
4185 }
4186 for (int i=0; i<intents.length; i++) {
4187 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004188 if (intent != null) {
4189 if (intent.hasFileDescriptors()) {
4190 throw new IllegalArgumentException("File descriptors passed in Intent");
4191 }
4192 if (type == INTENT_SENDER_BROADCAST &&
4193 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4194 throw new IllegalArgumentException(
4195 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4196 }
4197 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004198 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004199 }
4200 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004201 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004202 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004203 }
4204 }
4205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 synchronized(this) {
4207 int callingUid = Binder.getCallingUid();
4208 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004209 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004210 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004212 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 String msg = "Permission Denial: getIntentSender() from pid="
4214 + Binder.getCallingPid()
4215 + ", uid=" + Binder.getCallingUid()
4216 + ", (need uid=" + uid + ")"
4217 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004218 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004219 throw new SecurityException(msg);
4220 }
4221 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004222
Amith Yamasani742a6712011-05-04 14:49:28 -07004223 if (DEBUG_MU)
4224 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4225 + Binder.getOrigCallingUid());
4226 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004227 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229 } catch (RemoteException e) {
4230 throw new SecurityException(e);
4231 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004232 }
4233 }
4234
4235 IIntentSender getIntentSenderLocked(int type,
4236 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004237 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004238 if (DEBUG_MU)
4239 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004240 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004241 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004242 activity = mMainStack.isInStackLocked(token);
4243 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004244 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004246 if (activity.finishing) {
4247 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004249 }
4250
4251 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4252 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4253 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4254 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4255 |PendingIntent.FLAG_UPDATE_CURRENT);
4256
4257 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4258 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004259 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004260 WeakReference<PendingIntentRecord> ref;
4261 ref = mIntentSenderRecords.get(key);
4262 PendingIntentRecord rec = ref != null ? ref.get() : null;
4263 if (rec != null) {
4264 if (!cancelCurrent) {
4265 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004266 if (rec.key.requestIntent != null) {
4267 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4268 }
4269 if (intents != null) {
4270 intents[intents.length-1] = rec.key.requestIntent;
4271 rec.key.allIntents = intents;
4272 rec.key.allResolvedTypes = resolvedTypes;
4273 } else {
4274 rec.key.allIntents = null;
4275 rec.key.allResolvedTypes = null;
4276 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 return rec;
4279 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004280 rec.canceled = true;
4281 mIntentSenderRecords.remove(key);
4282 }
4283 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 return rec;
4285 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004286 rec = new PendingIntentRecord(this, key, callingUid);
4287 mIntentSenderRecords.put(key, rec.ref);
4288 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
4289 if (activity.pendingResults == null) {
4290 activity.pendingResults
4291 = new HashSet<WeakReference<PendingIntentRecord>>();
4292 }
4293 activity.pendingResults.add(rec.ref);
4294 }
4295 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 }
4297
4298 public void cancelIntentSender(IIntentSender sender) {
4299 if (!(sender instanceof PendingIntentRecord)) {
4300 return;
4301 }
4302 synchronized(this) {
4303 PendingIntentRecord rec = (PendingIntentRecord)sender;
4304 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004305 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306 .getPackageUid(rec.key.packageName);
4307 if (uid != Binder.getCallingUid()) {
4308 String msg = "Permission Denial: cancelIntentSender() from pid="
4309 + Binder.getCallingPid()
4310 + ", uid=" + Binder.getCallingUid()
4311 + " is not allowed to cancel packges "
4312 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004313 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004314 throw new SecurityException(msg);
4315 }
4316 } catch (RemoteException e) {
4317 throw new SecurityException(e);
4318 }
4319 cancelIntentSenderLocked(rec, true);
4320 }
4321 }
4322
4323 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4324 rec.canceled = true;
4325 mIntentSenderRecords.remove(rec.key);
4326 if (cleanActivity && rec.key.activity != null) {
4327 rec.key.activity.pendingResults.remove(rec.ref);
4328 }
4329 }
4330
4331 public String getPackageForIntentSender(IIntentSender pendingResult) {
4332 if (!(pendingResult instanceof PendingIntentRecord)) {
4333 return null;
4334 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004335 try {
4336 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4337 return res.key.packageName;
4338 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 }
4340 return null;
4341 }
4342
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004343 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4344 if (!(pendingResult instanceof PendingIntentRecord)) {
4345 return false;
4346 }
4347 try {
4348 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4349 if (res.key.allIntents == null) {
4350 return false;
4351 }
4352 for (int i=0; i<res.key.allIntents.length; i++) {
4353 Intent intent = res.key.allIntents[i];
4354 if (intent.getPackage() != null && intent.getComponent() != null) {
4355 return false;
4356 }
4357 }
4358 return true;
4359 } catch (ClassCastException e) {
4360 }
4361 return false;
4362 }
4363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 public void setProcessLimit(int max) {
4365 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4366 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004367 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004368 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004369 mProcessLimitOverride = max;
4370 }
4371 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 }
4373
4374 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004375 synchronized (this) {
4376 return mProcessLimitOverride;
4377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 }
4379
4380 void foregroundTokenDied(ForegroundToken token) {
4381 synchronized (ActivityManagerService.this) {
4382 synchronized (mPidsSelfLocked) {
4383 ForegroundToken cur
4384 = mForegroundProcesses.get(token.pid);
4385 if (cur != token) {
4386 return;
4387 }
4388 mForegroundProcesses.remove(token.pid);
4389 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4390 if (pr == null) {
4391 return;
4392 }
4393 pr.forcingToForeground = null;
4394 pr.foregroundServices = false;
4395 }
4396 updateOomAdjLocked();
4397 }
4398 }
4399
4400 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4401 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4402 "setProcessForeground()");
4403 synchronized(this) {
4404 boolean changed = false;
4405
4406 synchronized (mPidsSelfLocked) {
4407 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004408 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004409 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004410 return;
4411 }
4412 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4413 if (oldToken != null) {
4414 oldToken.token.unlinkToDeath(oldToken, 0);
4415 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004416 if (pr != null) {
4417 pr.forcingToForeground = null;
4418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419 changed = true;
4420 }
4421 if (isForeground && token != null) {
4422 ForegroundToken newToken = new ForegroundToken() {
4423 public void binderDied() {
4424 foregroundTokenDied(this);
4425 }
4426 };
4427 newToken.pid = pid;
4428 newToken.token = token;
4429 try {
4430 token.linkToDeath(newToken, 0);
4431 mForegroundProcesses.put(pid, newToken);
4432 pr.forcingToForeground = token;
4433 changed = true;
4434 } catch (RemoteException e) {
4435 // If the process died while doing this, we will later
4436 // do the cleanup with the process death link.
4437 }
4438 }
4439 }
4440
4441 if (changed) {
4442 updateOomAdjLocked();
4443 }
4444 }
4445 }
4446
4447 // =========================================================
4448 // PERMISSIONS
4449 // =========================================================
4450
4451 static class PermissionController extends IPermissionController.Stub {
4452 ActivityManagerService mActivityManagerService;
4453 PermissionController(ActivityManagerService activityManagerService) {
4454 mActivityManagerService = activityManagerService;
4455 }
4456
4457 public boolean checkPermission(String permission, int pid, int uid) {
4458 return mActivityManagerService.checkPermission(permission, pid,
4459 uid) == PackageManager.PERMISSION_GRANTED;
4460 }
4461 }
4462
4463 /**
4464 * This can be called with or without the global lock held.
4465 */
4466 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004467 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 // We might be performing an operation on behalf of an indirect binder
4469 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4470 // client identity accordingly before proceeding.
4471 Identity tlsIdentity = sCallerIdentity.get();
4472 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004473 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4475 uid = tlsIdentity.uid;
4476 pid = tlsIdentity.pid;
4477 }
4478
4479 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004480 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 return PackageManager.PERMISSION_GRANTED;
4482 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004483 // Isolated processes don't get any permissions.
4484 if (UserId.isIsolated(uid)) {
4485 return PackageManager.PERMISSION_DENIED;
4486 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004487 // If there is a uid that owns whatever is being accessed, it has
4488 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004489 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004490 return PackageManager.PERMISSION_GRANTED;
4491 }
4492 // If the target is not exported, then nobody else can get to it.
4493 if (!exported) {
4494 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 return PackageManager.PERMISSION_DENIED;
4496 }
4497 if (permission == null) {
4498 return PackageManager.PERMISSION_GRANTED;
4499 }
4500 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004501 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 .checkUidPermission(permission, uid);
4503 } catch (RemoteException e) {
4504 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004505 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 }
4507 return PackageManager.PERMISSION_DENIED;
4508 }
4509
4510 /**
4511 * As the only public entry point for permissions checking, this method
4512 * can enforce the semantic that requesting a check on a null global
4513 * permission is automatically denied. (Internally a null permission
4514 * string is used when calling {@link #checkComponentPermission} in cases
4515 * when only uid-based security is needed.)
4516 *
4517 * This can be called with or without the global lock held.
4518 */
4519 public int checkPermission(String permission, int pid, int uid) {
4520 if (permission == null) {
4521 return PackageManager.PERMISSION_DENIED;
4522 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004523 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004524 }
4525
4526 /**
4527 * Binder IPC calls go through the public entry point.
4528 * This can be called with or without the global lock held.
4529 */
4530 int checkCallingPermission(String permission) {
4531 return checkPermission(permission,
4532 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004533 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 }
4535
4536 /**
4537 * This can be called with or without the global lock held.
4538 */
4539 void enforceCallingPermission(String permission, String func) {
4540 if (checkCallingPermission(permission)
4541 == PackageManager.PERMISSION_GRANTED) {
4542 return;
4543 }
4544
4545 String msg = "Permission Denial: " + func + " from pid="
4546 + Binder.getCallingPid()
4547 + ", uid=" + Binder.getCallingUid()
4548 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004549 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 throw new SecurityException(msg);
4551 }
4552
4553 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07004554 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
4555 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4556 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
4557 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4558 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004559 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004560 // Is the component private from the target uid?
4561 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
4562
4563 // Acceptable if the there is no read permission needed from the
4564 // target or the target is holding the read permission.
4565 if (!readPerm) {
4566 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004567 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004568 == PackageManager.PERMISSION_GRANTED)) {
4569 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570 }
4571 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004572
4573 // Acceptable if the there is no write permission needed from the
4574 // target or the target is holding the read permission.
4575 if (!writePerm) {
4576 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004578 == PackageManager.PERMISSION_GRANTED)) {
4579 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 }
4581 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004582
4583 // Acceptable if there is a path permission matching the URI that
4584 // the target holds the permission on.
4585 PathPermission[] pps = pi.pathPermissions;
4586 if (pps != null && (!readPerm || !writePerm)) {
4587 final String path = uri.getPath();
4588 int i = pps.length;
4589 while (i > 0 && (!readPerm || !writePerm)) {
4590 i--;
4591 PathPermission pp = pps[i];
4592 if (!readPerm) {
4593 final String pprperm = pp.getReadPermission();
4594 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4595 + pprperm + " for " + pp.getPath()
4596 + ": match=" + pp.match(path)
4597 + " check=" + pm.checkUidPermission(pprperm, uid));
4598 if (pprperm != null && pp.match(path) &&
4599 (pm.checkUidPermission(pprperm, uid)
4600 == PackageManager.PERMISSION_GRANTED)) {
4601 readPerm = true;
4602 }
4603 }
4604 if (!writePerm) {
4605 final String ppwperm = pp.getWritePermission();
4606 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4607 + ppwperm + " for " + pp.getPath()
4608 + ": match=" + pp.match(path)
4609 + " check=" + pm.checkUidPermission(ppwperm, uid));
4610 if (ppwperm != null && pp.match(path) &&
4611 (pm.checkUidPermission(ppwperm, uid)
4612 == PackageManager.PERMISSION_GRANTED)) {
4613 writePerm = true;
4614 }
4615 }
4616 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004618 } catch (RemoteException e) {
4619 return false;
4620 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004621
4622 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 }
4624
4625 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4626 int modeFlags) {
4627 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004628 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004629 return true;
4630 }
4631 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4632 if (perms == null) return false;
4633 UriPermission perm = perms.get(uri);
4634 if (perm == null) return false;
4635 return (modeFlags&perm.modeFlags) == modeFlags;
4636 }
4637
4638 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004639 enforceNotIsolatedCaller("checkUriPermission");
4640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 // Another redirected-binder-call permissions check as in
4642 // {@link checkComponentPermission}.
4643 Identity tlsIdentity = sCallerIdentity.get();
4644 if (tlsIdentity != null) {
4645 uid = tlsIdentity.uid;
4646 pid = tlsIdentity.pid;
4647 }
4648
Amith Yamasani742a6712011-05-04 14:49:28 -07004649 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004650 // Our own process gets to do everything.
4651 if (pid == MY_PID) {
4652 return PackageManager.PERMISSION_GRANTED;
4653 }
4654 synchronized(this) {
4655 return checkUriPermissionLocked(uri, uid, modeFlags)
4656 ? PackageManager.PERMISSION_GRANTED
4657 : PackageManager.PERMISSION_DENIED;
4658 }
4659 }
4660
Dianne Hackborn39792d22010-08-19 18:01:52 -07004661 /**
4662 * Check if the targetPkg can be granted permission to access uri by
4663 * the callingUid using the given modeFlags. Throws a security exception
4664 * if callingUid is not allowed to do this. Returns the uid of the target
4665 * if the URI permission grant should be performed; returns -1 if it is not
4666 * needed (for example targetPkg already has permission to access the URI).
4667 */
4668 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
4669 Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004670 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4671 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4672 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004673 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004674 }
4675
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004676 if (targetPkg != null) {
4677 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4678 "Checking grant " + targetPkg + " permission to " + uri);
4679 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004680
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004681 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682
4683 // If this is not a content: uri, we can't do anything with it.
4684 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004685 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004686 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004687 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004688 }
4689
4690 String name = uri.getAuthority();
4691 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004692 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4693 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 if (cpr != null) {
4695 pi = cpr.info;
4696 } else {
4697 try {
4698 pi = pm.resolveContentProvider(name,
4699 PackageManager.GET_URI_PERMISSION_PATTERNS);
4700 } catch (RemoteException ex) {
4701 }
4702 }
4703 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004704 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004705 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004706 }
4707
4708 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004709 if (targetPkg != null) {
4710 try {
4711 targetUid = pm.getPackageUid(targetPkg);
4712 if (targetUid < 0) {
4713 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4714 "Can't grant URI permission no uid for: " + targetPkg);
4715 return -1;
4716 }
4717 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004718 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004719 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004720 } else {
4721 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004722 }
4723
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004724 if (targetUid >= 0) {
4725 // First... does the target actually need this permission?
4726 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4727 // No need to grant the target this permission.
4728 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4729 "Target " + targetPkg + " already has full permission to " + uri);
4730 return -1;
4731 }
4732 } else {
4733 // First... there is no target package, so can anyone access it?
4734 boolean allowed = pi.exported;
4735 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4736 if (pi.readPermission != null) {
4737 allowed = false;
4738 }
4739 }
4740 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4741 if (pi.writePermission != null) {
4742 allowed = false;
4743 }
4744 }
4745 if (allowed) {
4746 return -1;
4747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 }
4749
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004750 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004751 if (!pi.grantUriPermissions) {
4752 throw new SecurityException("Provider " + pi.packageName
4753 + "/" + pi.name
4754 + " does not allow granting of Uri permissions (uri "
4755 + uri + ")");
4756 }
4757 if (pi.uriPermissionPatterns != null) {
4758 final int N = pi.uriPermissionPatterns.length;
4759 boolean allowed = false;
4760 for (int i=0; i<N; i++) {
4761 if (pi.uriPermissionPatterns[i] != null
4762 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4763 allowed = true;
4764 break;
4765 }
4766 }
4767 if (!allowed) {
4768 throw new SecurityException("Provider " + pi.packageName
4769 + "/" + pi.name
4770 + " does not allow granting of permission to path of Uri "
4771 + uri);
4772 }
4773 }
4774
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004775 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004777 if (callingUid != Process.myUid()) {
4778 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4779 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4780 throw new SecurityException("Uid " + callingUid
4781 + " does not have permission to uri " + uri);
4782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004783 }
4784 }
4785
Dianne Hackborn39792d22010-08-19 18:01:52 -07004786 return targetUid;
4787 }
4788
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004789 public int checkGrantUriPermission(int callingUid, String targetPkg,
4790 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004791 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004792 synchronized(this) {
4793 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4794 }
4795 }
4796
Dianne Hackborn39792d22010-08-19 18:01:52 -07004797 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4798 Uri uri, int modeFlags, UriPermissionOwner owner) {
4799 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4800 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4801 if (modeFlags == 0) {
4802 return;
4803 }
4804
4805 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004806 // to the uri, and the target doesn't. Let's now give this to
4807 // the target.
4808
Joe Onorato8a9b2202010-02-26 18:56:32 -08004809 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004810 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 HashMap<Uri, UriPermission> targetUris
4813 = mGrantedUriPermissions.get(targetUid);
4814 if (targetUris == null) {
4815 targetUris = new HashMap<Uri, UriPermission>();
4816 mGrantedUriPermissions.put(targetUid, targetUris);
4817 }
4818
4819 UriPermission perm = targetUris.get(uri);
4820 if (perm == null) {
4821 perm = new UriPermission(targetUid, uri);
4822 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004823 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004825 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004826 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004827 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004828 } else {
4829 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4830 perm.readOwners.add(owner);
4831 owner.addReadPermission(perm);
4832 }
4833 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4834 perm.writeOwners.add(owner);
4835 owner.addWritePermission(perm);
4836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 }
4838 }
4839
Dianne Hackborn39792d22010-08-19 18:01:52 -07004840 void grantUriPermissionLocked(int callingUid,
4841 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004842 if (targetPkg == null) {
4843 throw new NullPointerException("targetPkg");
4844 }
4845
Dianne Hackborn39792d22010-08-19 18:01:52 -07004846 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4847 if (targetUid < 0) {
4848 return;
4849 }
4850
4851 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4852 }
4853
4854 /**
4855 * Like checkGrantUriPermissionLocked, but takes an Intent.
4856 */
4857 int checkGrantUriPermissionFromIntentLocked(int callingUid,
4858 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004859 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004860 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004861 + " from " + intent + "; flags=0x"
4862 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4863
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004864 if (targetPkg == null) {
4865 throw new NullPointerException("targetPkg");
4866 }
4867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004868 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004869 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870 }
4871 Uri data = intent.getData();
4872 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004873 return -1;
4874 }
4875 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4876 intent.getFlags());
4877 }
4878
4879 /**
4880 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4881 */
4882 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
4883 String targetPkg, Intent intent, UriPermissionOwner owner) {
4884 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
4885 intent.getFlags(), owner);
4886 }
4887
4888 void grantUriPermissionFromIntentLocked(int callingUid,
4889 String targetPkg, Intent intent, UriPermissionOwner owner) {
4890 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
4891 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004892 return;
4893 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004894
4895 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 }
4897
4898 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4899 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004900 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004901 synchronized(this) {
4902 final ProcessRecord r = getRecordForAppLocked(caller);
4903 if (r == null) {
4904 throw new SecurityException("Unable to find app for caller "
4905 + caller
4906 + " when granting permission to uri " + uri);
4907 }
4908 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004909 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004910 }
4911 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004912 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004913 }
4914
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004915 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004916 null);
4917 }
4918 }
4919
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004920 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004921 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4922 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4923 HashMap<Uri, UriPermission> perms
4924 = mGrantedUriPermissions.get(perm.uid);
4925 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004926 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004927 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004928 perms.remove(perm.uri);
4929 if (perms.size() == 0) {
4930 mGrantedUriPermissions.remove(perm.uid);
4931 }
4932 }
4933 }
4934 }
4935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004936 private void revokeUriPermissionLocked(int callingUid, Uri uri,
4937 int modeFlags) {
4938 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4939 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4940 if (modeFlags == 0) {
4941 return;
4942 }
4943
Joe Onorato8a9b2202010-02-26 18:56:32 -08004944 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004945 "Revoking all granted permissions to " + uri);
4946
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004947 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004948
4949 final String authority = uri.getAuthority();
4950 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004951 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
4952 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004953 if (cpr != null) {
4954 pi = cpr.info;
4955 } else {
4956 try {
4957 pi = pm.resolveContentProvider(authority,
4958 PackageManager.GET_URI_PERMISSION_PATTERNS);
4959 } catch (RemoteException ex) {
4960 }
4961 }
4962 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004963 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 return;
4965 }
4966
4967 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07004968 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969 // Right now, if you are not the original owner of the permission,
4970 // you are not allowed to revoke it.
4971 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4972 throw new SecurityException("Uid " + callingUid
4973 + " does not have permission to uri " + uri);
4974 //}
4975 }
4976
4977 // Go through all of the permissions and remove any that match.
4978 final List<String> SEGMENTS = uri.getPathSegments();
4979 if (SEGMENTS != null) {
4980 final int NS = SEGMENTS.size();
4981 int N = mGrantedUriPermissions.size();
4982 for (int i=0; i<N; i++) {
4983 HashMap<Uri, UriPermission> perms
4984 = mGrantedUriPermissions.valueAt(i);
4985 Iterator<UriPermission> it = perms.values().iterator();
4986 toploop:
4987 while (it.hasNext()) {
4988 UriPermission perm = it.next();
4989 Uri targetUri = perm.uri;
4990 if (!authority.equals(targetUri.getAuthority())) {
4991 continue;
4992 }
4993 List<String> targetSegments = targetUri.getPathSegments();
4994 if (targetSegments == null) {
4995 continue;
4996 }
4997 if (targetSegments.size() < NS) {
4998 continue;
4999 }
5000 for (int j=0; j<NS; j++) {
5001 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5002 continue toploop;
5003 }
5004 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005005 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005006 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005007 perm.clearModes(modeFlags);
5008 if (perm.modeFlags == 0) {
5009 it.remove();
5010 }
5011 }
5012 if (perms.size() == 0) {
5013 mGrantedUriPermissions.remove(
5014 mGrantedUriPermissions.keyAt(i));
5015 N--;
5016 i--;
5017 }
5018 }
5019 }
5020 }
5021
5022 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5023 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005024 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005025 synchronized(this) {
5026 final ProcessRecord r = getRecordForAppLocked(caller);
5027 if (r == null) {
5028 throw new SecurityException("Unable to find app for caller "
5029 + caller
5030 + " when revoking permission to uri " + uri);
5031 }
5032 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005033 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005034 return;
5035 }
5036
5037 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5038 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5039 if (modeFlags == 0) {
5040 return;
5041 }
5042
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005043 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005044
5045 final String authority = uri.getAuthority();
5046 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005047 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005048 if (cpr != null) {
5049 pi = cpr.info;
5050 } else {
5051 try {
5052 pi = pm.resolveContentProvider(authority,
5053 PackageManager.GET_URI_PERMISSION_PATTERNS);
5054 } catch (RemoteException ex) {
5055 }
5056 }
5057 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005058 Slog.w(TAG, "No content provider found for permission revoke: "
5059 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005060 return;
5061 }
5062
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005063 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 }
5065 }
5066
Dianne Hackborn7e269642010-08-25 19:50:20 -07005067 @Override
5068 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005069 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005070 synchronized(this) {
5071 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5072 return owner.getExternalTokenLocked();
5073 }
5074 }
5075
5076 @Override
5077 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5078 Uri uri, int modeFlags) {
5079 synchronized(this) {
5080 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5081 if (owner == null) {
5082 throw new IllegalArgumentException("Unknown owner: " + token);
5083 }
5084 if (fromUid != Binder.getCallingUid()) {
5085 if (Binder.getCallingUid() != Process.myUid()) {
5086 // Only system code can grant URI permissions on behalf
5087 // of other users.
5088 throw new SecurityException("nice try");
5089 }
5090 }
5091 if (targetPkg == null) {
5092 throw new IllegalArgumentException("null target");
5093 }
5094 if (uri == null) {
5095 throw new IllegalArgumentException("null uri");
5096 }
5097
5098 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5099 }
5100 }
5101
5102 @Override
5103 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5104 synchronized(this) {
5105 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5106 if (owner == null) {
5107 throw new IllegalArgumentException("Unknown owner: " + token);
5108 }
5109
5110 if (uri == null) {
5111 owner.removeUriPermissionsLocked(mode);
5112 } else {
5113 owner.removeUriPermissionLocked(uri, mode);
5114 }
5115 }
5116 }
5117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5119 synchronized (this) {
5120 ProcessRecord app =
5121 who != null ? getRecordForAppLocked(who) : null;
5122 if (app == null) return;
5123
5124 Message msg = Message.obtain();
5125 msg.what = WAIT_FOR_DEBUGGER_MSG;
5126 msg.obj = app;
5127 msg.arg1 = waiting ? 1 : 0;
5128 mHandler.sendMessage(msg);
5129 }
5130 }
5131
5132 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005133 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5134 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005135 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005136 outInfo.threshold = homeAppMem;
5137 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5138 outInfo.hiddenAppThreshold = hiddenAppMem;
5139 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005140 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005141 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5142 ProcessList.VISIBLE_APP_ADJ);
5143 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5144 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145 }
5146
5147 // =========================================================
5148 // TASK MANAGEMENT
5149 // =========================================================
5150
5151 public List getTasks(int maxNum, int flags,
5152 IThumbnailReceiver receiver) {
5153 ArrayList list = new ArrayList();
5154
5155 PendingThumbnailsRecord pending = null;
5156 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005157 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005158
5159 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005160 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005161 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5162 + ", receiver=" + receiver);
5163
5164 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5165 != PackageManager.PERMISSION_GRANTED) {
5166 if (receiver != null) {
5167 // If the caller wants to wait for pending thumbnails,
5168 // it ain't gonna get them.
5169 try {
5170 receiver.finished();
5171 } catch (RemoteException ex) {
5172 }
5173 }
5174 String msg = "Permission Denial: getTasks() from pid="
5175 + Binder.getCallingPid()
5176 + ", uid=" + Binder.getCallingUid()
5177 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005178 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 throw new SecurityException(msg);
5180 }
5181
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005182 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005183 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005184 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005185 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 TaskRecord curTask = null;
5187 int numActivities = 0;
5188 int numRunning = 0;
5189 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005190 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005192 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005193
5194 // Initialize state for next task if needed.
5195 if (top == null ||
5196 (top.state == ActivityState.INITIALIZING
5197 && top.task == r.task)) {
5198 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005199 curTask = r.task;
5200 numActivities = numRunning = 0;
5201 }
5202
5203 // Add 'r' into the current task.
5204 numActivities++;
5205 if (r.app != null && r.app.thread != null) {
5206 numRunning++;
5207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005208
Joe Onorato8a9b2202010-02-26 18:56:32 -08005209 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005210 TAG, r.intent.getComponent().flattenToShortString()
5211 + ": task=" + r.task);
5212
5213 // If the next one is a different task, generate a new
5214 // TaskInfo entry for what we have.
5215 if (next == null || next.task != curTask) {
5216 ActivityManager.RunningTaskInfo ci
5217 = new ActivityManager.RunningTaskInfo();
5218 ci.id = curTask.taskId;
5219 ci.baseActivity = r.intent.getComponent();
5220 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005221 if (top.thumbHolder != null) {
5222 ci.description = top.thumbHolder.lastDescription;
5223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 ci.numActivities = numActivities;
5225 ci.numRunning = numRunning;
5226 //System.out.println(
5227 // "#" + maxNum + ": " + " descr=" + ci.description);
5228 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005229 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230 TAG, "State=" + top.state + "Idle=" + top.idle
5231 + " app=" + top.app
5232 + " thr=" + (top.app != null ? top.app.thread : null));
5233 if (top.state == ActivityState.RESUMED
5234 || top.state == ActivityState.PAUSING) {
5235 if (top.idle && top.app != null
5236 && top.app.thread != null) {
5237 topRecord = top;
5238 topThumbnail = top.app.thread;
5239 } else {
5240 top.thumbnailNeeded = true;
5241 }
5242 }
5243 if (pending == null) {
5244 pending = new PendingThumbnailsRecord(receiver);
5245 }
5246 pending.pendingRecords.add(top);
5247 }
5248 list.add(ci);
5249 maxNum--;
5250 top = null;
5251 }
5252 }
5253
5254 if (pending != null) {
5255 mPendingThumbnails.add(pending);
5256 }
5257 }
5258
Joe Onorato8a9b2202010-02-26 18:56:32 -08005259 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260
5261 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005262 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005264 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005265 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005266 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005267 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005268 }
5269 }
5270
5271 if (pending == null && receiver != null) {
5272 // In this case all thumbnails were available and the client
5273 // is being asked to be told when the remaining ones come in...
5274 // which is unusually, since the top-most currently running
5275 // activity should never have a canned thumbnail! Oh well.
5276 try {
5277 receiver.finished();
5278 } catch (RemoteException ex) {
5279 }
5280 }
5281
5282 return list;
5283 }
5284
5285 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5286 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005287 final int callingUid = Binder.getCallingUid();
5288 // If it's the system uid asking, then use the current user id.
5289 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5290 // require the entire list.
5291 final int callingUserId = callingUid == Process.SYSTEM_UID
5292 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005293 synchronized (this) {
5294 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5295 "getRecentTasks()");
5296
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005297 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005299 final int N = mRecentTasks.size();
5300 ArrayList<ActivityManager.RecentTaskInfo> res
5301 = new ArrayList<ActivityManager.RecentTaskInfo>(
5302 maxNum < N ? maxNum : N);
5303 for (int i=0; i<N && maxNum > 0; i++) {
5304 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005305 // Only add calling user's recent tasks
5306 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005307 // Return the entry if desired by the caller. We always return
5308 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005309 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005310 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5311 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005312
Dianne Hackborn905577f2011-09-07 18:31:28 -07005313 if (i == 0
5314 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005315 || (tr.intent == null)
5316 || ((tr.intent.getFlags()
5317 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5318 ActivityManager.RecentTaskInfo rti
5319 = new ActivityManager.RecentTaskInfo();
5320 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005321 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005322 rti.baseIntent = new Intent(
5323 tr.intent != null ? tr.intent : tr.affinityIntent);
5324 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005325 rti.description = tr.lastDescription;
5326
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005327 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5328 // Check whether this activity is currently available.
5329 try {
5330 if (rti.origActivity != null) {
5331 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5332 continue;
5333 }
5334 } else if (rti.baseIntent != null) {
5335 if (pm.queryIntentActivities(rti.baseIntent,
5336 null, 0) == null) {
5337 continue;
5338 }
5339 }
5340 } catch (RemoteException e) {
5341 // Will never happen.
5342 }
5343 }
5344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345 res.add(rti);
5346 maxNum--;
5347 }
5348 }
5349 return res;
5350 }
5351 }
5352
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005353 private TaskRecord taskForIdLocked(int id) {
5354 final int N = mRecentTasks.size();
5355 for (int i=0; i<N; i++) {
5356 TaskRecord tr = mRecentTasks.get(i);
5357 if (tr.taskId == id) {
5358 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005359 }
5360 }
5361 return null;
5362 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005363
5364 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5365 synchronized (this) {
5366 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5367 "getTaskThumbnails()");
5368 TaskRecord tr = taskForIdLocked(id);
5369 if (tr != null) {
5370 return mMainStack.getTaskThumbnailsLocked(tr);
5371 }
5372 }
5373 return null;
5374 }
5375
5376 public boolean removeSubTask(int taskId, int subTaskIndex) {
5377 synchronized (this) {
5378 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5379 "removeSubTask()");
5380 long ident = Binder.clearCallingIdentity();
5381 try {
5382 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
5383 } finally {
5384 Binder.restoreCallingIdentity(ident);
5385 }
5386 }
5387 }
5388
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005389 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005390 TaskRecord tr = root.task;
5391 Intent baseIntent = new Intent(
5392 tr.intent != null ? tr.intent : tr.affinityIntent);
5393 ComponentName component = baseIntent.getComponent();
5394 if (component == null) {
5395 Slog.w(TAG, "Now component for base intent of task: " + tr);
5396 return;
5397 }
5398
5399 // Find any running services associated with this app.
5400 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07005401 for (ServiceRecord sr : mServiceMap.getAllServices(root.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005402 if (sr.packageName.equals(component.getPackageName())) {
5403 services.add(sr);
5404 }
5405 }
5406
5407 // Take care of any running services associated with the app.
5408 for (int i=0; i<services.size(); i++) {
5409 ServiceRecord sr = services.get(i);
5410 if (sr.startRequested) {
5411 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005412 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005413 stopServiceLocked(sr);
5414 } else {
5415 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
5416 sr.makeNextStartId(), baseIntent, -1));
5417 if (sr.app != null && sr.app.thread != null) {
5418 sendServiceArgsLocked(sr, false);
5419 }
5420 }
5421 }
5422 }
5423
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005424 if (killProcesses) {
5425 // Find any running processes associated with this app.
5426 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5427 SparseArray<ProcessRecord> appProcs
5428 = mProcessNames.getMap().get(component.getPackageName());
5429 if (appProcs != null) {
5430 for (int i=0; i<appProcs.size(); i++) {
5431 procs.add(appProcs.valueAt(i));
5432 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005433 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005434
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005435 // Kill the running processes.
5436 for (int i=0; i<procs.size(); i++) {
5437 ProcessRecord pr = procs.get(i);
5438 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5439 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5440 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5441 pr.processName, pr.setAdj, "remove task");
5442 Process.killProcessQuiet(pr.pid);
5443 } else {
5444 pr.waitingToKill = "remove task";
5445 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005446 }
5447 }
5448 }
5449
5450 public boolean removeTask(int taskId, int flags) {
5451 synchronized (this) {
5452 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5453 "removeTask()");
5454 long ident = Binder.clearCallingIdentity();
5455 try {
5456 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
5457 if (r != null) {
5458 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005459 cleanUpRemovedTaskLocked(r,
5460 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005461 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005462 } else {
5463 TaskRecord tr = null;
5464 int i=0;
5465 while (i < mRecentTasks.size()) {
5466 TaskRecord t = mRecentTasks.get(i);
5467 if (t.taskId == taskId) {
5468 tr = t;
5469 break;
5470 }
5471 i++;
5472 }
5473 if (tr != null) {
5474 if (tr.numActivities <= 0) {
5475 // Caller is just removing a recent task that is
5476 // not actively running. That is easy!
5477 mRecentTasks.remove(i);
5478 } else {
5479 Slog.w(TAG, "removeTask: task " + taskId
5480 + " does not have activities to remove, "
5481 + " but numActivities=" + tr.numActivities
5482 + ": " + tr);
5483 }
5484 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005485 }
5486 } finally {
5487 Binder.restoreCallingIdentity(ident);
5488 }
5489 }
5490 return false;
5491 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5494 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005495 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 TaskRecord jt = startTask;
5497
5498 // First look backwards
5499 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005500 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 if (r.task != jt) {
5502 jt = r.task;
5503 if (affinity.equals(jt.affinity)) {
5504 return j;
5505 }
5506 }
5507 }
5508
5509 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005510 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005511 jt = startTask;
5512 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005513 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 if (r.task != jt) {
5515 if (affinity.equals(jt.affinity)) {
5516 return j;
5517 }
5518 jt = r.task;
5519 }
5520 }
5521
5522 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005523 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 return N-1;
5525 }
5526
5527 return -1;
5528 }
5529
5530 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005531 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005533 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5535 "moveTaskToFront()");
5536
5537 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005538 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5539 Binder.getCallingUid(), "Task to front")) {
5540 return;
5541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 final long origId = Binder.clearCallingIdentity();
5543 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005544 TaskRecord tr = taskForIdLocked(task);
5545 if (tr != null) {
5546 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5547 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005549 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5550 // Caller wants the home activity moved with it. To accomplish this,
5551 // we'll just move the home task to the top first.
5552 mMainStack.moveHomeToFrontLocked();
5553 }
5554 mMainStack.moveTaskToFrontLocked(tr, null);
5555 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005557 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5558 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005560 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5561 mMainStack.mUserLeaving = true;
5562 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005563 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5564 // Caller wants the home activity moved with it. To accomplish this,
5565 // we'll just move the home task to the top first.
5566 mMainStack.moveHomeToFrontLocked();
5567 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005568 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 return;
5570 }
5571 }
5572 } finally {
5573 Binder.restoreCallingIdentity(origId);
5574 }
5575 }
5576 }
5577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005578 public void moveTaskToBack(int task) {
5579 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5580 "moveTaskToBack()");
5581
5582 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005583 if (mMainStack.mResumedActivity != null
5584 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005585 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5586 Binder.getCallingUid(), "Task to back")) {
5587 return;
5588 }
5589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005591 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005592 Binder.restoreCallingIdentity(origId);
5593 }
5594 }
5595
5596 /**
5597 * Moves an activity, and all of the other activities within the same task, to the bottom
5598 * of the history stack. The activity's order within the task is unchanged.
5599 *
5600 * @param token A reference to the activity we wish to move
5601 * @param nonRoot If false then this only works if the activity is the root
5602 * of a task; if true it will work for any activity in a task.
5603 * @return Returns true if the move completed, false if not.
5604 */
5605 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005606 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 synchronized(this) {
5608 final long origId = Binder.clearCallingIdentity();
5609 int taskId = getTaskForActivityLocked(token, !nonRoot);
5610 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005611 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 }
5613 Binder.restoreCallingIdentity(origId);
5614 }
5615 return false;
5616 }
5617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 public void moveTaskBackwards(int task) {
5619 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5620 "moveTaskBackwards()");
5621
5622 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005623 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5624 Binder.getCallingUid(), "Task backwards")) {
5625 return;
5626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 final long origId = Binder.clearCallingIdentity();
5628 moveTaskBackwardsLocked(task);
5629 Binder.restoreCallingIdentity(origId);
5630 }
5631 }
5632
5633 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005634 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 }
5636
5637 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5638 synchronized(this) {
5639 return getTaskForActivityLocked(token, onlyRoot);
5640 }
5641 }
5642
5643 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005644 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005645 TaskRecord lastTask = null;
5646 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005647 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005648 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 if (!onlyRoot || lastTask != r.task) {
5650 return r.task.taskId;
5651 }
5652 return -1;
5653 }
5654 lastTask = r.task;
5655 }
5656
5657 return -1;
5658 }
5659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 // =========================================================
5661 // THUMBNAILS
5662 // =========================================================
5663
5664 public void reportThumbnail(IBinder token,
5665 Bitmap thumbnail, CharSequence description) {
5666 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5667 final long origId = Binder.clearCallingIdentity();
5668 sendPendingThumbnail(null, token, thumbnail, description, true);
5669 Binder.restoreCallingIdentity(origId);
5670 }
5671
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005672 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 Bitmap thumbnail, CharSequence description, boolean always) {
5674 TaskRecord task = null;
5675 ArrayList receivers = null;
5676
5677 //System.out.println("Send pending thumbnail: " + r);
5678
5679 synchronized(this) {
5680 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005681 r = mMainStack.isInStackLocked(token);
5682 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005683 return;
5684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005686 if (thumbnail == null && r.thumbHolder != null) {
5687 thumbnail = r.thumbHolder.lastThumbnail;
5688 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689 }
5690 if (thumbnail == null && !always) {
5691 // If there is no thumbnail, and this entry is not actually
5692 // going away, then abort for now and pick up the next
5693 // thumbnail we get.
5694 return;
5695 }
5696 task = r.task;
5697
5698 int N = mPendingThumbnails.size();
5699 int i=0;
5700 while (i<N) {
5701 PendingThumbnailsRecord pr =
5702 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5703 //System.out.println("Looking in " + pr.pendingRecords);
5704 if (pr.pendingRecords.remove(r)) {
5705 if (receivers == null) {
5706 receivers = new ArrayList();
5707 }
5708 receivers.add(pr);
5709 if (pr.pendingRecords.size() == 0) {
5710 pr.finished = true;
5711 mPendingThumbnails.remove(i);
5712 N--;
5713 continue;
5714 }
5715 }
5716 i++;
5717 }
5718 }
5719
5720 if (receivers != null) {
5721 final int N = receivers.size();
5722 for (int i=0; i<N; i++) {
5723 try {
5724 PendingThumbnailsRecord pr =
5725 (PendingThumbnailsRecord)receivers.get(i);
5726 pr.receiver.newThumbnail(
5727 task != null ? task.taskId : -1, thumbnail, description);
5728 if (pr.finished) {
5729 pr.receiver.finished();
5730 }
5731 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005732 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 }
5734 }
5735 }
5736 }
5737
5738 // =========================================================
5739 // CONTENT PROVIDERS
5740 // =========================================================
5741
Jeff Brown10e89712011-07-08 18:52:57 -07005742 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5743 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005745 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005746 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005747 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 } catch (RemoteException ex) {
5749 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005750 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005751 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5752 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005753 if (providers != null) {
5754 final int N = providers.size();
5755 for (int i=0; i<N; i++) {
5756 ProviderInfo cpi =
5757 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005758
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005759 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005760 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005762 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005763 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005764 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005765 if (DEBUG_MU)
5766 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005767 app.pubProviders.put(cpi.name, cpr);
5768 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005769 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 }
5771 }
5772 return providers;
5773 }
5774
5775 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005776 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005778 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005780 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005781 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 return null;
5783 }
5784 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005785 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 == PackageManager.PERMISSION_GRANTED) {
5787 return null;
5788 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005789
5790 PathPermission[] pps = cpi.pathPermissions;
5791 if (pps != null) {
5792 int i = pps.length;
5793 while (i > 0) {
5794 i--;
5795 PathPermission pp = pps[i];
5796 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005797 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005798 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005799 return null;
5800 }
5801 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005802 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005803 == PackageManager.PERMISSION_GRANTED) {
5804 return null;
5805 }
5806 }
5807 }
5808
Dianne Hackbornb424b632010-08-18 15:59:05 -07005809 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5810 if (perms != null) {
5811 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5812 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5813 return null;
5814 }
5815 }
5816 }
5817
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005818 String msg;
5819 if (!cpi.exported) {
5820 msg = "Permission Denial: opening provider " + cpi.name
5821 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5822 + ", uid=" + callingUid + ") that is not exported from uid "
5823 + cpi.applicationInfo.uid;
5824 } else {
5825 msg = "Permission Denial: opening provider " + cpi.name
5826 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5827 + ", uid=" + callingUid + ") requires "
5828 + cpi.readPermission + " or " + cpi.writePermission;
5829 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005830 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 return msg;
5832 }
5833
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005834 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5835 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005836 if (r != null) {
5837 Integer cnt = r.conProviders.get(cpr);
5838 if (DEBUG_PROVIDER) Slog.v(TAG,
5839 "Adding provider requested by "
5840 + r.processName + " from process "
5841 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5842 + " cnt=" + (cnt == null ? 1 : cnt));
5843 if (cnt == null) {
5844 cpr.clients.add(r);
5845 r.conProviders.put(cpr, new Integer(1));
5846 return true;
5847 } else {
5848 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5849 }
5850 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005851 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005852 }
5853 return false;
5854 }
5855
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005856 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5857 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005858 if (r != null) {
5859 Integer cnt = r.conProviders.get(cpr);
5860 if (DEBUG_PROVIDER) Slog.v(TAG,
5861 "Removing provider requested by "
5862 + r.processName + " from process "
5863 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5864 + " cnt=" + cnt);
5865 if (cnt == null || cnt.intValue() <= 1) {
5866 cpr.clients.remove(r);
5867 r.conProviders.remove(cpr);
5868 return true;
5869 } else {
5870 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
5871 }
5872 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005873 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005874 }
5875 return false;
5876 }
5877
Amith Yamasani742a6712011-05-04 14:49:28 -07005878 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005879 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 ContentProviderRecord cpr;
5881 ProviderInfo cpi = null;
5882
5883 synchronized(this) {
5884 ProcessRecord r = null;
5885 if (caller != null) {
5886 r = getRecordForAppLocked(caller);
5887 if (r == null) {
5888 throw new SecurityException(
5889 "Unable to find app for caller " + caller
5890 + " (pid=" + Binder.getCallingPid()
5891 + ") when getting content provider " + name);
5892 }
5893 }
5894
5895 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005896 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07005897 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005898 boolean providerRunning = cpr != null;
5899 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005901 String msg;
5902 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5903 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005904 }
5905
5906 if (r != null && cpr.canRunHere(r)) {
5907 // This provider has been published or is in the process
5908 // of being published... but it is also allowed to run
5909 // in the caller's process, so don't make a connection
5910 // and just let the caller instantiate its own instance.
5911 if (cpr.provider != null) {
5912 // don't give caller the provider object, it needs
5913 // to make its own.
5914 cpr = new ContentProviderRecord(cpr);
5915 }
5916 return cpr;
5917 }
5918
5919 final long origId = Binder.clearCallingIdentity();
5920
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005921 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005922 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005923 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005924 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005925 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005926 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005927 // make sure to count it as being accessed and thus
5928 // back up on the LRU list. This is good because
5929 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005930 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07005931 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07005932 }
5933
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005934 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005935 if (false) {
5936 if (cpr.name.flattenToShortString().equals(
5937 "com.android.providers.calendar/.CalendarProvider2")) {
5938 Slog.v(TAG, "****************** KILLING "
5939 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005940 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005941 }
5942 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005943 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005944 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
5945 // NOTE: there is still a race here where a signal could be
5946 // pending on the process even though we managed to update its
5947 // adj level. Not sure what to do about this, but at least
5948 // the race is now smaller.
5949 if (!success) {
5950 // Uh oh... it looks like the provider's process
5951 // has been killed on us. We need to wait for a new
5952 // process to be started, and make sure its death
5953 // doesn't kill our process.
5954 Slog.i(TAG,
5955 "Existing provider " + cpr.name.flattenToShortString()
5956 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005957 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005958 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005959 if (!lastRef) {
5960 // This wasn't the last ref our process had on
5961 // the provider... we have now been killed, bail.
5962 return null;
5963 }
5964 providerRunning = false;
5965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 }
5967
5968 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005971 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005973 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07005974 resolveContentProvider(name,
5975 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 } catch (RemoteException ex) {
5977 }
5978 if (cpi == null) {
5979 return null;
5980 }
5981
Amith Yamasani742a6712011-05-04 14:49:28 -07005982 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
5983 Binder.getOrigCallingUser());
5984
Dianne Hackbornb424b632010-08-18 15:59:05 -07005985 String msg;
5986 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5987 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 }
5989
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07005990 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005991 && !cpi.processName.equals("system")) {
5992 // If this content provider does not run in the system
5993 // process, and the system is not yet ready to run other
5994 // processes, then fail fast instead of hanging.
5995 throw new IllegalArgumentException(
5996 "Attempt to launch content provider before system ready");
5997 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005998
5999 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006000 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 final boolean firstClass = cpr == null;
6002 if (firstClass) {
6003 try {
6004 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006005 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 getApplicationInfo(
6007 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006008 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006010 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 + cpi.name);
6012 return null;
6013 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006014 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006015 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006016 } catch (RemoteException ex) {
6017 // pm is in same process, this will never happen.
6018 }
6019 }
6020
6021 if (r != null && cpr.canRunHere(r)) {
6022 // If this is a multiprocess provider, then just return its
6023 // info and allow the caller to instantiate it. Only do
6024 // this if the provider is the same user as the caller's
6025 // process, or can run as root (so can be in any process).
6026 return cpr;
6027 }
6028
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006029 if (DEBUG_PROVIDER) {
6030 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006031 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006032 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 }
6034
6035 // This is single process, and our app is now connecting to it.
6036 // See if we are already in the process of launching this
6037 // provider.
6038 final int N = mLaunchingProviders.size();
6039 int i;
6040 for (i=0; i<N; i++) {
6041 if (mLaunchingProviders.get(i) == cpr) {
6042 break;
6043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 }
6045
6046 // If the provider is not already being launched, then get it
6047 // started.
6048 if (i >= N) {
6049 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006050
6051 try {
6052 // Content provider is now in use, its package can't be stopped.
6053 try {
6054 AppGlobals.getPackageManager().setPackageStoppedState(
6055 cpr.appInfo.packageName, false);
6056 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006057 } catch (IllegalArgumentException e) {
6058 Slog.w(TAG, "Failed trying to unstop package "
6059 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006060 }
6061
6062 ProcessRecord proc = startProcessLocked(cpi.processName,
6063 cpr.appInfo, false, 0, "content provider",
6064 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006065 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006066 if (proc == null) {
6067 Slog.w(TAG, "Unable to launch app "
6068 + cpi.applicationInfo.packageName + "/"
6069 + cpi.applicationInfo.uid + " for provider "
6070 + name + ": process is bad");
6071 return null;
6072 }
6073 cpr.launchingApp = proc;
6074 mLaunchingProviders.add(cpr);
6075 } finally {
6076 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 }
6079
6080 // Make sure the provider is published (the same provider class
6081 // may be published under multiple names).
6082 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006083 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006084 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006085
Amith Yamasani742a6712011-05-04 14:49:28 -07006086 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006087 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 }
6089 }
6090
6091 // Wait for the provider to be published...
6092 synchronized (cpr) {
6093 while (cpr.provider == null) {
6094 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006095 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006096 + cpi.applicationInfo.packageName + "/"
6097 + cpi.applicationInfo.uid + " for provider "
6098 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006099 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 cpi.applicationInfo.packageName,
6101 cpi.applicationInfo.uid, name);
6102 return null;
6103 }
6104 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006105 if (DEBUG_MU) {
6106 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6107 + cpr.launchingApp);
6108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 cpr.wait();
6110 } catch (InterruptedException ex) {
6111 }
6112 }
6113 }
6114 return cpr;
6115 }
6116
6117 public final ContentProviderHolder getContentProvider(
6118 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006119 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 if (caller == null) {
6121 String msg = "null IApplicationThread when getting content provider "
6122 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006123 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 throw new SecurityException(msg);
6125 }
6126
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006127 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 }
6129
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006130 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6131 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6132 "Do not have permission in call getContentProviderExternal()");
6133 return getContentProviderExternalUnchecked(name, token);
6134 }
6135
6136 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6137 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 }
6139
6140 /**
6141 * Drop a content provider from a ProcessRecord's bookkeeping
6142 * @param cpr
6143 */
6144 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006145 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006147 int userId = UserId.getUserId(Binder.getCallingUid());
6148 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006150 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006151 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006152 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 return;
6154 }
6155 final ProcessRecord r = getRecordForAppLocked(caller);
6156 if (r == null) {
6157 throw new SecurityException(
6158 "Unable to find app for caller " + caller +
6159 " when removing content provider " + name);
6160 }
6161 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006162 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006163 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6164 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6165 + r.info.processName + " from process "
6166 + localCpr.appInfo.processName);
6167 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006168 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006169 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006170 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 return;
6172 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006173 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006174 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006177 }
6178 }
6179
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006180 public void removeContentProviderExternal(String name, IBinder token) {
6181 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6182 "Do not have permission in call removeContentProviderExternal()");
6183 removeContentProviderExternalUnchecked(name, token);
6184 }
6185
6186 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006188 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6189 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190 if(cpr == null) {
6191 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006192 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 return;
6194 }
6195
6196 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006197 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006198 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6199 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006200 if (localCpr.hasExternalProcessHandles()) {
6201 if (localCpr.removeExternalProcessHandleLocked(token)) {
6202 updateOomAdjLocked();
6203 } else {
6204 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6205 + " with no external reference for token: "
6206 + token + ".");
6207 }
6208 } else {
6209 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6210 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 }
6213 }
6214
6215 public final void publishContentProviders(IApplicationThread caller,
6216 List<ContentProviderHolder> providers) {
6217 if (providers == null) {
6218 return;
6219 }
6220
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006221 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 synchronized(this) {
6223 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006224 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006225 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 if (r == null) {
6227 throw new SecurityException(
6228 "Unable to find app for caller " + caller
6229 + " (pid=" + Binder.getCallingPid()
6230 + ") when publishing content providers");
6231 }
6232
6233 final long origId = Binder.clearCallingIdentity();
6234
6235 final int N = providers.size();
6236 for (int i=0; i<N; i++) {
6237 ContentProviderHolder src = providers.get(i);
6238 if (src == null || src.info == null || src.provider == null) {
6239 continue;
6240 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006241 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006242 if (DEBUG_MU)
6243 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006245 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006246 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 String names[] = dst.info.authority.split(";");
6248 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006249 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 }
6251
6252 int NL = mLaunchingProviders.size();
6253 int j;
6254 for (j=0; j<NL; j++) {
6255 if (mLaunchingProviders.get(j) == dst) {
6256 mLaunchingProviders.remove(j);
6257 j--;
6258 NL--;
6259 }
6260 }
6261 synchronized (dst) {
6262 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006263 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 dst.notifyAll();
6265 }
6266 updateOomAdjLocked(r);
6267 }
6268 }
6269
6270 Binder.restoreCallingIdentity(origId);
6271 }
6272 }
6273
6274 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006275 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006276 synchronized (mSelf) {
6277 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6278 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006279 if (providers != null) {
6280 for (int i=providers.size()-1; i>=0; i--) {
6281 ProviderInfo pi = (ProviderInfo)providers.get(i);
6282 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6283 Slog.w(TAG, "Not installing system proc provider " + pi.name
6284 + ": not system .apk");
6285 providers.remove(i);
6286 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006287 }
6288 }
6289 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006290 if (providers != null) {
6291 mSystemThread.installSystemProviders(providers);
6292 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006293
6294 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006295
6296 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 }
6298
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006299 /**
6300 * Allows app to retrieve the MIME type of a URI without having permission
6301 * to access its content provider.
6302 *
6303 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6304 *
6305 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6306 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6307 */
6308 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006309 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006310 final String name = uri.getAuthority();
6311 final long ident = Binder.clearCallingIdentity();
6312 ContentProviderHolder holder = null;
6313
6314 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006315 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006316 if (holder != null) {
6317 return holder.provider.getType(uri);
6318 }
6319 } catch (RemoteException e) {
6320 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6321 return null;
6322 } finally {
6323 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006324 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006325 }
6326 Binder.restoreCallingIdentity(ident);
6327 }
6328
6329 return null;
6330 }
6331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 // =========================================================
6333 // GLOBAL MANAGEMENT
6334 // =========================================================
6335
6336 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006337 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 String proc = customProcess != null ? customProcess : info.processName;
6339 BatteryStatsImpl.Uid.Proc ps = null;
6340 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006341 int uid = info.uid;
6342 if (isolated) {
6343 int userId = UserId.getUserId(uid);
6344 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6345 uid = 0;
6346 while (true) {
6347 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6348 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6349 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6350 }
6351 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6352 mNextIsolatedProcessUid++;
6353 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6354 // No process for this uid, use it.
6355 break;
6356 }
6357 stepsLeft--;
6358 if (stepsLeft <= 0) {
6359 return null;
6360 }
6361 }
6362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 synchronized (stats) {
6364 ps = stats.getProcessStatsLocked(info.uid, proc);
6365 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006366 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 }
6368
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006369 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6370 ProcessRecord app;
6371 if (!isolated) {
6372 app = getProcessRecordLocked(info.processName, info.uid);
6373 } else {
6374 app = null;
6375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376
6377 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006378 app = newProcessRecordLocked(null, info, null, isolated);
6379 mProcessNames.put(info.processName, app.uid, app);
6380 if (isolated) {
6381 mIsolatedProcesses.put(app.uid, app);
6382 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006383 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 }
6385
Dianne Hackborne7f97212011-02-24 14:40:20 -08006386 // This package really, really can not be stopped.
6387 try {
6388 AppGlobals.getPackageManager().setPackageStoppedState(
6389 info.packageName, false);
6390 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006391 } catch (IllegalArgumentException e) {
6392 Slog.w(TAG, "Failed trying to unstop package "
6393 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006394 }
6395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6397 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6398 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006399 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 }
6401 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6402 mPersistentStartingProcesses.add(app);
6403 startProcessLocked(app, "added application", app.processName);
6404 }
6405
6406 return app;
6407 }
6408
6409 public void unhandledBack() {
6410 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6411 "unhandledBack()");
6412
6413 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006414 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006415 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 TAG, "Performing unhandledBack(): stack size = " + count);
6417 if (count > 1) {
6418 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006419 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6421 Binder.restoreCallingIdentity(origId);
6422 }
6423 }
6424 }
6425
6426 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006427 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006429 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 ParcelFileDescriptor pfd = null;
6431 if (cph != null) {
6432 // We record the binder invoker's uid in thread-local storage before
6433 // going to the content provider to open the file. Later, in the code
6434 // that handles all permissions checks, we look for this uid and use
6435 // that rather than the Activity Manager's own uid. The effect is that
6436 // we do the check against the caller's permissions even though it looks
6437 // to the content provider like the Activity Manager itself is making
6438 // the request.
6439 sCallerIdentity.set(new Identity(
6440 Binder.getCallingPid(), Binder.getCallingUid()));
6441 try {
6442 pfd = cph.provider.openFile(uri, "r");
6443 } catch (FileNotFoundException e) {
6444 // do nothing; pfd will be returned null
6445 } finally {
6446 // Ensure that whatever happens, we clean up the identity state
6447 sCallerIdentity.remove();
6448 }
6449
6450 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006451 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006453 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 }
6455 return pfd;
6456 }
6457
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006458 // Actually is sleeping or shutting down or whatever else in the future
6459 // is an inactive state.
6460 public boolean isSleeping() {
6461 return mSleeping || mShuttingDown;
6462 }
6463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 public void goingToSleep() {
6465 synchronized(this) {
6466 mSleeping = true;
6467 mWindowManager.setEventDispatching(false);
6468
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006469 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006470
6471 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006472 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006473 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6474 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006475 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006476 }
6477 }
6478
Dianne Hackborn55280a92009-05-07 15:53:46 -07006479 public boolean shutdown(int timeout) {
6480 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6481 != PackageManager.PERMISSION_GRANTED) {
6482 throw new SecurityException("Requires permission "
6483 + android.Manifest.permission.SHUTDOWN);
6484 }
6485
6486 boolean timedout = false;
6487
6488 synchronized(this) {
6489 mShuttingDown = true;
6490 mWindowManager.setEventDispatching(false);
6491
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006492 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006493 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006494 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006495 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006496 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006497 long delay = endTime - System.currentTimeMillis();
6498 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006499 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006500 timedout = true;
6501 break;
6502 }
6503 try {
6504 this.wait();
6505 } catch (InterruptedException e) {
6506 }
6507 }
6508 }
6509 }
6510
6511 mUsageStatsService.shutdown();
6512 mBatteryStatsService.shutdown();
6513
6514 return timedout;
6515 }
6516
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006517 public final void activitySlept(IBinder token) {
6518 if (localLOGV) Slog.v(
6519 TAG, "Activity slept: token=" + token);
6520
6521 ActivityRecord r = null;
6522
6523 final long origId = Binder.clearCallingIdentity();
6524
6525 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006526 r = mMainStack.isInStackLocked(token);
6527 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006528 mMainStack.activitySleptLocked(r);
6529 }
6530 }
6531
6532 Binder.restoreCallingIdentity(origId);
6533 }
6534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 public void wakingUp() {
6536 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 mWindowManager.setEventDispatching(true);
6538 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006539 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006540 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 }
6542 }
6543
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006544 public void stopAppSwitches() {
6545 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6546 != PackageManager.PERMISSION_GRANTED) {
6547 throw new SecurityException("Requires permission "
6548 + android.Manifest.permission.STOP_APP_SWITCHES);
6549 }
6550
6551 synchronized(this) {
6552 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6553 + APP_SWITCH_DELAY_TIME;
6554 mDidAppSwitch = false;
6555 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6556 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6557 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6558 }
6559 }
6560
6561 public void resumeAppSwitches() {
6562 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6563 != PackageManager.PERMISSION_GRANTED) {
6564 throw new SecurityException("Requires permission "
6565 + android.Manifest.permission.STOP_APP_SWITCHES);
6566 }
6567
6568 synchronized(this) {
6569 // Note that we don't execute any pending app switches... we will
6570 // let those wait until either the timeout, or the next start
6571 // activity request.
6572 mAppSwitchesAllowedTime = 0;
6573 }
6574 }
6575
6576 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6577 String name) {
6578 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6579 return true;
6580 }
6581
6582 final int perm = checkComponentPermission(
6583 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006584 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006585 if (perm == PackageManager.PERMISSION_GRANTED) {
6586 return true;
6587 }
6588
Joe Onorato8a9b2202010-02-26 18:56:32 -08006589 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006590 return false;
6591 }
6592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006593 public void setDebugApp(String packageName, boolean waitForDebugger,
6594 boolean persistent) {
6595 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6596 "setDebugApp()");
6597
6598 // Note that this is not really thread safe if there are multiple
6599 // callers into it at the same time, but that's not a situation we
6600 // care about.
6601 if (persistent) {
6602 final ContentResolver resolver = mContext.getContentResolver();
6603 Settings.System.putString(
6604 resolver, Settings.System.DEBUG_APP,
6605 packageName);
6606 Settings.System.putInt(
6607 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6608 waitForDebugger ? 1 : 0);
6609 }
6610
6611 synchronized (this) {
6612 if (!persistent) {
6613 mOrigDebugApp = mDebugApp;
6614 mOrigWaitForDebugger = mWaitForDebugger;
6615 }
6616 mDebugApp = packageName;
6617 mWaitForDebugger = waitForDebugger;
6618 mDebugTransient = !persistent;
6619 if (packageName != null) {
6620 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07006621 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006622 Binder.restoreCallingIdentity(origId);
6623 }
6624 }
6625 }
6626
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006627 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6628 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6629 synchronized (this) {
6630 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6631 if (!isDebuggable) {
6632 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6633 throw new SecurityException("Process not debuggable: " + app.packageName);
6634 }
6635 }
6636 mProfileApp = processName;
6637 mProfileFile = profileFile;
6638 if (mProfileFd != null) {
6639 try {
6640 mProfileFd.close();
6641 } catch (IOException e) {
6642 }
6643 mProfileFd = null;
6644 }
6645 mProfileFd = profileFd;
6646 mProfileType = 0;
6647 mAutoStopProfiler = autoStopProfiler;
6648 }
6649 }
6650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006651 public void setAlwaysFinish(boolean enabled) {
6652 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6653 "setAlwaysFinish()");
6654
6655 Settings.System.putInt(
6656 mContext.getContentResolver(),
6657 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6658
6659 synchronized (this) {
6660 mAlwaysFinishActivities = enabled;
6661 }
6662 }
6663
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006664 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006666 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006668 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 }
6670 }
6671
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006672 public boolean isUserAMonkey() {
6673 // For now the fact that there is a controller implies
6674 // we have a monkey.
6675 synchronized (this) {
6676 return mController != null;
6677 }
6678 }
6679
Jeff Sharkeya4620792011-05-20 15:29:23 -07006680 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006681 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6682 "registerProcessObserver()");
6683 synchronized (this) {
6684 mProcessObservers.register(observer);
6685 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006686 }
6687
6688 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006689 synchronized (this) {
6690 mProcessObservers.unregister(observer);
6691 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006692 }
6693
Daniel Sandler69a48172010-06-23 16:29:36 -04006694 public void setImmersive(IBinder token, boolean immersive) {
6695 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006696 ActivityRecord r = mMainStack.isInStackLocked(token);
6697 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006698 throw new IllegalArgumentException();
6699 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006700 r.immersive = immersive;
6701 }
6702 }
6703
6704 public boolean isImmersive(IBinder token) {
6705 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006706 ActivityRecord r = mMainStack.isInStackLocked(token);
6707 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006708 throw new IllegalArgumentException();
6709 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006710 return r.immersive;
6711 }
6712 }
6713
6714 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006715 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006716 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006717 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006718 return (r != null) ? r.immersive : false;
6719 }
6720 }
6721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 public final void enterSafeMode() {
6723 synchronized(this) {
6724 // It only makes sense to do this before the system is ready
6725 // and started launching other packages.
6726 if (!mSystemReady) {
6727 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006728 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 } catch (RemoteException e) {
6730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 }
6732 }
6733 }
6734
Jeff Brownb09abc12011-01-13 21:08:27 -08006735 public final void showSafeModeOverlay() {
6736 View v = LayoutInflater.from(mContext).inflate(
6737 com.android.internal.R.layout.safe_mode, null);
6738 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6739 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6740 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6741 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6742 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6743 lp.format = v.getBackground().getOpacity();
6744 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6745 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6746 ((WindowManager)mContext.getSystemService(
6747 Context.WINDOW_SERVICE)).addView(v, lp);
6748 }
6749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 public void noteWakeupAlarm(IIntentSender sender) {
6751 if (!(sender instanceof PendingIntentRecord)) {
6752 return;
6753 }
6754 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6755 synchronized (stats) {
6756 if (mBatteryStatsService.isOnBattery()) {
6757 mBatteryStatsService.enforceCallingPermission();
6758 PendingIntentRecord rec = (PendingIntentRecord)sender;
6759 int MY_UID = Binder.getCallingUid();
6760 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6761 BatteryStatsImpl.Uid.Pkg pkg =
6762 stats.getPackageStatsLocked(uid, rec.key.packageName);
6763 pkg.incWakeupsLocked();
6764 }
6765 }
6766 }
6767
Dianne Hackborn64825172011-03-02 21:32:58 -08006768 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006770 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006772 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006773 // XXX Note: don't acquire main activity lock here, because the window
6774 // manager calls in with its locks held.
6775
6776 boolean killed = false;
6777 synchronized (mPidsSelfLocked) {
6778 int[] types = new int[pids.length];
6779 int worstType = 0;
6780 for (int i=0; i<pids.length; i++) {
6781 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6782 if (proc != null) {
6783 int type = proc.setAdj;
6784 types[i] = type;
6785 if (type > worstType) {
6786 worstType = type;
6787 }
6788 }
6789 }
6790
Dianne Hackborn64825172011-03-02 21:32:58 -08006791 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006792 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006793 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6794 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006795 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006797
6798 // If this is not a secure call, don't let it kill processes that
6799 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006800 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6801 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006802 }
6803
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006804 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 for (int i=0; i<pids.length; i++) {
6806 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6807 if (proc == null) {
6808 continue;
6809 }
6810 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006811 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006812 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006813 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6814 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006816 proc.killedBackground = true;
6817 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 }
6819 }
6820 }
6821 return killed;
6822 }
6823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006824 public final void startRunning(String pkg, String cls, String action,
6825 String data) {
6826 synchronized(this) {
6827 if (mStartRunning) {
6828 return;
6829 }
6830 mStartRunning = true;
6831 mTopComponent = pkg != null && cls != null
6832 ? new ComponentName(pkg, cls) : null;
6833 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6834 mTopData = data;
6835 if (!mSystemReady) {
6836 return;
6837 }
6838 }
6839
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006840 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006841 }
6842
6843 private void retrieveSettings() {
6844 final ContentResolver resolver = mContext.getContentResolver();
6845 String debugApp = Settings.System.getString(
6846 resolver, Settings.System.DEBUG_APP);
6847 boolean waitForDebugger = Settings.System.getInt(
6848 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6849 boolean alwaysFinishActivities = Settings.System.getInt(
6850 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6851
6852 Configuration configuration = new Configuration();
6853 Settings.System.getConfiguration(resolver, configuration);
6854
6855 synchronized (this) {
6856 mDebugApp = mOrigDebugApp = debugApp;
6857 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6858 mAlwaysFinishActivities = alwaysFinishActivities;
6859 // This happens before any activities are started, so we can
6860 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08006861 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006862 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 }
6864 }
6865
6866 public boolean testIsSystemReady() {
6867 // no need to synchronize(this) just to read & return the value
6868 return mSystemReady;
6869 }
6870
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006871 private static File getCalledPreBootReceiversFile() {
6872 File dataDir = Environment.getDataDirectory();
6873 File systemDir = new File(dataDir, "system");
6874 File fname = new File(systemDir, "called_pre_boots.dat");
6875 return fname;
6876 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07006877
6878 static final int LAST_DONE_VERSION = 10000;
6879
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006880 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6881 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6882 File file = getCalledPreBootReceiversFile();
6883 FileInputStream fis = null;
6884 try {
6885 fis = new FileInputStream(file);
6886 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006887 int fvers = dis.readInt();
6888 if (fvers == LAST_DONE_VERSION) {
6889 String vers = dis.readUTF();
6890 String codename = dis.readUTF();
6891 String build = dis.readUTF();
6892 if (android.os.Build.VERSION.RELEASE.equals(vers)
6893 && android.os.Build.VERSION.CODENAME.equals(codename)
6894 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
6895 int num = dis.readInt();
6896 while (num > 0) {
6897 num--;
6898 String pkg = dis.readUTF();
6899 String cls = dis.readUTF();
6900 lastDoneReceivers.add(new ComponentName(pkg, cls));
6901 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006902 }
6903 }
6904 } catch (FileNotFoundException e) {
6905 } catch (IOException e) {
6906 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6907 } finally {
6908 if (fis != null) {
6909 try {
6910 fis.close();
6911 } catch (IOException e) {
6912 }
6913 }
6914 }
6915 return lastDoneReceivers;
6916 }
6917
6918 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
6919 File file = getCalledPreBootReceiversFile();
6920 FileOutputStream fos = null;
6921 DataOutputStream dos = null;
6922 try {
6923 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
6924 fos = new FileOutputStream(file);
6925 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006926 dos.writeInt(LAST_DONE_VERSION);
6927 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006928 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07006929 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006930 dos.writeInt(list.size());
6931 for (int i=0; i<list.size(); i++) {
6932 dos.writeUTF(list.get(i).getPackageName());
6933 dos.writeUTF(list.get(i).getClassName());
6934 }
6935 } catch (IOException e) {
6936 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
6937 file.delete();
6938 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006939 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006940 if (dos != null) {
6941 try {
6942 dos.close();
6943 } catch (IOException e) {
6944 // TODO Auto-generated catch block
6945 e.printStackTrace();
6946 }
6947 }
6948 }
6949 }
6950
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006951 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006952 synchronized(this) {
6953 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006954 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006955 return;
6956 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006957
6958 // Check to see if there are any update receivers to run.
6959 if (!mDidUpdate) {
6960 if (mWaitingUpdate) {
6961 return;
6962 }
6963 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6964 List<ResolveInfo> ris = null;
6965 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006966 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006967 intent, null, 0);
6968 } catch (RemoteException e) {
6969 }
6970 if (ris != null) {
6971 for (int i=ris.size()-1; i>=0; i--) {
6972 if ((ris.get(i).activityInfo.applicationInfo.flags
6973 &ApplicationInfo.FLAG_SYSTEM) == 0) {
6974 ris.remove(i);
6975 }
6976 }
6977 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006978
6979 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
6980
6981 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006982 for (int i=0; i<ris.size(); i++) {
6983 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006984 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6985 if (lastDoneReceivers.contains(comp)) {
6986 ris.remove(i);
6987 i--;
6988 }
6989 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07006990
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006991 for (int i=0; i<ris.size(); i++) {
6992 ActivityInfo ai = ris.get(i).activityInfo;
6993 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6994 doneReceivers.add(comp);
6995 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006996 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08006997 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006998 finisher = new IIntentReceiver.Stub() {
6999 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007000 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007001 boolean sticky) {
7002 // The raw IIntentReceiver interface is called
7003 // with the AM lock held, so redispatch to
7004 // execute our code without the lock.
7005 mHandler.post(new Runnable() {
7006 public void run() {
7007 synchronized (ActivityManagerService.this) {
7008 mDidUpdate = true;
7009 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007010 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007011 showBootMessage(mContext.getText(
7012 R.string.android_upgrading_complete),
7013 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007014 systemReady(goingCallback);
7015 }
7016 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007017 }
7018 };
7019 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007020 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007021 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007022 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007023 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007024 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007025 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007026 mWaitingUpdate = true;
7027 }
7028 }
7029 }
7030 if (mWaitingUpdate) {
7031 return;
7032 }
7033 mDidUpdate = true;
7034 }
7035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007036 mSystemReady = true;
7037 if (!mStartRunning) {
7038 return;
7039 }
7040 }
7041
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007042 ArrayList<ProcessRecord> procsToKill = null;
7043 synchronized(mPidsSelfLocked) {
7044 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7045 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7046 if (!isAllowedWhileBooting(proc.info)){
7047 if (procsToKill == null) {
7048 procsToKill = new ArrayList<ProcessRecord>();
7049 }
7050 procsToKill.add(proc);
7051 }
7052 }
7053 }
7054
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007055 synchronized(this) {
7056 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007057 for (int i=procsToKill.size()-1; i>=0; i--) {
7058 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007059 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007060 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007061 }
7062 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007063
7064 // Now that we have cleaned up any update processes, we
7065 // are ready to start launching real processes and know that
7066 // we won't trample on them any more.
7067 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007068 }
7069
Joe Onorato8a9b2202010-02-26 18:56:32 -08007070 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007071 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072 SystemClock.uptimeMillis());
7073
7074 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007075 // Make sure we have no pre-ready processes sitting around.
7076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007077 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7078 ResolveInfo ri = mContext.getPackageManager()
7079 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007080 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 CharSequence errorMsg = null;
7082 if (ri != null) {
7083 ActivityInfo ai = ri.activityInfo;
7084 ApplicationInfo app = ai.applicationInfo;
7085 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7086 mTopAction = Intent.ACTION_FACTORY_TEST;
7087 mTopData = null;
7088 mTopComponent = new ComponentName(app.packageName,
7089 ai.name);
7090 } else {
7091 errorMsg = mContext.getResources().getText(
7092 com.android.internal.R.string.factorytest_not_system);
7093 }
7094 } else {
7095 errorMsg = mContext.getResources().getText(
7096 com.android.internal.R.string.factorytest_no_action);
7097 }
7098 if (errorMsg != null) {
7099 mTopAction = null;
7100 mTopData = null;
7101 mTopComponent = null;
7102 Message msg = Message.obtain();
7103 msg.what = SHOW_FACTORY_ERROR_MSG;
7104 msg.getData().putCharSequence("msg", errorMsg);
7105 mHandler.sendMessage(msg);
7106 }
7107 }
7108 }
7109
7110 retrieveSettings();
7111
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007112 if (goingCallback != null) goingCallback.run();
7113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007114 synchronized (this) {
7115 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7116 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007117 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007118 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 if (apps != null) {
7120 int N = apps.size();
7121 int i;
7122 for (i=0; i<N; i++) {
7123 ApplicationInfo info
7124 = (ApplicationInfo)apps.get(i);
7125 if (info != null &&
7126 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007127 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007128 }
7129 }
7130 }
7131 } catch (RemoteException ex) {
7132 // pm is in same process, this will never happen.
7133 }
7134 }
7135
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007136 // Start up initial activity.
7137 mBooting = true;
7138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007139 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007140 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007141 Message msg = Message.obtain();
7142 msg.what = SHOW_UID_ERROR_MSG;
7143 mHandler.sendMessage(msg);
7144 }
7145 } catch (RemoteException e) {
7146 }
7147
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007148 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007149 }
7150 }
7151
Dan Egnorb7f03672009-12-09 16:22:32 -08007152 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007153 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007154 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007155 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007156 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007157 startAppProblemLocked(app);
7158 app.stopFreezingAllLocked();
7159 return handleAppCrashLocked(app);
7160 }
7161
Dan Egnorb7f03672009-12-09 16:22:32 -08007162 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007163 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007164 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007165 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007166 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7167 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007168 startAppProblemLocked(app);
7169 app.stopFreezingAllLocked();
7170 }
7171
7172 /**
7173 * Generate a process error record, suitable for attachment to a ProcessRecord.
7174 *
7175 * @param app The ProcessRecord in which the error occurred.
7176 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7177 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007178 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007179 * @param shortMsg Short message describing the crash.
7180 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007181 * @param stackTrace Full crash stack trace, may be null.
7182 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007183 * @return Returns a fully-formed AppErrorStateInfo record.
7184 */
7185 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007186 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007189 report.condition = condition;
7190 report.processName = app.processName;
7191 report.pid = app.pid;
7192 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007193 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007194 report.shortMsg = shortMsg;
7195 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007196 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197
7198 return report;
7199 }
7200
Dan Egnor42471dd2010-01-07 17:25:22 -08007201 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007202 synchronized (this) {
7203 app.crashing = false;
7204 app.crashingReport = null;
7205 app.notResponding = false;
7206 app.notRespondingReport = null;
7207 if (app.anrDialog == fromDialog) {
7208 app.anrDialog = null;
7209 }
7210 if (app.waitDialog == fromDialog) {
7211 app.waitDialog = null;
7212 }
7213 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007214 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007215 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007216 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7217 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007218 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007220 }
7221 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007222
Dan Egnorb7f03672009-12-09 16:22:32 -08007223 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 long now = SystemClock.uptimeMillis();
7225
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007226 Long crashTime;
7227 if (!app.isolated) {
7228 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7229 } else {
7230 crashTime = null;
7231 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007232 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007233 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007234 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007235 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007236 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007237 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007238 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7239 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007240 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007241 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007242 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007243 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007244 }
7245 }
7246 if (!app.persistent) {
7247 // We don't want to start this process again until the user
7248 // explicitly does so... but for persistent process, we really
7249 // need to keep it running. If a persistent process is actually
7250 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007251 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007252 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007253 if (!app.isolated) {
7254 // XXX We don't have a way to mark isolated processes
7255 // as bad, since they don't have a peristent identity.
7256 mBadProcesses.put(app.info.processName, app.uid, now);
7257 mProcessCrashTimes.remove(app.info.processName, app.uid);
7258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007259 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007260 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007261 // Don't let services in this process be restarted and potentially
7262 // annoy the user repeatedly. Unless it is persistent, since those
7263 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007264 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007265 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007266 return false;
7267 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007268 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007269 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007270 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007271 if (r.app == app) {
7272 // If the top running activity is from this crashing
7273 // process, then terminate it to avoid getting in a loop.
7274 Slog.w(TAG, " Force finishing activity "
7275 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007276 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007277 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007278 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007279 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007280 // stopped, to avoid a situation where one will get
7281 // re-start our crashing activity once it gets resumed again.
7282 index--;
7283 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007284 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007285 if (r.state == ActivityState.RESUMED
7286 || r.state == ActivityState.PAUSING
7287 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007288 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007289 Slog.w(TAG, " Force finishing activity "
7290 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007291 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007292 Activity.RESULT_CANCELED, null, "crashed");
7293 }
7294 }
7295 }
7296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007297 }
7298
7299 // Bump up the crash count of any services currently running in the proc.
7300 if (app.services.size() != 0) {
7301 // Any services running in the application need to be placed
7302 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007303 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007304 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007305 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007306 sr.crashCount++;
7307 }
7308 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007309
7310 // If the crashing process is what we consider to be the "home process" and it has been
7311 // replaced by a third-party app, clear the package preferred activities from packages
7312 // with a home activity running in the process to prevent a repeatedly crashing app
7313 // from blocking the user to manually clear the list.
7314 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7315 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7316 Iterator it = mHomeProcess.activities.iterator();
7317 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007318 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007319 if (r.isHomeActivity) {
7320 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7321 try {
7322 ActivityThread.getPackageManager()
7323 .clearPackagePreferredActivities(r.packageName);
7324 } catch (RemoteException c) {
7325 // pm is in same process, this will never happen.
7326 }
7327 }
7328 }
7329 }
7330
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007331 if (!app.isolated) {
7332 // XXX Can't keep track of crash times for isolated processes,
7333 // because they don't have a perisistent identity.
7334 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7335 }
7336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 return true;
7338 }
7339
7340 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007341 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7342 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007343 skipCurrentReceiverLocked(app);
7344 }
7345
7346 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007347 for (BroadcastQueue queue : mBroadcastQueues) {
7348 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007349 }
7350 }
7351
Dan Egnor60d87622009-12-16 16:32:58 -08007352 /**
7353 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7354 * The application process will exit immediately after this call returns.
7355 * @param app object of the crashing app, null for the system server
7356 * @param crashInfo describing the exception
7357 */
7358 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007359 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007360 final String processName = app == null ? "system_server"
7361 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007362
7363 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007364 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007365 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007366 crashInfo.exceptionClassName,
7367 crashInfo.exceptionMessage,
7368 crashInfo.throwFileName,
7369 crashInfo.throwLineNumber);
7370
Jeff Sharkeya353d262011-10-28 11:12:06 -07007371 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007372
7373 crashApplication(r, crashInfo);
7374 }
7375
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007376 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007377 IBinder app,
7378 int violationMask,
7379 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007380 ProcessRecord r = findAppProcess(app, "StrictMode");
7381 if (r == null) {
7382 return;
7383 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007384
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007385 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007386 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007387 boolean logIt = true;
7388 synchronized (mAlreadyLoggedViolatedStacks) {
7389 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7390 logIt = false;
7391 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007392 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007393 // the relative pain numbers, without logging all
7394 // the stack traces repeatedly. We'd want to do
7395 // likewise in the client code, which also does
7396 // dup suppression, before the Binder call.
7397 } else {
7398 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7399 mAlreadyLoggedViolatedStacks.clear();
7400 }
7401 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7402 }
7403 }
7404 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007405 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007406 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007407 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007408
7409 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7410 AppErrorResult result = new AppErrorResult();
7411 synchronized (this) {
7412 final long origId = Binder.clearCallingIdentity();
7413
7414 Message msg = Message.obtain();
7415 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7416 HashMap<String, Object> data = new HashMap<String, Object>();
7417 data.put("result", result);
7418 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007419 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007420 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007421 msg.obj = data;
7422 mHandler.sendMessage(msg);
7423
7424 Binder.restoreCallingIdentity(origId);
7425 }
7426 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007427 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007428 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007429 }
7430
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007431 // Depending on the policy in effect, there could be a bunch of
7432 // these in quick succession so we try to batch these together to
7433 // minimize disk writes, number of dropbox entries, and maximize
7434 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007435 private void logStrictModeViolationToDropBox(
7436 ProcessRecord process,
7437 StrictMode.ViolationInfo info) {
7438 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007439 return;
7440 }
7441 final boolean isSystemApp = process == null ||
7442 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7443 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007444 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007445 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7446 final DropBoxManager dbox = (DropBoxManager)
7447 mContext.getSystemService(Context.DROPBOX_SERVICE);
7448
7449 // Exit early if the dropbox isn't configured to accept this report type.
7450 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7451
7452 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007453 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007454 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7455 synchronized (sb) {
7456 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007457 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007458 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7459 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007460 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7461 if (info.violationNumThisLoop != 0) {
7462 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7463 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007464 if (info.numAnimationsRunning != 0) {
7465 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7466 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007467 if (info.broadcastIntentAction != null) {
7468 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7469 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007470 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007471 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007472 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007473 if (info.numInstances != -1) {
7474 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7475 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007476 if (info.tags != null) {
7477 for (String tag : info.tags) {
7478 sb.append("Span-Tag: ").append(tag).append("\n");
7479 }
7480 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007481 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007482 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7483 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007484 }
7485 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007486
7487 // Only buffer up to ~64k. Various logging bits truncate
7488 // things at 128k.
7489 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007490 }
7491
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007492 // Flush immediately if the buffer's grown too large, or this
7493 // is a non-system app. Non-system apps are isolated with a
7494 // different tag & policy and not batched.
7495 //
7496 // Batching is useful during internal testing with
7497 // StrictMode settings turned up high. Without batching,
7498 // thousands of separate files could be created on boot.
7499 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007500 new Thread("Error dump: " + dropboxTag) {
7501 @Override
7502 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007503 String report;
7504 synchronized (sb) {
7505 report = sb.toString();
7506 sb.delete(0, sb.length());
7507 sb.trimToSize();
7508 }
7509 if (report.length() != 0) {
7510 dbox.addText(dropboxTag, report);
7511 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007512 }
7513 }.start();
7514 return;
7515 }
7516
7517 // System app batching:
7518 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007519 // An existing dropbox-writing thread is outstanding, so
7520 // we don't need to start it up. The existing thread will
7521 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007522 return;
7523 }
7524
7525 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7526 // (After this point, we shouldn't access AMS internal data structures.)
7527 new Thread("Error dump: " + dropboxTag) {
7528 @Override
7529 public void run() {
7530 // 5 second sleep to let stacks arrive and be batched together
7531 try {
7532 Thread.sleep(5000); // 5 seconds
7533 } catch (InterruptedException e) {}
7534
7535 String errorReport;
7536 synchronized (mStrictModeBuffer) {
7537 errorReport = mStrictModeBuffer.toString();
7538 if (errorReport.length() == 0) {
7539 return;
7540 }
7541 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7542 mStrictModeBuffer.trimToSize();
7543 }
7544 dbox.addText(dropboxTag, errorReport);
7545 }
7546 }.start();
7547 }
7548
Dan Egnor60d87622009-12-16 16:32:58 -08007549 /**
7550 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7551 * @param app object of the crashing app, null for the system server
7552 * @param tag reported by the caller
7553 * @param crashInfo describing the context of the error
7554 * @return true if the process should exit immediately (WTF is fatal)
7555 */
7556 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007557 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007558 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007559 final String processName = app == null ? "system_server"
7560 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007561
7562 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007563 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007564 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007565 tag, crashInfo.exceptionMessage);
7566
Jeff Sharkeya353d262011-10-28 11:12:06 -07007567 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007568
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007569 if (r != null && r.pid != Process.myPid() &&
7570 Settings.Secure.getInt(mContext.getContentResolver(),
7571 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007572 crashApplication(r, crashInfo);
7573 return true;
7574 } else {
7575 return false;
7576 }
7577 }
7578
7579 /**
7580 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7581 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7582 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007583 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007584 if (app == null) {
7585 return null;
7586 }
7587
7588 synchronized (this) {
7589 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7590 final int NA = apps.size();
7591 for (int ia=0; ia<NA; ia++) {
7592 ProcessRecord p = apps.valueAt(ia);
7593 if (p.thread != null && p.thread.asBinder() == app) {
7594 return p;
7595 }
7596 }
7597 }
7598
Dianne Hackborncb44d962011-03-10 17:02:27 -08007599 Slog.w(TAG, "Can't find mystery application for " + reason
7600 + " from pid=" + Binder.getCallingPid()
7601 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007602 return null;
7603 }
7604 }
7605
7606 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007607 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7608 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007609 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007610 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7611 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007612 // Watchdog thread ends up invoking this function (with
7613 // a null ProcessRecord) to add the stack file to dropbox.
7614 // Do not acquire a lock on this (am) in such cases, as it
7615 // could cause a potential deadlock, if and when watchdog
7616 // is invoked due to unavailability of lock on am and it
7617 // would prevent watchdog from killing system_server.
7618 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007619 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007620 return;
7621 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007622 // Note: ProcessRecord 'process' is guarded by the service
7623 // instance. (notably process.pkgList, which could otherwise change
7624 // concurrently during execution of this method)
7625 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007626 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007627 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007628 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007629 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7630 for (String pkg : process.pkgList) {
7631 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007632 try {
Dan Egnora455d192010-03-12 08:52:28 -08007633 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7634 if (pi != null) {
7635 sb.append(" v").append(pi.versionCode);
7636 if (pi.versionName != null) {
7637 sb.append(" (").append(pi.versionName).append(")");
7638 }
7639 }
7640 } catch (RemoteException e) {
7641 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007642 }
Dan Egnora455d192010-03-12 08:52:28 -08007643 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007644 }
Dan Egnora455d192010-03-12 08:52:28 -08007645 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007646 }
7647
7648 private static String processClass(ProcessRecord process) {
7649 if (process == null || process.pid == MY_PID) {
7650 return "system_server";
7651 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7652 return "system_app";
7653 } else {
7654 return "data_app";
7655 }
7656 }
7657
7658 /**
7659 * Write a description of an error (crash, WTF, ANR) to the drop box.
7660 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7661 * @param process which caused the error, null means the system server
7662 * @param activity which triggered the error, null if unknown
7663 * @param parent activity related to the error, null if unknown
7664 * @param subject line related to the error, null if absent
7665 * @param report in long form describing the error, null if absent
7666 * @param logFile to include in the report, null if none
7667 * @param crashInfo giving an application stack trace, null if absent
7668 */
7669 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007670 ProcessRecord process, String processName, ActivityRecord activity,
7671 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007672 final String report, final File logFile,
7673 final ApplicationErrorReport.CrashInfo crashInfo) {
7674 // NOTE -- this must never acquire the ActivityManagerService lock,
7675 // otherwise the watchdog may be prevented from resetting the system.
7676
7677 final String dropboxTag = processClass(process) + "_" + eventType;
7678 final DropBoxManager dbox = (DropBoxManager)
7679 mContext.getSystemService(Context.DROPBOX_SERVICE);
7680
7681 // Exit early if the dropbox isn't configured to accept this report type.
7682 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7683
7684 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007685 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007686 if (activity != null) {
7687 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7688 }
7689 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7690 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7691 }
7692 if (parent != null && parent != activity) {
7693 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7694 }
7695 if (subject != null) {
7696 sb.append("Subject: ").append(subject).append("\n");
7697 }
7698 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007699 if (Debug.isDebuggerConnected()) {
7700 sb.append("Debugger: Connected\n");
7701 }
Dan Egnora455d192010-03-12 08:52:28 -08007702 sb.append("\n");
7703
7704 // Do the rest in a worker thread to avoid blocking the caller on I/O
7705 // (After this point, we shouldn't access AMS internal data structures.)
7706 Thread worker = new Thread("Error dump: " + dropboxTag) {
7707 @Override
7708 public void run() {
7709 if (report != null) {
7710 sb.append(report);
7711 }
7712 if (logFile != null) {
7713 try {
7714 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7715 } catch (IOException e) {
7716 Slog.e(TAG, "Error reading " + logFile, e);
7717 }
7718 }
7719 if (crashInfo != null && crashInfo.stackTrace != null) {
7720 sb.append(crashInfo.stackTrace);
7721 }
7722
7723 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7724 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7725 if (lines > 0) {
7726 sb.append("\n");
7727
7728 // Merge several logcat streams, and take the last N lines
7729 InputStreamReader input = null;
7730 try {
7731 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7732 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7733 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7734
7735 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7736 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7737 input = new InputStreamReader(logcat.getInputStream());
7738
7739 int num;
7740 char[] buf = new char[8192];
7741 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7742 } catch (IOException e) {
7743 Slog.e(TAG, "Error running logcat", e);
7744 } finally {
7745 if (input != null) try { input.close(); } catch (IOException e) {}
7746 }
7747 }
7748
7749 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007750 }
Dan Egnora455d192010-03-12 08:52:28 -08007751 };
7752
7753 if (process == null || process.pid == MY_PID) {
7754 worker.run(); // We may be about to die -- need to run this synchronously
7755 } else {
7756 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007757 }
7758 }
7759
7760 /**
7761 * Bring up the "unexpected error" dialog box for a crashing app.
7762 * Deal with edge cases (intercepts from instrumented applications,
7763 * ActivityController, error intent receivers, that sort of thing).
7764 * @param r the application crashing
7765 * @param crashInfo describing the failure
7766 */
7767 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007768 long timeMillis = System.currentTimeMillis();
7769 String shortMsg = crashInfo.exceptionClassName;
7770 String longMsg = crashInfo.exceptionMessage;
7771 String stackTrace = crashInfo.stackTrace;
7772 if (shortMsg != null && longMsg != null) {
7773 longMsg = shortMsg + ": " + longMsg;
7774 } else if (shortMsg != null) {
7775 longMsg = shortMsg;
7776 }
7777
Dan Egnor60d87622009-12-16 16:32:58 -08007778 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007780 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007781 try {
7782 String name = r != null ? r.processName : null;
7783 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007784 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007785 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007786 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 + " at watcher's request");
7788 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007789 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007790 }
7791 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007792 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 }
7794 }
7795
7796 final long origId = Binder.clearCallingIdentity();
7797
7798 // If this process is running instrumentation, finish it.
7799 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007800 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007802 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7803 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007804 Bundle info = new Bundle();
7805 info.putString("shortMsg", shortMsg);
7806 info.putString("longMsg", longMsg);
7807 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7808 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007809 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007810 }
7811
Dan Egnor60d87622009-12-16 16:32:58 -08007812 // If we can't identify the process or it's already exceeded its crash quota,
7813 // quit right away without showing a crash dialog.
7814 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007816 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 }
7818
7819 Message msg = Message.obtain();
7820 msg.what = SHOW_ERROR_MSG;
7821 HashMap data = new HashMap();
7822 data.put("result", result);
7823 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 msg.obj = data;
7825 mHandler.sendMessage(msg);
7826
7827 Binder.restoreCallingIdentity(origId);
7828 }
7829
7830 int res = result.get();
7831
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007832 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007833 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007834 if (r != null && !r.isolated) {
7835 // XXX Can't keep track of crash time for isolated processes,
7836 // since they don't have a persistent identity.
7837 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007838 SystemClock.uptimeMillis());
7839 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007840 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007841 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007842 }
7843 }
7844
7845 if (appErrorIntent != null) {
7846 try {
7847 mContext.startActivity(appErrorIntent);
7848 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007849 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007853
7854 Intent createAppErrorIntentLocked(ProcessRecord r,
7855 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7856 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007857 if (report == null) {
7858 return null;
7859 }
7860 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7861 result.setComponent(r.errorReportReceiver);
7862 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7863 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7864 return result;
7865 }
7866
Dan Egnorb7f03672009-12-09 16:22:32 -08007867 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7868 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007869 if (r.errorReportReceiver == null) {
7870 return null;
7871 }
7872
7873 if (!r.crashing && !r.notResponding) {
7874 return null;
7875 }
7876
Dan Egnorb7f03672009-12-09 16:22:32 -08007877 ApplicationErrorReport report = new ApplicationErrorReport();
7878 report.packageName = r.info.packageName;
7879 report.installerPackageName = r.errorReportReceiver.getPackageName();
7880 report.processName = r.processName;
7881 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007882 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007883
Dan Egnorb7f03672009-12-09 16:22:32 -08007884 if (r.crashing) {
7885 report.type = ApplicationErrorReport.TYPE_CRASH;
7886 report.crashInfo = crashInfo;
7887 } else if (r.notResponding) {
7888 report.type = ApplicationErrorReport.TYPE_ANR;
7889 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007890
Dan Egnorb7f03672009-12-09 16:22:32 -08007891 report.anrInfo.activity = r.notRespondingReport.tag;
7892 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7893 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007894 }
7895
Dan Egnorb7f03672009-12-09 16:22:32 -08007896 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007897 }
7898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007900 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007901 // assume our apps are happy - lazy create the list
7902 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7903
7904 synchronized (this) {
7905
7906 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007907 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7908 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7910 // This one's in trouble, so we'll generate a report for it
7911 // crashes are higher priority (in case there's a crash *and* an anr)
7912 ActivityManager.ProcessErrorStateInfo report = null;
7913 if (app.crashing) {
7914 report = app.crashingReport;
7915 } else if (app.notResponding) {
7916 report = app.notRespondingReport;
7917 }
7918
7919 if (report != null) {
7920 if (errList == null) {
7921 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
7922 }
7923 errList.add(report);
7924 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007925 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007926 " crashing = " + app.crashing +
7927 " notResponding = " + app.notResponding);
7928 }
7929 }
7930 }
7931 }
7932
7933 return errList;
7934 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07007935
7936 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007937 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07007938 if (currApp != null) {
7939 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
7940 }
7941 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007942 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
7943 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007944 } else if (adj >= ProcessList.HOME_APP_ADJ) {
7945 if (currApp != null) {
7946 currApp.lru = 0;
7947 }
7948 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007949 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07007950 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
7951 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
7952 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
7953 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
7954 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
7955 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
7956 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
7957 } else {
7958 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
7959 }
7960 }
7961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007962 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007963 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007964 // Lazy instantiation of list
7965 List<ActivityManager.RunningAppProcessInfo> runList = null;
7966 synchronized (this) {
7967 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007968 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7969 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
7971 // Generate process state info for running application
7972 ActivityManager.RunningAppProcessInfo currApp =
7973 new ActivityManager.RunningAppProcessInfo(app.processName,
7974 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07007975 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007976 if (mHeavyWeightProcess == app) {
Dianne Hackborn482566e2010-09-03 12:51:28 -07007977 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007978 }
Dianne Hackborn42499172010-10-15 18:45:07 -07007979 if (app.persistent) {
7980 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
7981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 int adj = app.curAdj;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007983 currApp.importance = oomAdjToImportance(adj, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007984 currApp.importanceReasonCode = app.adjTypeCode;
7985 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
8036 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008037 if (checkCallingPermission(android.Manifest.permission.DUMP)
8038 != PackageManager.PERMISSION_GRANTED) {
8039 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8040 + Binder.getCallingPid()
8041 + ", uid=" + Binder.getCallingUid()
8042 + " without permission "
8043 + android.Manifest.permission.DUMP);
8044 return;
8045 }
8046
8047 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008048 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008049 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008050
8051 int opti = 0;
8052 while (opti < args.length) {
8053 String opt = args[opti];
8054 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8055 break;
8056 }
8057 opti++;
8058 if ("-a".equals(opt)) {
8059 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008060 } else if ("-c".equals(opt)) {
8061 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008062 } else if ("-h".equals(opt)) {
8063 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008064 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008065 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008066 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008067 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8068 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8069 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008070 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008071 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008072 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008073 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008074 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008075 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008076 pw.println(" all: dump all activities");
8077 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008078 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008079 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8080 pw.println(" a partial substring in a component name, a");
8081 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008082 pw.println(" -a: include all available server state.");
8083 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008085 } else {
8086 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008088 }
8089
8090 // Is the caller requesting to dump a particular piece of data?
8091 if (opti < args.length) {
8092 String cmd = args[opti];
8093 opti++;
8094 if ("activities".equals(cmd) || "a".equals(cmd)) {
8095 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008096 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008097 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008098 return;
8099 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008100 String[] newArgs;
8101 String name;
8102 if (opti >= args.length) {
8103 name = null;
8104 newArgs = EMPTY_STRING_ARRAY;
8105 } else {
8106 name = args[opti];
8107 opti++;
8108 newArgs = new String[args.length - opti];
8109 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8110 args.length - opti);
8111 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008112 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008113 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008114 }
8115 return;
8116 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008117 String[] newArgs;
8118 String name;
8119 if (opti >= args.length) {
8120 name = null;
8121 newArgs = EMPTY_STRING_ARRAY;
8122 } else {
8123 name = args[opti];
8124 opti++;
8125 newArgs = new String[args.length - opti];
8126 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8127 args.length - opti);
8128 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008129 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008130 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008131 }
8132 return;
8133 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008134 String[] newArgs;
8135 String name;
8136 if (opti >= args.length) {
8137 name = null;
8138 newArgs = EMPTY_STRING_ARRAY;
8139 } else {
8140 name = args[opti];
8141 opti++;
8142 newArgs = new String[args.length - opti];
8143 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8144 args.length - opti);
8145 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008146 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008147 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008148 }
8149 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008150 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8151 synchronized (this) {
8152 dumpOomLocked(fd, pw, args, opti, true);
8153 }
8154 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008155 } else if ("provider".equals(cmd)) {
8156 String[] newArgs;
8157 String name;
8158 if (opti >= args.length) {
8159 name = null;
8160 newArgs = EMPTY_STRING_ARRAY;
8161 } else {
8162 name = args[opti];
8163 opti++;
8164 newArgs = new String[args.length - opti];
8165 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8166 }
8167 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8168 pw.println("No providers match: " + name);
8169 pw.println("Use -h for help.");
8170 }
8171 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008172 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8173 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008174 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008175 }
8176 return;
8177 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008178 String[] newArgs;
8179 String name;
8180 if (opti >= args.length) {
8181 name = null;
8182 newArgs = EMPTY_STRING_ARRAY;
8183 } else {
8184 name = args[opti];
8185 opti++;
8186 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008187 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8188 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008189 }
8190 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8191 pw.println("No services match: " + name);
8192 pw.println("Use -h for help.");
8193 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008194 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008195 } else if ("package".equals(cmd)) {
8196 String[] newArgs;
8197 if (opti >= args.length) {
8198 pw.println("package: no package name specified");
8199 pw.println("Use -h for help.");
8200 return;
8201 } else {
8202 dumpPackage = args[opti];
8203 opti++;
8204 newArgs = new String[args.length - opti];
8205 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8206 args.length - opti);
8207 args = newArgs;
8208 opti = 0;
8209 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008210 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8211 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008212 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008213 }
8214 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008215 } else {
8216 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008217 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8218 pw.println("Bad activity command, or no activities match: " + cmd);
8219 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008220 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008221 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008223 }
8224
8225 // No piece of data specified, dump everything.
8226 synchronized (this) {
8227 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008228 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008229 if (needSep) {
8230 pw.println(" ");
8231 }
8232 if (dumpAll) {
8233 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008234 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008235 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008236 if (needSep) {
8237 pw.println(" ");
8238 }
8239 if (dumpAll) {
8240 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008241 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008242 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008243 if (needSep) {
8244 pw.println(" ");
8245 }
8246 if (dumpAll) {
8247 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008248 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008249 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008250 if (needSep) {
8251 pw.println(" ");
8252 }
8253 if (dumpAll) {
8254 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008255 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008256 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008257 if (needSep) {
8258 pw.println(" ");
8259 }
8260 if (dumpAll) {
8261 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008262 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008263 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008264 }
8265 }
8266
8267 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008268 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008269 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8270 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008271 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8272 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008273 pw.println(" ");
8274 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008275 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8276 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008277 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008278 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008279 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008280 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008281 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008282 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008283 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008285 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008286 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008287 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008288 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008289 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8290 pw.println(" ");
8291 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008292 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008293 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008294 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008295 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008296 pw.println(" ");
8297 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008298 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008299 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008301
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008302 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008303 if (mMainStack.mPausingActivity != null) {
8304 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008305 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008306 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008307 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008308 if (dumpAll) {
8309 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8310 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008311 pw.println(" mDismissKeyguardOnNextActivity: "
8312 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008314
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008315 if (mRecentTasks.size() > 0) {
8316 pw.println();
8317 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008318
8319 final int N = mRecentTasks.size();
8320 for (int i=0; i<N; i++) {
8321 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008322 if (dumpPackage != null) {
8323 if (tr.realActivity == null ||
8324 !dumpPackage.equals(tr.realActivity)) {
8325 continue;
8326 }
8327 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008328 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8329 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008330 if (dumpAll) {
8331 mRecentTasks.get(i).dump(pw, " ");
8332 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008333 }
8334 }
8335
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008336 if (dumpAll) {
8337 pw.println(" ");
8338 pw.println(" mCurTask: " + mCurTask);
8339 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008340
8341 return true;
8342 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008343
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008344 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008345 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008346 boolean needSep = false;
8347 int numPers = 0;
8348
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008349 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8350
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008351 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8353 final int NA = procs.size();
8354 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008355 ProcessRecord r = procs.valueAt(ia);
8356 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8357 continue;
8358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008359 if (!needSep) {
8360 pw.println(" All known processes:");
8361 needSep = true;
8362 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008363 pw.print(r.persistent ? " *PERS*" : " *APP*");
8364 pw.print(" UID "); pw.print(procs.keyAt(ia));
8365 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008366 r.dump(pw, " ");
8367 if (r.persistent) {
8368 numPers++;
8369 }
8370 }
8371 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008372 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008373
8374 if (mIsolatedProcesses.size() > 0) {
8375 if (needSep) pw.println(" ");
8376 needSep = true;
8377 pw.println(" Isolated process list (sorted by uid):");
8378 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8379 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8380 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8381 continue;
8382 }
8383 pw.println(String.format("%sIsolated #%2d: %s",
8384 " ", i, r.toString()));
8385 }
8386 }
8387
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008388 if (mLruProcesses.size() > 0) {
8389 if (needSep) pw.println(" ");
8390 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008391 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008392 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008393 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008394 needSep = true;
8395 }
8396
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008397 if (dumpAll) {
8398 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008399 boolean printed = false;
8400 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8401 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8402 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8403 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008404 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008405 if (!printed) {
8406 if (needSep) pw.println(" ");
8407 needSep = true;
8408 pw.println(" PID mappings:");
8409 printed = true;
8410 }
8411 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8412 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008413 }
8414 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008415 }
8416
8417 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008418 synchronized (mPidsSelfLocked) {
8419 boolean printed = false;
8420 for (int i=0; i<mForegroundProcesses.size(); i++) {
8421 ProcessRecord r = mPidsSelfLocked.get(
8422 mForegroundProcesses.valueAt(i).pid);
8423 if (dumpPackage != null && (r == null
8424 || !dumpPackage.equals(r.info.packageName))) {
8425 continue;
8426 }
8427 if (!printed) {
8428 if (needSep) pw.println(" ");
8429 needSep = true;
8430 pw.println(" Foreground Processes:");
8431 printed = true;
8432 }
8433 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8434 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008436 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008437 }
8438
8439 if (mPersistentStartingProcesses.size() > 0) {
8440 if (needSep) pw.println(" ");
8441 needSep = true;
8442 pw.println(" Persisent processes that are starting:");
8443 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008444 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008446
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008447 if (mRemovedProcesses.size() > 0) {
8448 if (needSep) pw.println(" ");
8449 needSep = true;
8450 pw.println(" Processes that are being removed:");
8451 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008452 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008453 }
8454
8455 if (mProcessesOnHold.size() > 0) {
8456 if (needSep) pw.println(" ");
8457 needSep = true;
8458 pw.println(" Processes that are on old until the system is ready:");
8459 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008460 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008462
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008463 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008464
8465 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008466 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008467 long now = SystemClock.uptimeMillis();
8468 for (Map.Entry<String, SparseArray<Long>> procs
8469 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008470 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008471 SparseArray<Long> uids = procs.getValue();
8472 final int N = uids.size();
8473 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008474 int puid = uids.keyAt(i);
8475 ProcessRecord r = mProcessNames.get(pname, puid);
8476 if (dumpPackage != null && (r == null
8477 || !dumpPackage.equals(r.info.packageName))) {
8478 continue;
8479 }
8480 if (!printed) {
8481 if (needSep) pw.println(" ");
8482 needSep = true;
8483 pw.println(" Time since processes crashed:");
8484 printed = true;
8485 }
8486 pw.print(" Process "); pw.print(pname);
8487 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008488 pw.print(": last crashed ");
8489 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008490 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008491 }
8492 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008495 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008496 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008497 for (Map.Entry<String, SparseArray<Long>> procs
8498 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008499 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008500 SparseArray<Long> uids = procs.getValue();
8501 final int N = uids.size();
8502 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008503 int puid = uids.keyAt(i);
8504 ProcessRecord r = mProcessNames.get(pname, puid);
8505 if (dumpPackage != null && (r == null
8506 || !dumpPackage.equals(r.info.packageName))) {
8507 continue;
8508 }
8509 if (!printed) {
8510 if (needSep) pw.println(" ");
8511 needSep = true;
8512 pw.println(" Bad processes:");
8513 }
8514 pw.print(" Bad process "); pw.print(pname);
8515 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008516 pw.print(": crashed at time ");
8517 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008518 }
8519 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008521
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008522 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008523 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008524 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008525 if (dumpAll) {
8526 StringBuilder sb = new StringBuilder(128);
8527 sb.append(" mPreviousProcessVisibleTime: ");
8528 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8529 pw.println(sb);
8530 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008531 if (mHeavyWeightProcess != null) {
8532 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8533 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008534 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008535 if (dumpAll) {
8536 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008537 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008538 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008539 for (Map.Entry<String, Integer> entry
8540 : mCompatModePackages.getPackages().entrySet()) {
8541 String pkg = entry.getKey();
8542 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008543 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8544 continue;
8545 }
8546 if (!printed) {
8547 pw.println(" mScreenCompatPackages:");
8548 printed = true;
8549 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008550 pw.print(" "); pw.print(pkg); pw.print(": ");
8551 pw.print(mode); pw.println();
8552 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008553 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008554 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008555 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8556 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8557 || mOrigWaitForDebugger) {
8558 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8559 + " mDebugTransient=" + mDebugTransient
8560 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8561 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008562 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8563 || mProfileFd != null) {
8564 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8565 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8566 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8567 + mAutoStopProfiler);
8568 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008569 if (mAlwaysFinishActivities || mController != null) {
8570 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8571 + " mController=" + mController);
8572 }
8573 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008575 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008576 + " mProcessesReady=" + mProcessesReady
8577 + " mSystemReady=" + mSystemReady);
8578 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 + " mBooted=" + mBooted
8580 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008581 pw.print(" mLastPowerCheckRealtime=");
8582 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8583 pw.println("");
8584 pw.print(" mLastPowerCheckUptime=");
8585 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8586 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008587 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8588 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008589 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008590 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8591 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008593
8594 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595 }
8596
Dianne Hackborn287952c2010-09-22 22:34:31 -07008597 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008598 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008599 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008600 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008601 long now = SystemClock.uptimeMillis();
8602 for (int i=0; i<mProcessesToGc.size(); i++) {
8603 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008604 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8605 continue;
8606 }
8607 if (!printed) {
8608 if (needSep) pw.println(" ");
8609 needSep = true;
8610 pw.println(" Processes that are waiting to GC:");
8611 printed = true;
8612 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008613 pw.print(" Process "); pw.println(proc);
8614 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8615 pw.print(", last gced=");
8616 pw.print(now-proc.lastRequestedGc);
8617 pw.print(" ms ago, last lowMem=");
8618 pw.print(now-proc.lastLowMemory);
8619 pw.println(" ms ago");
8620
8621 }
8622 }
8623 return needSep;
8624 }
8625
8626 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8627 int opti, boolean dumpAll) {
8628 boolean needSep = false;
8629
8630 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008631 if (needSep) pw.println(" ");
8632 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008633 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008634 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008635 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008636 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8637 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8638 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8639 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8640 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008641 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008642 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008643 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008644 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008645 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008646 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008647
8648 if (needSep) pw.println(" ");
8649 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008650 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008651 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008652 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008653 needSep = true;
8654 }
8655
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008656 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008657
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008658 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008659 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008660 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008661 if (mHeavyWeightProcess != null) {
8662 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8663 }
8664
8665 return true;
8666 }
8667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 /**
8669 * There are three ways to call this:
8670 * - no service specified: dump all the services
8671 * - a flattened component name that matched an existing service was specified as the
8672 * first arg: dump that one service
8673 * - the first arg isn't the flattened component name of an existing service:
8674 * dump all services whose component contains the first arg as a substring
8675 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008676 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8677 int opti, boolean dumpAll) {
8678 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008679
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008680 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008681 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008682 try {
8683 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8684 for (UserInfo user : users) {
8685 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8686 services.add(r1);
8687 }
8688 }
8689 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008690 }
8691 }
8692 } else {
8693 ComponentName componentName = name != null
8694 ? ComponentName.unflattenFromString(name) : null;
8695 int objectId = 0;
8696 if (componentName == null) {
8697 // Not a '/' separated full component name; maybe an object ID?
8698 try {
8699 objectId = Integer.parseInt(name, 16);
8700 name = null;
8701 componentName = null;
8702 } catch (RuntimeException e) {
8703 }
8704 }
8705
8706 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008707 try {
8708 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8709 for (UserInfo user : users) {
8710 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8711 if (componentName != null) {
8712 if (r1.name.equals(componentName)) {
8713 services.add(r1);
8714 }
8715 } else if (name != null) {
8716 if (r1.name.flattenToString().contains(name)) {
8717 services.add(r1);
8718 }
8719 } else if (System.identityHashCode(r1) == objectId) {
8720 services.add(r1);
8721 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008722 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008723 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008724 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008725 }
8726 }
8727 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008728
8729 if (services.size() <= 0) {
8730 return false;
8731 }
8732
8733 boolean needSep = false;
8734 for (int i=0; i<services.size(); i++) {
8735 if (needSep) {
8736 pw.println();
8737 }
8738 needSep = true;
8739 dumpService("", fd, pw, services.get(i), args, dumpAll);
8740 }
8741 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008742 }
8743
8744 /**
8745 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8746 * there is a thread associated with the service.
8747 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008748 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8749 final ServiceRecord r, String[] args, boolean dumpAll) {
8750 String innerPrefix = prefix + " ";
8751 synchronized (this) {
8752 pw.print(prefix); pw.print("SERVICE ");
8753 pw.print(r.shortName); pw.print(" ");
8754 pw.print(Integer.toHexString(System.identityHashCode(r)));
8755 pw.print(" pid=");
8756 if (r.app != null) pw.println(r.app.pid);
8757 else pw.println("(not running)");
8758 if (dumpAll) {
8759 r.dump(pw, innerPrefix);
8760 }
8761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008762 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008763 pw.print(prefix); pw.println(" Client:");
8764 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008765 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008766 TransferPipe tp = new TransferPipe();
8767 try {
8768 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8769 tp.setBufferPrefix(prefix + " ");
8770 tp.go(fd);
8771 } finally {
8772 tp.kill();
8773 }
8774 } catch (IOException e) {
8775 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008777 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778 }
8779 }
8780 }
8781
Marco Nelissen18cb2872011-11-15 11:19:53 -08008782 /**
8783 * There are three ways to call this:
8784 * - no provider specified: dump all the providers
8785 * - a flattened component name that matched an existing provider was specified as the
8786 * first arg: dump that one provider
8787 * - the first arg isn't the flattened component name of an existing provider:
8788 * dump all providers whose component contains the first arg as a substring
8789 */
8790 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8791 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008792 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008793 }
8794
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008795 static class ItemMatcher {
8796 ArrayList<ComponentName> components;
8797 ArrayList<String> strings;
8798 ArrayList<Integer> objects;
8799 boolean all;
8800
8801 ItemMatcher() {
8802 all = true;
8803 }
8804
8805 void build(String name) {
8806 ComponentName componentName = ComponentName.unflattenFromString(name);
8807 if (componentName != null) {
8808 if (components == null) {
8809 components = new ArrayList<ComponentName>();
8810 }
8811 components.add(componentName);
8812 all = false;
8813 } else {
8814 int objectId = 0;
8815 // Not a '/' separated full component name; maybe an object ID?
8816 try {
8817 objectId = Integer.parseInt(name, 16);
8818 if (objects == null) {
8819 objects = new ArrayList<Integer>();
8820 }
8821 objects.add(objectId);
8822 all = false;
8823 } catch (RuntimeException e) {
8824 // Not an integer; just do string match.
8825 if (strings == null) {
8826 strings = new ArrayList<String>();
8827 }
8828 strings.add(name);
8829 all = false;
8830 }
8831 }
8832 }
8833
8834 int build(String[] args, int opti) {
8835 for (; opti<args.length; opti++) {
8836 String name = args[opti];
8837 if ("--".equals(name)) {
8838 return opti+1;
8839 }
8840 build(name);
8841 }
8842 return opti;
8843 }
8844
8845 boolean match(Object object, ComponentName comp) {
8846 if (all) {
8847 return true;
8848 }
8849 if (components != null) {
8850 for (int i=0; i<components.size(); i++) {
8851 if (components.get(i).equals(comp)) {
8852 return true;
8853 }
8854 }
8855 }
8856 if (objects != null) {
8857 for (int i=0; i<objects.size(); i++) {
8858 if (System.identityHashCode(object) == objects.get(i)) {
8859 return true;
8860 }
8861 }
8862 }
8863 if (strings != null) {
8864 String flat = comp.flattenToString();
8865 for (int i=0; i<strings.size(); i++) {
8866 if (flat.contains(strings.get(i))) {
8867 return true;
8868 }
8869 }
8870 }
8871 return false;
8872 }
8873 }
8874
Dianne Hackborn625ac272010-09-17 18:29:22 -07008875 /**
8876 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008877 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07008878 * - the cmd arg isn't the flattened component name of an existing activity:
8879 * dump all activity whose component contains the cmd as a substring
8880 * - A hex number of the ActivityRecord object instance.
8881 */
8882 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8883 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008884 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008885
8886 if ("all".equals(name)) {
8887 synchronized (this) {
8888 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008889 activities.add(r1);
8890 }
8891 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07008892 } else if ("top".equals(name)) {
8893 synchronized (this) {
8894 final int N = mMainStack.mHistory.size();
8895 if (N > 0) {
8896 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
8897 }
8898 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008899 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008900 ItemMatcher matcher = new ItemMatcher();
8901 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008902
8903 synchronized (this) {
8904 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008905 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008906 activities.add(r1);
8907 }
8908 }
8909 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008910 }
8911
8912 if (activities.size() <= 0) {
8913 return false;
8914 }
8915
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008916 String[] newArgs = new String[args.length - opti];
8917 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8918
Dianne Hackborn30d71892010-12-11 10:37:55 -08008919 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008920 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08008921 for (int i=activities.size()-1; i>=0; i--) {
8922 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008923 if (needSep) {
8924 pw.println();
8925 }
8926 needSep = true;
8927 synchronized (this) {
8928 if (lastTask != r.task) {
8929 lastTask = r.task;
8930 pw.print("TASK "); pw.print(lastTask.affinity);
8931 pw.print(" id="); pw.println(lastTask.taskId);
8932 if (dumpAll) {
8933 lastTask.dump(pw, " ");
8934 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008935 }
8936 }
8937 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008938 }
8939 return true;
8940 }
8941
8942 /**
8943 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
8944 * there is a thread associated with the activity.
8945 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08008946 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008947 final ActivityRecord r, String[] args, boolean dumpAll) {
8948 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08008949 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008950 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
8951 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
8952 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08008953 if (r.app != null) pw.println(r.app.pid);
8954 else pw.println("(not running)");
8955 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008956 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008957 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008958 }
8959 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008960 // flush anything that is already in the PrintWriter since the thread is going
8961 // to write to the file descriptor directly
8962 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07008963 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008964 TransferPipe tp = new TransferPipe();
8965 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08008966 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
8967 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008968 tp.go(fd);
8969 } finally {
8970 tp.kill();
8971 }
8972 } catch (IOException e) {
8973 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008974 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008975 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008976 }
8977 }
8978 }
8979
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008980 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008981 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008982 boolean needSep = false;
8983
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008984 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008986 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008987 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008988 Iterator it = mRegisteredReceivers.values().iterator();
8989 while (it.hasNext()) {
8990 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008991 if (dumpPackage != null && (r.app == null ||
8992 !dumpPackage.equals(r.app.info.packageName))) {
8993 continue;
8994 }
8995 if (!printed) {
8996 pw.println(" Registered Receivers:");
8997 needSep = true;
8998 printed = true;
8999 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009000 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001 r.dump(pw, " ");
9002 }
9003 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009004
9005 if (mReceiverResolver.dump(pw, needSep ?
9006 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9007 " ", dumpPackage, false)) {
9008 needSep = true;
9009 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009010 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009011
9012 for (BroadcastQueue q : mBroadcastQueues) {
9013 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009015
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009016 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009017
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009018 if (mStickyBroadcasts != null && dumpPackage == null) {
9019 if (needSep) {
9020 pw.println();
9021 }
9022 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009023 pw.println(" Sticky broadcasts:");
9024 StringBuilder sb = new StringBuilder(128);
9025 for (Map.Entry<String, ArrayList<Intent>> ent
9026 : mStickyBroadcasts.entrySet()) {
9027 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009028 if (dumpAll) {
9029 pw.println(":");
9030 ArrayList<Intent> intents = ent.getValue();
9031 final int N = intents.size();
9032 for (int i=0; i<N; i++) {
9033 sb.setLength(0);
9034 sb.append(" Intent: ");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009035 intents.get(i).toShortString(sb, false, true, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009036 pw.println(sb.toString());
9037 Bundle bundle = intents.get(i).getExtras();
9038 if (bundle != null) {
9039 pw.print(" ");
9040 pw.println(bundle.toString());
9041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009042 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009043 } else {
9044 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009045 }
9046 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009047 needSep = true;
9048 }
9049
9050 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009051 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009052 for (BroadcastQueue queue : mBroadcastQueues) {
9053 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9054 + queue.mBroadcastsScheduled);
9055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009056 pw.println(" mHandler:");
9057 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009058 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009059 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009060
9061 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009062 }
9063
Marco Nelissen18cb2872011-11-15 11:19:53 -08009064 /**
9065 * Prints a list of ServiceRecords (dumpsys activity services)
9066 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009067 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009068 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009069 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009070
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009071 ItemMatcher matcher = new ItemMatcher();
9072 matcher.build(args, opti);
9073
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009074 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009075 try {
9076 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9077 for (UserInfo user : users) {
9078 if (mServiceMap.getAllServices(user.id).size() > 0) {
9079 boolean printed = false;
9080 long nowReal = SystemClock.elapsedRealtime();
9081 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9082 user.id).iterator();
9083 needSep = false;
9084 while (it.hasNext()) {
9085 ServiceRecord r = it.next();
9086 if (!matcher.match(r, r.name)) {
9087 continue;
9088 }
9089 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9090 continue;
9091 }
9092 if (!printed) {
9093 pw.println(" Active services:");
9094 printed = true;
9095 }
9096 if (needSep) {
9097 pw.println();
9098 }
9099 pw.print(" * ");
9100 pw.println(r);
9101 if (dumpAll) {
9102 r.dump(pw, " ");
9103 needSep = true;
9104 } else {
9105 pw.print(" app=");
9106 pw.println(r.app);
9107 pw.print(" created=");
9108 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9109 pw.print(" started=");
9110 pw.print(r.startRequested);
9111 pw.print(" connections=");
9112 pw.println(r.connections.size());
9113 if (r.connections.size() > 0) {
9114 pw.println(" Connections:");
9115 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9116 for (int i = 0; i < clist.size(); i++) {
9117 ConnectionRecord conn = clist.get(i);
9118 pw.print(" ");
9119 pw.print(conn.binding.intent.intent.getIntent()
9120 .toShortString(false, false, false));
9121 pw.print(" -> ");
9122 ProcessRecord proc = conn.binding.client;
9123 pw.println(proc != null ? proc.toShortString() : "null");
9124 }
9125 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009126 }
9127 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009128 if (dumpClient && r.app != null && r.app.thread != null) {
9129 pw.println(" Client:");
9130 pw.flush();
9131 try {
9132 TransferPipe tp = new TransferPipe();
9133 try {
9134 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9135 r, args);
9136 tp.setBufferPrefix(" ");
9137 // Short timeout, since blocking here can
9138 // deadlock with the application.
9139 tp.go(fd, 2000);
9140 } finally {
9141 tp.kill();
9142 }
9143 } catch (IOException e) {
9144 pw.println(" Failure while dumping the service: " + e);
9145 } catch (RemoteException e) {
9146 pw.println(" Got a RemoteException while dumping the service");
9147 }
9148 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009149 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009150 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009151 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009153 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009154 } catch (RemoteException re) {
9155
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009157
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009158 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009159 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009160 for (int i=0; i<mPendingServices.size(); i++) {
9161 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009162 if (!matcher.match(r, r.name)) {
9163 continue;
9164 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009165 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9166 continue;
9167 }
9168 if (!printed) {
9169 if (needSep) pw.println(" ");
9170 needSep = true;
9171 pw.println(" Pending services:");
9172 printed = true;
9173 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009174 pw.print(" * Pending "); pw.println(r);
9175 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009176 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009177 needSep = true;
9178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009179
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009180 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009181 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009182 for (int i=0; i<mRestartingServices.size(); i++) {
9183 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009184 if (!matcher.match(r, r.name)) {
9185 continue;
9186 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009187 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9188 continue;
9189 }
9190 if (!printed) {
9191 if (needSep) pw.println(" ");
9192 needSep = true;
9193 pw.println(" Restarting services:");
9194 printed = true;
9195 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009196 pw.print(" * Restarting "); pw.println(r);
9197 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009198 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009199 needSep = true;
9200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009201
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009202 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009203 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009204 for (int i=0; i<mStoppingServices.size(); i++) {
9205 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009206 if (!matcher.match(r, r.name)) {
9207 continue;
9208 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009209 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9210 continue;
9211 }
9212 if (!printed) {
9213 if (needSep) pw.println(" ");
9214 needSep = true;
9215 pw.println(" Stopping services:");
9216 printed = true;
9217 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009218 pw.print(" * Stopping "); pw.println(r);
9219 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009220 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009221 needSep = true;
9222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009223
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009224 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009225 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009226 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009227 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009228 = mServiceConnections.values().iterator();
9229 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009230 ArrayList<ConnectionRecord> r = it.next();
9231 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009232 ConnectionRecord cr = r.get(i);
9233 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9234 continue;
9235 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009236 if (dumpPackage != null && (cr.binding.client == null
9237 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9238 continue;
9239 }
9240 if (!printed) {
9241 if (needSep) pw.println(" ");
9242 needSep = true;
9243 pw.println(" Connection bindings to services:");
9244 printed = true;
9245 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009246 pw.print(" * "); pw.println(cr);
9247 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009249 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009250 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009251 }
9252 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009253
9254 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009255 }
9256
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009257 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009258 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009259 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009260
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009261 ItemMatcher matcher = new ItemMatcher();
9262 matcher.build(args, opti);
9263
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009264 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009265
9266 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009267
9268 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009269 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009270 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009271 ContentProviderRecord r = mLaunchingProviders.get(i);
9272 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9273 continue;
9274 }
9275 if (!printed) {
9276 if (needSep) pw.println(" ");
9277 needSep = true;
9278 pw.println(" Launching content providers:");
9279 printed = true;
9280 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009281 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009282 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009283 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009284 }
9285
9286 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009287 if (needSep) pw.println();
9288 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009289 pw.println("Granted Uri Permissions:");
9290 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9291 int uid = mGrantedUriPermissions.keyAt(i);
9292 HashMap<Uri, UriPermission> perms
9293 = mGrantedUriPermissions.valueAt(i);
9294 pw.print(" * UID "); pw.print(uid);
9295 pw.println(" holds:");
9296 for (UriPermission perm : perms.values()) {
9297 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009298 if (dumpAll) {
9299 perm.dump(pw, " ");
9300 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009301 }
9302 }
9303 needSep = true;
9304 }
9305
9306 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009307 }
9308
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009309 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009310 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009311 boolean needSep = false;
9312
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009313 if (mIntentSenderRecords.size() > 0) {
9314 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009315 Iterator<WeakReference<PendingIntentRecord>> it
9316 = mIntentSenderRecords.values().iterator();
9317 while (it.hasNext()) {
9318 WeakReference<PendingIntentRecord> ref = it.next();
9319 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009320 if (dumpPackage != null && (rec == null
9321 || !dumpPackage.equals(rec.key.packageName))) {
9322 continue;
9323 }
9324 if (!printed) {
9325 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9326 printed = true;
9327 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009328 needSep = true;
9329 if (rec != null) {
9330 pw.print(" * "); pw.println(rec);
9331 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009332 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009333 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009334 } else {
9335 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009336 }
9337 }
9338 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009339
9340 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009341 }
9342
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009343 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009344 String prefix, String label, boolean complete, boolean brief, boolean client,
9345 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009347 boolean needNL = false;
9348 final String innerPrefix = prefix + " ";
9349 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009350 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009351 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009352 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9353 continue;
9354 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009355 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009356 if (needNL) {
9357 pw.println(" ");
9358 needNL = false;
9359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009360 if (lastTask != r.task) {
9361 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009362 pw.print(prefix);
9363 pw.print(full ? "* " : " ");
9364 pw.println(lastTask);
9365 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009366 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009367 } else if (complete) {
9368 // Complete + brief == give a summary. Isn't that obvious?!?
9369 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009370 pw.print(prefix); pw.print(" ");
9371 pw.println(lastTask.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009372 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009374 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009375 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9376 pw.print(" #"); pw.print(i); pw.print(": ");
9377 pw.println(r);
9378 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009379 r.dump(pw, innerPrefix);
9380 } else if (complete) {
9381 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009382 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009383 if (r.app != null) {
9384 pw.print(innerPrefix); pw.println(r.app);
9385 }
9386 }
9387 if (client && r.app != null && r.app.thread != null) {
9388 // flush anything that is already in the PrintWriter since the thread is going
9389 // to write to the file descriptor directly
9390 pw.flush();
9391 try {
9392 TransferPipe tp = new TransferPipe();
9393 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009394 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9395 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009396 // Short timeout, since blocking here can
9397 // deadlock with the application.
9398 tp.go(fd, 2000);
9399 } finally {
9400 tp.kill();
9401 }
9402 } catch (IOException e) {
9403 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9404 } catch (RemoteException e) {
9405 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9406 }
9407 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009409 }
9410 }
9411
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009412 private static String buildOomTag(String prefix, String space, int val, int base) {
9413 if (val == base) {
9414 if (space == null) return prefix;
9415 return prefix + " ";
9416 }
9417 return prefix + "+" + Integer.toString(val-base);
9418 }
9419
9420 private static final int dumpProcessList(PrintWriter pw,
9421 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009422 String prefix, String normalLabel, String persistentLabel,
9423 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009424 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009425 final int N = list.size()-1;
9426 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009427 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009428 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9429 continue;
9430 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009431 pw.println(String.format("%s%s #%2d: %s",
9432 prefix, (r.persistent ? persistentLabel : normalLabel),
9433 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 if (r.persistent) {
9435 numPers++;
9436 }
9437 }
9438 return numPers;
9439 }
9440
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009441 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009442 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009443 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009444 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009445
Dianne Hackborn905577f2011-09-07 18:31:28 -07009446 ArrayList<Pair<ProcessRecord, Integer>> list
9447 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9448 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009449 ProcessRecord r = origList.get(i);
9450 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9451 continue;
9452 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009453 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9454 }
9455
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009456 if (list.size() <= 0) {
9457 return false;
9458 }
9459
Dianne Hackborn905577f2011-09-07 18:31:28 -07009460 Comparator<Pair<ProcessRecord, Integer>> comparator
9461 = new Comparator<Pair<ProcessRecord, Integer>>() {
9462 @Override
9463 public int compare(Pair<ProcessRecord, Integer> object1,
9464 Pair<ProcessRecord, Integer> object2) {
9465 if (object1.first.setAdj != object2.first.setAdj) {
9466 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9467 }
9468 if (object1.second.intValue() != object2.second.intValue()) {
9469 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9470 }
9471 return 0;
9472 }
9473 };
9474
9475 Collections.sort(list, comparator);
9476
Dianne Hackborn287952c2010-09-22 22:34:31 -07009477 final long curRealtime = SystemClock.elapsedRealtime();
9478 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9479 final long curUptime = SystemClock.uptimeMillis();
9480 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9481
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009482 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009483 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009484 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009485 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009486 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009487 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9488 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009489 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9490 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009491 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9492 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009493 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9494 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009495 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009496 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009497 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9498 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9499 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9500 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9501 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9502 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9503 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9504 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009505 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9506 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009507 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9508 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009509 } else {
9510 oomAdj = Integer.toString(r.setAdj);
9511 }
9512 String schedGroup;
9513 switch (r.setSchedGroup) {
9514 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9515 schedGroup = "B";
9516 break;
9517 case Process.THREAD_GROUP_DEFAULT:
9518 schedGroup = "F";
9519 break;
9520 default:
9521 schedGroup = Integer.toString(r.setSchedGroup);
9522 break;
9523 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009524 String foreground;
9525 if (r.foregroundActivities) {
9526 foreground = "A";
9527 } else if (r.foregroundServices) {
9528 foreground = "S";
9529 } else {
9530 foreground = " ";
9531 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009532 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009533 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009534 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9535 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009536 if (r.adjSource != null || r.adjTarget != null) {
9537 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009538 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009539 if (r.adjTarget instanceof ComponentName) {
9540 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9541 } else if (r.adjTarget != null) {
9542 pw.print(r.adjTarget.toString());
9543 } else {
9544 pw.print("{null}");
9545 }
9546 pw.print("<=");
9547 if (r.adjSource instanceof ProcessRecord) {
9548 pw.print("Proc{");
9549 pw.print(((ProcessRecord)r.adjSource).toShortString());
9550 pw.println("}");
9551 } else if (r.adjSource != null) {
9552 pw.println(r.adjSource.toString());
9553 } else {
9554 pw.println("{null}");
9555 }
9556 }
9557 if (inclDetails) {
9558 pw.print(prefix);
9559 pw.print(" ");
9560 pw.print("oom: max="); pw.print(r.maxAdj);
9561 pw.print(" hidden="); pw.print(r.hiddenAdj);
9562 pw.print(" curRaw="); pw.print(r.curRawAdj);
9563 pw.print(" setRaw="); pw.print(r.setRawAdj);
9564 pw.print(" cur="); pw.print(r.curAdj);
9565 pw.print(" set="); pw.println(r.setAdj);
9566 pw.print(prefix);
9567 pw.print(" ");
9568 pw.print("keeping="); pw.print(r.keeping);
9569 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009570 pw.print(" empty="); pw.print(r.empty);
9571 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009572
9573 if (!r.keeping) {
9574 if (r.lastWakeTime != 0) {
9575 long wtime;
9576 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9577 synchronized (stats) {
9578 wtime = stats.getProcessWakeTime(r.info.uid,
9579 r.pid, curRealtime);
9580 }
9581 long timeUsed = wtime - r.lastWakeTime;
9582 pw.print(prefix);
9583 pw.print(" ");
9584 pw.print("keep awake over ");
9585 TimeUtils.formatDuration(realtimeSince, pw);
9586 pw.print(" used ");
9587 TimeUtils.formatDuration(timeUsed, pw);
9588 pw.print(" (");
9589 pw.print((timeUsed*100)/realtimeSince);
9590 pw.println("%)");
9591 }
9592 if (r.lastCpuTime != 0) {
9593 long timeUsed = r.curCpuTime - r.lastCpuTime;
9594 pw.print(prefix);
9595 pw.print(" ");
9596 pw.print("run cpu over ");
9597 TimeUtils.formatDuration(uptimeSince, pw);
9598 pw.print(" used ");
9599 TimeUtils.formatDuration(timeUsed, pw);
9600 pw.print(" (");
9601 pw.print((timeUsed*100)/uptimeSince);
9602 pw.println("%)");
9603 }
9604 }
9605 }
9606 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009607 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009608 }
9609
Dianne Hackbornb437e092011-08-05 17:50:29 -07009610 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009611 ArrayList<ProcessRecord> procs;
9612 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009613 if (args != null && args.length > start
9614 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009615 procs = new ArrayList<ProcessRecord>();
9616 int pid = -1;
9617 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009618 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009619 } catch (NumberFormatException e) {
9620
9621 }
9622 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9623 ProcessRecord proc = mLruProcesses.get(i);
9624 if (proc.pid == pid) {
9625 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009626 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009627 procs.add(proc);
9628 }
9629 }
9630 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009631 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009632 return null;
9633 }
9634 } else {
9635 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9636 }
9637 }
9638 return procs;
9639 }
9640
9641 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9642 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009643 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009644 if (procs == null) {
9645 return;
9646 }
9647
9648 long uptime = SystemClock.uptimeMillis();
9649 long realtime = SystemClock.elapsedRealtime();
9650 pw.println("Applications Graphics Acceleration Info:");
9651 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9652
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009653 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9654 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009655 if (r.thread != null) {
9656 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9657 pw.flush();
9658 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009659 TransferPipe tp = new TransferPipe();
9660 try {
9661 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9662 tp.go(fd);
9663 } finally {
9664 tp.kill();
9665 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009666 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009667 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009668 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009669 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009670 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009671 pw.flush();
9672 }
9673 }
9674 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009675 }
9676
Jeff Brown6754ba22011-12-14 20:20:01 -08009677 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9678 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9679 if (procs == null) {
9680 return;
9681 }
9682
9683 pw.println("Applications Database Info:");
9684
9685 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9686 ProcessRecord r = procs.get(i);
9687 if (r.thread != null) {
9688 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9689 pw.flush();
9690 try {
9691 TransferPipe tp = new TransferPipe();
9692 try {
9693 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9694 tp.go(fd);
9695 } finally {
9696 tp.kill();
9697 }
9698 } catch (IOException e) {
9699 pw.println("Failure while dumping the app: " + r);
9700 pw.flush();
9701 } catch (RemoteException e) {
9702 pw.println("Got a RemoteException while dumping the app " + r);
9703 pw.flush();
9704 }
9705 }
9706 }
9707 }
9708
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009709 final static class MemItem {
9710 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009711 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009712 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009713 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009714 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009715
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009716 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009717 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009718 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009719 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009720 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009721 }
9722 }
9723
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009724 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009725 boolean sort) {
9726 if (sort) {
9727 Collections.sort(items, new Comparator<MemItem>() {
9728 @Override
9729 public int compare(MemItem lhs, MemItem rhs) {
9730 if (lhs.pss < rhs.pss) {
9731 return 1;
9732 } else if (lhs.pss > rhs.pss) {
9733 return -1;
9734 }
9735 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009736 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009737 });
9738 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009739
9740 for (int i=0; i<items.size(); i++) {
9741 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009742 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009743 if (mi.subitems != null) {
9744 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9745 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009746 }
9747 }
9748
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009749 // These are in KB.
9750 static final long[] DUMP_MEM_BUCKETS = new long[] {
9751 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9752 120*1024, 160*1024, 200*1024,
9753 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9754 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9755 };
9756
Dianne Hackborn672342c2011-11-29 11:29:02 -08009757 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9758 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009759 int start = label.lastIndexOf('.');
9760 if (start >= 0) start++;
9761 else start = 0;
9762 int end = label.length();
9763 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9764 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9765 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9766 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009767 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009768 out.append(label, start, end);
9769 return;
9770 }
9771 }
9772 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009773 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009774 out.append(label, start, end);
9775 }
9776
9777 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9778 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9779 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9780 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9781 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9782 };
9783 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9784 "System", "Persistent", "Foreground",
9785 "Visible", "Perceptible", "Heavy Weight",
9786 "Backup", "A Services", "Home", "Previous",
9787 "B Services", "Background"
9788 };
9789
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009790 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009791 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009792 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009793 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009794 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009795
9796 int opti = 0;
9797 while (opti < args.length) {
9798 String opt = args[opti];
9799 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9800 break;
9801 }
9802 opti++;
9803 if ("-a".equals(opt)) {
9804 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009805 } else if ("--oom".equals(opt)) {
9806 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009807 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009808 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009809 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009810 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009811 pw.println("If [process] is specified it can be the name or ");
9812 pw.println("pid of a specific process to dump.");
9813 return;
9814 } else {
9815 pw.println("Unknown argument: " + opt + "; use -h for help");
9816 }
9817 }
9818
9819 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009820 if (procs == null) {
9821 return;
9822 }
9823
Dianne Hackborn6447ca32009-04-07 19:50:08 -07009824 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009825 long uptime = SystemClock.uptimeMillis();
9826 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -07009827
9828 if (procs.size() == 1 || isCheckinRequest) {
9829 dumpAll = true;
9830 }
9831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 if (isCheckinRequest) {
9833 // short checkin version
9834 pw.println(uptime + "," + realtime);
9835 pw.flush();
9836 } else {
9837 pw.println("Applications Memory Usage (kB):");
9838 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9839 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009840
Dianne Hackbornb437e092011-08-05 17:50:29 -07009841 String[] innerArgs = new String[args.length-opti];
9842 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
9843
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009844 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
9845 long nativePss=0, dalvikPss=0, otherPss=0;
9846 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
9847
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009848 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
9849 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
9850 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -07009851
9852 long totalPss = 0;
9853
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009854 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9855 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009856 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009857 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009858 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
9859 pw.flush();
9860 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009861 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009862 if (dumpAll) {
9863 try {
9864 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
9865 } catch (RemoteException e) {
9866 if (!isCheckinRequest) {
9867 pw.println("Got RemoteException!");
9868 pw.flush();
9869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009870 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009871 } else {
9872 mi = new Debug.MemoryInfo();
9873 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009874 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009875
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009876 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009877 long myTotalPss = mi.getTotalPss();
9878 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009879 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009880 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009881 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009882
9883 nativePss += mi.nativePss;
9884 dalvikPss += mi.dalvikPss;
9885 otherPss += mi.otherPss;
9886 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
9887 long mem = mi.getOtherPss(j);
9888 miscPss[j] += mem;
9889 otherPss -= mem;
9890 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009891
9892 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009893 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
9894 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009895 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009896 if (oomProcs[oomIndex] == null) {
9897 oomProcs[oomIndex] = new ArrayList<MemItem>();
9898 }
9899 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009900 break;
9901 }
9902 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009904 }
9905 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009906
9907 if (!isCheckinRequest && procs.size() > 1) {
9908 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
9909
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009910 catMems.add(new MemItem("Native", "Native", nativePss, -1));
9911 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
9912 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009913 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009914 String label = Debug.MemoryInfo.getOtherLabel(j);
9915 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009916 }
9917
Dianne Hackbornb437e092011-08-05 17:50:29 -07009918 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
9919 for (int j=0; j<oomPss.length; j++) {
9920 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009921 String label = DUMP_MEM_OOM_LABEL[j];
9922 MemItem item = new MemItem(label, label, oomPss[j],
9923 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009924 item.subitems = oomProcs[j];
9925 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009926 }
9927 }
9928
Dianne Hackborn672342c2011-11-29 11:29:02 -08009929 if (outTag != null || outStack != null) {
9930 if (outTag != null) {
9931 appendMemBucket(outTag, totalPss, "total", false);
9932 }
9933 if (outStack != null) {
9934 appendMemBucket(outStack, totalPss, "total", true);
9935 }
9936 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009937 for (int i=0; i<oomMems.size(); i++) {
9938 MemItem miCat = oomMems.get(i);
9939 if (miCat.subitems == null || miCat.subitems.size() < 1) {
9940 continue;
9941 }
9942 if (miCat.id < ProcessList.SERVICE_ADJ
9943 || miCat.id == ProcessList.HOME_APP_ADJ
9944 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009945 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
9946 outTag.append(" / ");
9947 }
9948 if (outStack != null) {
9949 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
9950 if (firstLine) {
9951 outStack.append(":");
9952 firstLine = false;
9953 }
9954 outStack.append("\n\t at ");
9955 } else {
9956 outStack.append("$");
9957 }
9958 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009959 for (int j=0; j<miCat.subitems.size(); j++) {
9960 MemItem mi = miCat.subitems.get(j);
9961 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009962 if (outTag != null) {
9963 outTag.append(" ");
9964 }
9965 if (outStack != null) {
9966 outStack.append("$");
9967 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009968 }
Dianne Hackborn672342c2011-11-29 11:29:02 -08009969 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
9970 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
9971 }
9972 if (outStack != null) {
9973 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
9974 }
9975 }
9976 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
9977 outStack.append("(");
9978 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
9979 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
9980 outStack.append(DUMP_MEM_OOM_LABEL[k]);
9981 outStack.append(":");
9982 outStack.append(DUMP_MEM_OOM_ADJ[k]);
9983 }
9984 }
9985 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009986 }
9987 }
9988 }
9989 }
9990
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009991 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -07009992 pw.println();
9993 pw.println("Total PSS by process:");
9994 dumpMemItems(pw, " ", procMems, true);
9995 pw.println();
9996 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009997 pw.println("Total PSS by OOM adjustment:");
9998 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009999 if (!oomOnly) {
10000 PrintWriter out = categoryPw != null ? categoryPw : pw;
10001 out.println();
10002 out.println("Total PSS by category:");
10003 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010004 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010005 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010006 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010008 }
10009
10010 /**
10011 * Searches array of arguments for the specified string
10012 * @param args array of argument strings
10013 * @param value value to search for
10014 * @return true if the value is contained in the array
10015 */
10016 private static boolean scanArgs(String[] args, String value) {
10017 if (args != null) {
10018 for (String arg : args) {
10019 if (value.equals(arg)) {
10020 return true;
10021 }
10022 }
10023 }
10024 return false;
10025 }
10026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010027 private final void killServicesLocked(ProcessRecord app,
10028 boolean allowRestart) {
10029 // Report disconnected services.
10030 if (false) {
10031 // XXX we are letting the client link to the service for
10032 // death notifications.
10033 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010034 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010035 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010036 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010037 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010038 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010039 = r.connections.values().iterator();
10040 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010041 ArrayList<ConnectionRecord> cl = jt.next();
10042 for (int i=0; i<cl.size(); i++) {
10043 ConnectionRecord c = cl.get(i);
10044 if (c.binding.client != app) {
10045 try {
10046 //c.conn.connected(r.className, null);
10047 } catch (Exception e) {
10048 // todo: this should be asynchronous!
10049 Slog.w(TAG, "Exception thrown disconnected servce "
10050 + r.shortName
10051 + " from app " + app.processName, e);
10052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010053 }
10054 }
10055 }
10056 }
10057 }
10058 }
10059 }
10060
10061 // Clean up any connections this application has to other services.
10062 if (app.connections.size() > 0) {
10063 Iterator<ConnectionRecord> it = app.connections.iterator();
10064 while (it.hasNext()) {
10065 ConnectionRecord r = it.next();
10066 removeConnectionLocked(r, app, null);
10067 }
10068 }
10069 app.connections.clear();
10070
10071 if (app.services.size() != 0) {
10072 // Any services running in the application need to be placed
10073 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010074 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010075 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010076 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010077 synchronized (sr.stats.getBatteryStats()) {
10078 sr.stats.stopLaunchedLocked();
10079 }
10080 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010081 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010082 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010083 if (mStoppingServices.remove(sr)) {
10084 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10085 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010086
10087 boolean hasClients = sr.bindings.size() > 0;
10088 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010089 Iterator<IntentBindRecord> bindings
10090 = sr.bindings.values().iterator();
10091 while (bindings.hasNext()) {
10092 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010093 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010094 + ": shouldUnbind=" + b.hasBound);
10095 b.binder = null;
10096 b.requested = b.received = b.hasBound = false;
10097 }
10098 }
10099
Dianne Hackborn070783f2010-12-29 16:46:28 -080010100 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10101 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010102 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010103 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010104 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010105 sr.crashCount, sr.shortName, app.pid);
10106 bringDownServiceLocked(sr, true);
10107 } else if (!allowRestart) {
10108 bringDownServiceLocked(sr, true);
10109 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010110 boolean canceled = scheduleServiceRestartLocked(sr, true);
10111
10112 // Should the service remain running? Note that in the
10113 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010114 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010115 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10116 if (sr.pendingStarts.size() == 0) {
10117 sr.startRequested = false;
10118 if (!hasClients) {
10119 // Whoops, no reason to restart!
10120 bringDownServiceLocked(sr, true);
10121 }
10122 }
10123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010124 }
10125 }
10126
10127 if (!allowRestart) {
10128 app.services.clear();
10129 }
10130 }
10131
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010132 // Make sure we have no more records on the stopping list.
10133 int i = mStoppingServices.size();
10134 while (i > 0) {
10135 i--;
10136 ServiceRecord sr = mStoppingServices.get(i);
10137 if (sr.app == app) {
10138 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010139 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010140 }
10141 }
10142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010143 app.executingServices.clear();
10144 }
10145
10146 private final void removeDyingProviderLocked(ProcessRecord proc,
10147 ContentProviderRecord cpr) {
10148 synchronized (cpr) {
10149 cpr.launchingApp = null;
10150 cpr.notifyAll();
10151 }
10152
Amith Yamasani742a6712011-05-04 14:49:28 -070010153 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010154 String names[] = cpr.info.authority.split(";");
10155 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010156 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010157 }
10158
10159 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10160 while (cit.hasNext()) {
10161 ProcessRecord capp = cit.next();
10162 if (!capp.persistent && capp.thread != null
10163 && capp.pid != 0
10164 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010165 Slog.i(TAG, "Kill " + capp.processName
10166 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010167 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010168 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010169 capp.processName, capp.setAdj, "dying provider "
10170 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010171 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010172 }
10173 }
10174
10175 mLaunchingProviders.remove(cpr);
10176 }
10177
10178 /**
10179 * Main code for cleaning up a process when it has gone away. This is
10180 * called both as a result of the process dying, or directly when stopping
10181 * a process when running in single process mode.
10182 */
10183 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010184 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010185 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010186 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010187 }
10188
Dianne Hackborn36124872009-10-08 16:22:03 -070010189 mProcessesToGc.remove(app);
10190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010191 // Dismiss any open dialogs.
10192 if (app.crashDialog != null) {
10193 app.crashDialog.dismiss();
10194 app.crashDialog = null;
10195 }
10196 if (app.anrDialog != null) {
10197 app.anrDialog.dismiss();
10198 app.anrDialog = null;
10199 }
10200 if (app.waitDialog != null) {
10201 app.waitDialog.dismiss();
10202 app.waitDialog = null;
10203 }
10204
10205 app.crashing = false;
10206 app.notResponding = false;
10207
10208 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010209 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010210 app.thread = null;
10211 app.forcingToForeground = null;
10212 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010213 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010214 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010215 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010216
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010217 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010218
10219 boolean restart = false;
10220
10221 int NL = mLaunchingProviders.size();
10222
10223 // Remove published content providers.
10224 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010225 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010226 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010227 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010228 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010229 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010230
10231 // See if someone is waiting for this provider... in which
10232 // case we don't remove it, but just let it restart.
10233 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010234 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010235 for (; i<NL; i++) {
10236 if (mLaunchingProviders.get(i) == cpr) {
10237 restart = true;
10238 break;
10239 }
10240 }
10241 } else {
10242 i = NL;
10243 }
10244
10245 if (i >= NL) {
10246 removeDyingProviderLocked(app, cpr);
10247 NL = mLaunchingProviders.size();
10248 }
10249 }
10250 app.pubProviders.clear();
10251 }
10252
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010253 // Take care of any launching providers waiting for this process.
10254 if (checkAppInLaunchingProvidersLocked(app, false)) {
10255 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010256 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010258 // Unregister from connected content providers.
10259 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010260 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010261 while (it.hasNext()) {
10262 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10263 cpr.clients.remove(app);
10264 }
10265 app.conProviders.clear();
10266 }
10267
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010268 // At this point there may be remaining entries in mLaunchingProviders
10269 // where we were the only one waiting, so they are no longer of use.
10270 // Look for these and clean up if found.
10271 // XXX Commented out for now. Trying to figure out a way to reproduce
10272 // the actual situation to identify what is actually going on.
10273 if (false) {
10274 for (int i=0; i<NL; i++) {
10275 ContentProviderRecord cpr = (ContentProviderRecord)
10276 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010277 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010278 synchronized (cpr) {
10279 cpr.launchingApp = null;
10280 cpr.notifyAll();
10281 }
10282 }
10283 }
10284 }
10285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010286 skipCurrentReceiverLocked(app);
10287
10288 // Unregister any receivers.
10289 if (app.receivers.size() > 0) {
10290 Iterator<ReceiverList> it = app.receivers.iterator();
10291 while (it.hasNext()) {
10292 removeReceiverLocked(it.next());
10293 }
10294 app.receivers.clear();
10295 }
10296
Christopher Tate181fafa2009-05-14 11:12:14 -070010297 // If the app is undergoing backup, tell the backup manager about it
10298 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010299 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010300 try {
10301 IBackupManager bm = IBackupManager.Stub.asInterface(
10302 ServiceManager.getService(Context.BACKUP_SERVICE));
10303 bm.agentDisconnected(app.info.packageName);
10304 } catch (RemoteException e) {
10305 // can't happen; backup manager is local
10306 }
10307 }
10308
Jeff Sharkey287bd832011-05-28 19:36:26 -070010309 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010311 // If the caller is restarting this app, then leave it in its
10312 // current lists and let the caller take care of it.
10313 if (restarting) {
10314 return;
10315 }
10316
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010317 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010318 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010319 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010320 mProcessNames.remove(app.processName, app.uid);
10321 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010322 if (mHeavyWeightProcess == app) {
10323 mHeavyWeightProcess = null;
10324 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010326 } else if (!app.removed) {
10327 // This app is persistent, so we need to keep its record around.
10328 // If it is not already on the pending app list, add it there
10329 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010330 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10331 mPersistentStartingProcesses.add(app);
10332 restart = true;
10333 }
10334 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010335 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10336 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010337 mProcessesOnHold.remove(app);
10338
The Android Open Source Project4df24232009-03-05 14:34:35 -080010339 if (app == mHomeProcess) {
10340 mHomeProcess = null;
10341 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010342 if (app == mPreviousProcess) {
10343 mPreviousProcess = null;
10344 }
10345
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010346 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010347 // We have components that still need to be running in the
10348 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010349 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010350 startProcessLocked(app, "restart", app.processName);
10351 } else if (app.pid > 0 && app.pid != MY_PID) {
10352 // Goodbye!
10353 synchronized (mPidsSelfLocked) {
10354 mPidsSelfLocked.remove(app.pid);
10355 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10356 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010357 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010358 }
10359 }
10360
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010361 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10362 // Look through the content providers we are waiting to have launched,
10363 // and if any run in this process then either schedule a restart of
10364 // the process or kill the client waiting for it if this process has
10365 // gone bad.
10366 int NL = mLaunchingProviders.size();
10367 boolean restart = false;
10368 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010369 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010370 if (cpr.launchingApp == app) {
10371 if (!alwaysBad && !app.bad) {
10372 restart = true;
10373 } else {
10374 removeDyingProviderLocked(app, cpr);
10375 NL = mLaunchingProviders.size();
10376 }
10377 }
10378 }
10379 return restart;
10380 }
10381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010382 // =========================================================
10383 // SERVICES
10384 // =========================================================
10385
10386 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10387 ActivityManager.RunningServiceInfo info =
10388 new ActivityManager.RunningServiceInfo();
10389 info.service = r.name;
10390 if (r.app != null) {
10391 info.pid = r.app.pid;
10392 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010393 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010394 info.process = r.processName;
10395 info.foreground = r.isForeground;
10396 info.activeSince = r.createTime;
10397 info.started = r.startRequested;
10398 info.clientCount = r.connections.size();
10399 info.crashCount = r.crashCount;
10400 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010401 if (r.isForeground) {
10402 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10403 }
10404 if (r.startRequested) {
10405 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10406 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010407 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010408 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10409 }
10410 if (r.app != null && r.app.persistent) {
10411 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10412 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010413
10414 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10415 for (int i=0; i<connl.size(); i++) {
10416 ConnectionRecord conn = connl.get(i);
10417 if (conn.clientLabel != 0) {
10418 info.clientPackage = conn.binding.client.info.packageName;
10419 info.clientLabel = conn.clientLabel;
10420 return info;
10421 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010422 }
10423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010424 return info;
10425 }
10426
10427 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10428 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010429 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010430 synchronized (this) {
10431 ArrayList<ActivityManager.RunningServiceInfo> res
10432 = new ArrayList<ActivityManager.RunningServiceInfo>();
10433
Amith Yamasani742a6712011-05-04 14:49:28 -070010434 int userId = UserId.getUserId(Binder.getCallingUid());
10435 if (mServiceMap.getAllServices(userId).size() > 0) {
10436 Iterator<ServiceRecord> it
10437 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010438 while (it.hasNext() && res.size() < maxNum) {
10439 res.add(makeRunningServiceInfoLocked(it.next()));
10440 }
10441 }
10442
10443 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10444 ServiceRecord r = mRestartingServices.get(i);
10445 ActivityManager.RunningServiceInfo info =
10446 makeRunningServiceInfoLocked(r);
10447 info.restarting = r.nextRestartTime;
10448 res.add(info);
10449 }
10450
10451 return res;
10452 }
10453 }
10454
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010455 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010456 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010457 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010458 int userId = UserId.getUserId(Binder.getCallingUid());
10459 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010460 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010461 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10462 for (int i=0; i<conn.size(); i++) {
10463 if (conn.get(i).clientIntent != null) {
10464 return conn.get(i).clientIntent;
10465 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010466 }
10467 }
10468 }
10469 }
10470 return null;
10471 }
10472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010473 private final ServiceRecord findServiceLocked(ComponentName name,
10474 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010475 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010476 return r == token ? r : null;
10477 }
10478
10479 private final class ServiceLookupResult {
10480 final ServiceRecord record;
10481 final String permission;
10482
10483 ServiceLookupResult(ServiceRecord _record, String _permission) {
10484 record = _record;
10485 permission = _permission;
10486 }
10487 };
10488
10489 private ServiceLookupResult findServiceLocked(Intent service,
10490 String resolvedType) {
10491 ServiceRecord r = null;
10492 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010493 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010494 }
10495 if (r == null) {
10496 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070010497 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010498 }
10499
10500 if (r == null) {
10501 try {
10502 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010503 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010504 service, resolvedType, 0);
10505 ServiceInfo sInfo =
10506 rInfo != null ? rInfo.serviceInfo : null;
10507 if (sInfo == null) {
10508 return null;
10509 }
10510
10511 ComponentName name = new ComponentName(
10512 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010513 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 } catch (RemoteException ex) {
10515 // pm is in same process, this will never happen.
10516 }
10517 }
10518 if (r != null) {
10519 int callingPid = Binder.getCallingPid();
10520 int callingUid = Binder.getCallingUid();
10521 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010522 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010523 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010524 if (!r.exported) {
10525 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10526 + " from pid=" + callingPid
10527 + ", uid=" + callingUid
10528 + " that is not exported from uid " + r.appInfo.uid);
10529 return new ServiceLookupResult(null, "not exported from uid "
10530 + r.appInfo.uid);
10531 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010532 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010533 + " from pid=" + callingPid
10534 + ", uid=" + callingUid
10535 + " requires " + r.permission);
10536 return new ServiceLookupResult(null, r.permission);
10537 }
10538 return new ServiceLookupResult(r, null);
10539 }
10540 return null;
10541 }
10542
10543 private class ServiceRestarter implements Runnable {
10544 private ServiceRecord mService;
10545
10546 void setService(ServiceRecord service) {
10547 mService = service;
10548 }
10549
10550 public void run() {
10551 synchronized(ActivityManagerService.this) {
10552 performServiceRestartLocked(mService);
10553 }
10554 }
10555 }
10556
10557 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010558 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010559 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010560 if (DEBUG_SERVICE)
10561 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010562 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010564 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010565 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010566 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010567 if (r == null) {
10568 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010569 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010571 if (r == null) {
10572 try {
10573 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010574 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010575 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010576 ServiceInfo sInfo =
10577 rInfo != null ? rInfo.serviceInfo : null;
10578 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010579 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010580 ": not found");
10581 return null;
10582 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010583 if (userId > 0) {
10584 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010586 ComponentName name = new ComponentName(
10587 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010588 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010589 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010590 Intent.FilterComparison filter = new Intent.FilterComparison(
10591 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010592 ServiceRestarter res = new ServiceRestarter();
10593 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10594 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10595 synchronized (stats) {
10596 ss = stats.getServiceStatsLocked(
10597 sInfo.applicationInfo.uid, sInfo.packageName,
10598 sInfo.name);
10599 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010600 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010601 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010602 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10603 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010604
10605 // Make sure this component isn't in the pending list.
10606 int N = mPendingServices.size();
10607 for (int i=0; i<N; i++) {
10608 ServiceRecord pr = mPendingServices.get(i);
10609 if (pr.name.equals(name)) {
10610 mPendingServices.remove(i);
10611 i--;
10612 N--;
10613 }
10614 }
10615 }
10616 } catch (RemoteException ex) {
10617 // pm is in same process, this will never happen.
10618 }
10619 }
10620 if (r != null) {
10621 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010622 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010623 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010624 if (!r.exported) {
10625 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10626 + " from pid=" + callingPid
10627 + ", uid=" + callingUid
10628 + " that is not exported from uid " + r.appInfo.uid);
10629 return new ServiceLookupResult(null, "not exported from uid "
10630 + r.appInfo.uid);
10631 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010632 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010633 + " from pid=" + callingPid
10634 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010635 + " requires " + r.permission);
10636 return new ServiceLookupResult(null, r.permission);
10637 }
10638 return new ServiceLookupResult(r, null);
10639 }
10640 return null;
10641 }
10642
Dianne Hackborn287952c2010-09-22 22:34:31 -070010643 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10644 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10645 + why + " of " + r + " in app " + r.app);
10646 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10647 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010648 long now = SystemClock.uptimeMillis();
10649 if (r.executeNesting == 0 && r.app != null) {
10650 if (r.app.executingServices.size() == 0) {
10651 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10652 msg.obj = r.app;
10653 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10654 }
10655 r.app.executingServices.add(r);
10656 }
10657 r.executeNesting++;
10658 r.executingStart = now;
10659 }
10660
10661 private final void sendServiceArgsLocked(ServiceRecord r,
10662 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010663 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010664 if (N == 0) {
10665 return;
10666 }
10667
Dianne Hackborn39792d22010-08-19 18:01:52 -070010668 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010669 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010670 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010671 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10672 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010673 if (si.intent == null && N > 1) {
10674 // If somehow we got a dummy null intent in the middle,
10675 // then skip it. DO NOT skip a null intent when it is
10676 // the only one in the list -- this is to support the
10677 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010678 continue;
10679 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010680 si.deliveredTime = SystemClock.uptimeMillis();
10681 r.deliveredStarts.add(si);
10682 si.deliveryCount++;
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010683 if (si.targetPermissionUid >= 0 && si.intent != null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010684 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -070010685 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010686 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010687 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 if (!oomAdjusted) {
10689 oomAdjusted = true;
10690 updateOomAdjLocked(r.app);
10691 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010692 int flags = 0;
10693 if (si.deliveryCount > 0) {
10694 flags |= Service.START_FLAG_RETRY;
10695 }
10696 if (si.doneExecutingCount > 0) {
10697 flags |= Service.START_FLAG_REDELIVERY;
10698 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010699 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010700 } catch (RemoteException e) {
10701 // Remote process gone... we'll let the normal cleanup take
10702 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010703 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010704 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010705 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010706 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010707 break;
10708 }
10709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010710 }
10711
10712 private final boolean requestServiceBindingLocked(ServiceRecord r,
10713 IntentBindRecord i, boolean rebind) {
10714 if (r.app == null || r.app.thread == null) {
10715 // If service is not currently running, can't yet bind.
10716 return false;
10717 }
10718 if ((!i.requested || rebind) && i.apps.size() > 0) {
10719 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010720 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010721 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10722 if (!rebind) {
10723 i.requested = true;
10724 }
10725 i.hasBound = true;
10726 i.doRebind = false;
10727 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010728 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010729 return false;
10730 }
10731 }
10732 return true;
10733 }
10734
10735 private final void requestServiceBindingsLocked(ServiceRecord r) {
10736 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10737 while (bindings.hasNext()) {
10738 IntentBindRecord i = bindings.next();
10739 if (!requestServiceBindingLocked(r, i, false)) {
10740 break;
10741 }
10742 }
10743 }
10744
10745 private final void realStartServiceLocked(ServiceRecord r,
10746 ProcessRecord app) throws RemoteException {
10747 if (app.thread == null) {
10748 throw new RemoteException();
10749 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010750 if (DEBUG_MU)
10751 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010752 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010753 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010754 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010755
10756 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010757 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010758 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010759
10760 boolean created = false;
10761 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010762 mStringBuilder.setLength(0);
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010763 r.intent.getIntent().toShortString(mStringBuilder, true, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010764 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010765 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010766 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010767 synchronized (r.stats.getBatteryStats()) {
10768 r.stats.startLaunchedLocked();
10769 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010770 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010771 app.thread.scheduleCreateService(r, r.serviceInfo,
10772 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010773 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010774 created = true;
10775 } finally {
10776 if (!created) {
10777 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010778 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010779 }
10780 }
10781
10782 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010783
10784 // If the service is in the started state, and there are no
10785 // pending arguments, then fake up one so its onStartCommand() will
10786 // be called.
10787 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010788 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
10789 null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010790 }
10791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010792 sendServiceArgsLocked(r, true);
10793 }
10794
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010795 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10796 boolean allowCancel) {
10797 boolean canceled = false;
10798
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010799 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010800 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010801 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010802
Dianne Hackborn070783f2010-12-29 16:46:28 -080010803 if ((r.serviceInfo.applicationInfo.flags
10804 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10805 minDuration /= 4;
10806 }
10807
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010808 // Any delivered but not yet finished starts should be put back
10809 // on the pending list.
10810 final int N = r.deliveredStarts.size();
10811 if (N > 0) {
10812 for (int i=N-1; i>=0; i--) {
10813 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070010814 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010815 if (si.intent == null) {
10816 // We'll generate this again if needed.
10817 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
10818 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
10819 r.pendingStarts.add(0, si);
10820 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
10821 dur *= 2;
10822 if (minDuration < dur) minDuration = dur;
10823 if (resetTime < dur) resetTime = dur;
10824 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010825 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010826 + r.name);
10827 canceled = true;
10828 }
10829 }
10830 r.deliveredStarts.clear();
10831 }
10832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 r.totalRestartCount++;
10834 if (r.restartDelay == 0) {
10835 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010836 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010837 } else {
10838 // If it has been a "reasonably long time" since the service
10839 // was started, then reset our restart duration back to
10840 // the beginning, so we don't infinitely increase the duration
10841 // on a service that just occasionally gets killed (which is
10842 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010843 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010844 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010845 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010846 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080010847 if ((r.serviceInfo.applicationInfo.flags
10848 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10849 // Services in peristent processes will restart much more
10850 // quickly, since they are pretty important. (Think SystemUI).
10851 r.restartDelay += minDuration/2;
10852 } else {
10853 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
10854 if (r.restartDelay < minDuration) {
10855 r.restartDelay = minDuration;
10856 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010858 }
10859 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010860
10861 r.nextRestartTime = now + r.restartDelay;
10862
10863 // Make sure that we don't end up restarting a bunch of services
10864 // all at the same time.
10865 boolean repeat;
10866 do {
10867 repeat = false;
10868 for (int i=mRestartingServices.size()-1; i>=0; i--) {
10869 ServiceRecord r2 = mRestartingServices.get(i);
10870 if (r2 != r && r.nextRestartTime
10871 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
10872 && r.nextRestartTime
10873 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
10874 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
10875 r.restartDelay = r.nextRestartTime - now;
10876 repeat = true;
10877 break;
10878 }
10879 }
10880 } while (repeat);
10881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010882 if (!mRestartingServices.contains(r)) {
10883 mRestartingServices.add(r);
10884 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010885
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010886 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010888 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010889 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010890 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010891 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010892 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080010893 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 r.shortName, r.restartDelay);
10895
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010896 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010897 }
10898
10899 final void performServiceRestartLocked(ServiceRecord r) {
10900 if (!mRestartingServices.contains(r)) {
10901 return;
10902 }
10903 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
10904 }
10905
10906 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
10907 if (r.restartDelay == 0) {
10908 return false;
10909 }
10910 r.resetRestartCounter();
10911 mRestartingServices.remove(r);
10912 mHandler.removeCallbacks(r.restarter);
10913 return true;
10914 }
10915
10916 private final boolean bringUpServiceLocked(ServiceRecord r,
10917 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010918 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010919 //r.dump(" ");
10920
Dianne Hackborn36124872009-10-08 16:22:03 -070010921 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 sendServiceArgsLocked(r, false);
10923 return true;
10924 }
10925
10926 if (!whileRestarting && r.restartDelay > 0) {
10927 // If waiting for a restart, then do nothing.
10928 return true;
10929 }
10930
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010931 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010932
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010933 // We are now bringing the service up, so no longer in the
10934 // restarting state.
10935 mRestartingServices.remove(r);
10936
Dianne Hackborne7f97212011-02-24 14:40:20 -080010937 // Service is now being launched, its package can't be stopped.
10938 try {
10939 AppGlobals.getPackageManager().setPackageStoppedState(
10940 r.packageName, false);
10941 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010942 } catch (IllegalArgumentException e) {
10943 Slog.w(TAG, "Failed trying to unstop package "
10944 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010945 }
10946
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010947 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010949 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010950
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010951 if (!isolated) {
10952 app = getProcessRecordLocked(appName, r.appInfo.uid);
10953 if (DEBUG_MU)
10954 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
10955 if (app != null && app.thread != null) {
10956 try {
10957 app.addPackage(r.appInfo.packageName);
10958 realStartServiceLocked(r, app);
10959 return true;
10960 } catch (RemoteException e) {
10961 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
10962 }
10963
10964 // If a dead object exception was thrown -- fall through to
10965 // restart the application.
10966 }
10967 } else {
10968 // If this service runs in an isolated process, then each time
10969 // we call startProcessLocked() we will get a new isolated
10970 // process, starting another process if we are currently waiting
10971 // for a previous process to come up. To deal with this, we store
10972 // in the service any current isolated process it is running in or
10973 // waiting to have come up.
10974 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010975 }
10976
Dianne Hackborn36124872009-10-08 16:22:03 -070010977 // Not running -- get it started, and enqueue this service record
10978 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010979 if (app == null) {
10980 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
10981 "service", r.name, false, isolated)) == null) {
10982 Slog.w(TAG, "Unable to launch app "
10983 + r.appInfo.packageName + "/"
10984 + r.appInfo.uid + " for service "
10985 + r.intent.getIntent() + ": process is bad");
10986 bringDownServiceLocked(r, true);
10987 return false;
10988 }
10989 if (isolated) {
10990 r.isolatedProc = app;
10991 }
Dianne Hackborn36124872009-10-08 16:22:03 -070010992 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010995 mPendingServices.add(r);
10996 }
Dianne Hackborn36124872009-10-08 16:22:03 -070010997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010998 return true;
10999 }
11000
11001 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011002 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011003 //r.dump(" ");
11004
11005 // Does it still need to run?
11006 if (!force && r.startRequested) {
11007 return;
11008 }
11009 if (r.connections.size() > 0) {
11010 if (!force) {
11011 // XXX should probably keep a count of the number of auto-create
11012 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011013 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011014 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011015 ArrayList<ConnectionRecord> cr = it.next();
11016 for (int i=0; i<cr.size(); i++) {
11017 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11018 return;
11019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011020 }
11021 }
11022 }
11023
11024 // Report to all of the connections that the service is no longer
11025 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011026 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011027 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011028 ArrayList<ConnectionRecord> c = it.next();
11029 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011030 ConnectionRecord cr = c.get(i);
11031 // There is still a connection to the service that is
11032 // being brought down. Mark it as dead.
11033 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011034 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011035 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011036 } catch (Exception e) {
11037 Slog.w(TAG, "Failure disconnecting service " + r.name +
11038 " to connection " + c.get(i).conn.asBinder() +
11039 " (in " + c.get(i).binding.client.processName + ")", e);
11040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011041 }
11042 }
11043 }
11044
11045 // Tell the service that it has been unbound.
11046 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11047 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11048 while (it.hasNext()) {
11049 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011050 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011051 + ": hasBound=" + ibr.hasBound);
11052 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11053 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011054 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011055 updateOomAdjLocked(r.app);
11056 ibr.hasBound = false;
11057 r.app.thread.scheduleUnbindService(r,
11058 ibr.intent.getIntent());
11059 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011060 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011061 + r.shortName, e);
11062 serviceDoneExecutingLocked(r, true);
11063 }
11064 }
11065 }
11066 }
11067
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011068 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011069 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011070 System.identityHashCode(r), r.shortName,
11071 (r.app != null) ? r.app.pid : -1);
11072
Amith Yamasani742a6712011-05-04 14:49:28 -070011073 mServiceMap.removeServiceByName(r.name, r.userId);
11074 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011075 r.totalRestartCount = 0;
11076 unscheduleServiceRestartLocked(r);
11077
11078 // Also make sure it is not on the pending list.
11079 int N = mPendingServices.size();
11080 for (int i=0; i<N; i++) {
11081 if (mPendingServices.get(i) == r) {
11082 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011083 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011084 i--;
11085 N--;
11086 }
11087 }
11088
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011089 r.cancelNotification();
11090 r.isForeground = false;
11091 r.foregroundId = 0;
11092 r.foregroundNoti = null;
11093
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011094 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011095 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011096 r.pendingStarts.clear();
11097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011098 if (r.app != null) {
11099 synchronized (r.stats.getBatteryStats()) {
11100 r.stats.stopLaunchedLocked();
11101 }
11102 r.app.services.remove(r);
11103 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011104 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011105 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011106 mStoppingServices.add(r);
11107 updateOomAdjLocked(r.app);
11108 r.app.thread.scheduleStopService(r);
11109 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011110 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011111 + r.shortName, e);
11112 serviceDoneExecutingLocked(r, true);
11113 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011114 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011115 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011116 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011117 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011118 }
11119 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011120 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011121 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011122 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011123
11124 if (r.bindings.size() > 0) {
11125 r.bindings.clear();
11126 }
11127
11128 if (r.restarter instanceof ServiceRestarter) {
11129 ((ServiceRestarter)r.restarter).setService(null);
11130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011131 }
11132
11133 ComponentName startServiceLocked(IApplicationThread caller,
11134 Intent service, String resolvedType,
11135 int callingPid, int callingUid) {
11136 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011137 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011138 + " type=" + resolvedType + " args=" + service.getExtras());
11139
11140 if (caller != null) {
11141 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11142 if (callerApp == null) {
11143 throw new SecurityException(
11144 "Unable to find app for caller " + caller
11145 + " (pid=" + Binder.getCallingPid()
11146 + ") when starting service " + service);
11147 }
11148 }
11149
11150 ServiceLookupResult res =
11151 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011152 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011153 if (res == null) {
11154 return null;
11155 }
11156 if (res.record == null) {
11157 return new ComponentName("!", res.permission != null
11158 ? res.permission : "private to package");
11159 }
11160 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -070011161 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
11162 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011163 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011164 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 }
11166 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011167 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011168 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn39792d22010-08-19 18:01:52 -070011169 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011170 r.lastActivity = SystemClock.uptimeMillis();
11171 synchronized (r.stats.getBatteryStats()) {
11172 r.stats.startRunningLocked();
11173 }
11174 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11175 return new ComponentName("!", "Service process is bad");
11176 }
11177 return r.name;
11178 }
11179 }
11180
11181 public ComponentName startService(IApplicationThread caller, Intent service,
11182 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011183 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011184 // Refuse possible leaked file descriptors
11185 if (service != null && service.hasFileDescriptors() == true) {
11186 throw new IllegalArgumentException("File descriptors passed in Intent");
11187 }
11188
Amith Yamasani742a6712011-05-04 14:49:28 -070011189 if (DEBUG_SERVICE)
11190 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011191 synchronized(this) {
11192 final int callingPid = Binder.getCallingPid();
11193 final int callingUid = Binder.getCallingUid();
11194 final long origId = Binder.clearCallingIdentity();
11195 ComponentName res = startServiceLocked(caller, service,
11196 resolvedType, callingPid, callingUid);
11197 Binder.restoreCallingIdentity(origId);
11198 return res;
11199 }
11200 }
11201
11202 ComponentName startServiceInPackage(int uid,
11203 Intent service, String resolvedType) {
11204 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011205 if (DEBUG_SERVICE)
11206 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011207 final long origId = Binder.clearCallingIdentity();
11208 ComponentName res = startServiceLocked(null, service,
11209 resolvedType, -1, uid);
11210 Binder.restoreCallingIdentity(origId);
11211 return res;
11212 }
11213 }
11214
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011215 private void stopServiceLocked(ServiceRecord service) {
11216 synchronized (service.stats.getBatteryStats()) {
11217 service.stats.stopRunningLocked();
11218 }
11219 service.startRequested = false;
11220 service.callStart = false;
11221 bringDownServiceLocked(service, false);
11222 }
11223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011224 public int stopService(IApplicationThread caller, Intent service,
11225 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011226 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011227 // Refuse possible leaked file descriptors
11228 if (service != null && service.hasFileDescriptors() == true) {
11229 throw new IllegalArgumentException("File descriptors passed in Intent");
11230 }
11231
11232 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011233 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011234 + " type=" + resolvedType);
11235
11236 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11237 if (caller != null && callerApp == null) {
11238 throw new SecurityException(
11239 "Unable to find app for caller " + caller
11240 + " (pid=" + Binder.getCallingPid()
11241 + ") when stopping service " + service);
11242 }
11243
11244 // If this service is active, make sure it is stopped.
11245 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11246 if (r != null) {
11247 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011248 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011249 try {
11250 stopServiceLocked(r.record);
11251 } finally {
11252 Binder.restoreCallingIdentity(origId);
11253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011254 return 1;
11255 }
11256 return -1;
11257 }
11258 }
11259
11260 return 0;
11261 }
11262
11263 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011264 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011265 // Refuse possible leaked file descriptors
11266 if (service != null && service.hasFileDescriptors() == true) {
11267 throw new IllegalArgumentException("File descriptors passed in Intent");
11268 }
11269
11270 IBinder ret = null;
11271
11272 synchronized(this) {
11273 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11274
11275 if (r != null) {
11276 // r.record is null if findServiceLocked() failed the caller permission check
11277 if (r.record == null) {
11278 throw new SecurityException(
11279 "Permission Denial: Accessing service " + r.record.name
11280 + " from pid=" + Binder.getCallingPid()
11281 + ", uid=" + Binder.getCallingUid()
11282 + " requires " + r.permission);
11283 }
11284 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11285 if (ib != null) {
11286 ret = ib.binder;
11287 }
11288 }
11289 }
11290
11291 return ret;
11292 }
11293
11294 public boolean stopServiceToken(ComponentName className, IBinder token,
11295 int startId) {
11296 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011297 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011298 + " " + token + " startId=" + startId);
11299 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011300 if (r != null) {
11301 if (startId >= 0) {
11302 // Asked to only stop if done with all work. Note that
11303 // to avoid leaks, we will take this as dropping all
11304 // start items up to and including this one.
11305 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11306 if (si != null) {
11307 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011308 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11309 cur.removeUriPermissionsLocked();
11310 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011311 break;
11312 }
11313 }
11314 }
11315
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011316 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011317 return false;
11318 }
11319
11320 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011321 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011322 + " is last, but have " + r.deliveredStarts.size()
11323 + " remaining args");
11324 }
11325 }
11326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011327 synchronized (r.stats.getBatteryStats()) {
11328 r.stats.stopRunningLocked();
11329 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011330 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 }
11332 final long origId = Binder.clearCallingIdentity();
11333 bringDownServiceLocked(r, false);
11334 Binder.restoreCallingIdentity(origId);
11335 return true;
11336 }
11337 }
11338 return false;
11339 }
11340
11341 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011342 int id, Notification notification, boolean removeNotification) {
11343 final long origId = Binder.clearCallingIdentity();
11344 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011345 synchronized(this) {
11346 ServiceRecord r = findServiceLocked(className, token);
11347 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011348 if (id != 0) {
11349 if (notification == null) {
11350 throw new IllegalArgumentException("null notification");
11351 }
11352 if (r.foregroundId != id) {
11353 r.cancelNotification();
11354 r.foregroundId = id;
11355 }
11356 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11357 r.foregroundNoti = notification;
11358 r.isForeground = true;
11359 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011360 if (r.app != null) {
11361 updateServiceForegroundLocked(r.app, true);
11362 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011363 } else {
11364 if (r.isForeground) {
11365 r.isForeground = false;
11366 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011367 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011368 updateServiceForegroundLocked(r.app, true);
11369 }
11370 }
11371 if (removeNotification) {
11372 r.cancelNotification();
11373 r.foregroundId = 0;
11374 r.foregroundNoti = null;
11375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011376 }
11377 }
11378 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011379 } finally {
11380 Binder.restoreCallingIdentity(origId);
11381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011382 }
11383
11384 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11385 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011386 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 if (sr.isForeground) {
11388 anyForeground = true;
11389 break;
11390 }
11391 }
11392 if (anyForeground != proc.foregroundServices) {
11393 proc.foregroundServices = anyForeground;
11394 if (oomAdj) {
11395 updateOomAdjLocked();
11396 }
11397 }
11398 }
11399
11400 public int bindService(IApplicationThread caller, IBinder token,
11401 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011402 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011403 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011404 // Refuse possible leaked file descriptors
11405 if (service != null && service.hasFileDescriptors() == true) {
11406 throw new IllegalArgumentException("File descriptors passed in Intent");
11407 }
11408
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011409 checkValidCaller(Binder.getCallingUid(), userId);
11410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011411 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011412 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011413 + " type=" + resolvedType + " conn=" + connection.asBinder()
11414 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011415 if (DEBUG_MU)
11416 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11417 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11419 if (callerApp == null) {
11420 throw new SecurityException(
11421 "Unable to find app for caller " + caller
11422 + " (pid=" + Binder.getCallingPid()
11423 + ") when binding service " + service);
11424 }
11425
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011426 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011427 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011428 activity = mMainStack.isInStackLocked(token);
11429 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011430 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011431 return 0;
11432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011433 }
11434
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011435 int clientLabel = 0;
11436 PendingIntent clientIntent = null;
11437
11438 if (callerApp.info.uid == Process.SYSTEM_UID) {
11439 // Hacky kind of thing -- allow system stuff to tell us
11440 // what they are, so we can report this elsewhere for
11441 // others to know why certain services are running.
11442 try {
11443 clientIntent = (PendingIntent)service.getParcelableExtra(
11444 Intent.EXTRA_CLIENT_INTENT);
11445 } catch (RuntimeException e) {
11446 }
11447 if (clientIntent != null) {
11448 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11449 if (clientLabel != 0) {
11450 // There are no useful extras in the intent, trash them.
11451 // System code calling with this stuff just needs to know
11452 // this will happen.
11453 service = service.cloneFilter();
11454 }
11455 }
11456 }
11457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011458 ServiceLookupResult res =
11459 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011460 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011461 if (res == null) {
11462 return 0;
11463 }
11464 if (res.record == null) {
11465 return -1;
11466 }
11467 ServiceRecord s = res.record;
11468
11469 final long origId = Binder.clearCallingIdentity();
11470
11471 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011472 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011473 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011474 }
11475
11476 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11477 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011478 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011479
11480 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011481 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11482 if (clist == null) {
11483 clist = new ArrayList<ConnectionRecord>();
11484 s.connections.put(binder, clist);
11485 }
11486 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011487 b.connections.add(c);
11488 if (activity != null) {
11489 if (activity.connections == null) {
11490 activity.connections = new HashSet<ConnectionRecord>();
11491 }
11492 activity.connections.add(c);
11493 }
11494 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011495 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11496 b.client.hasAboveClient = true;
11497 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011498 clist = mServiceConnections.get(binder);
11499 if (clist == null) {
11500 clist = new ArrayList<ConnectionRecord>();
11501 mServiceConnections.put(binder, clist);
11502 }
11503 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011504
11505 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11506 s.lastActivity = SystemClock.uptimeMillis();
11507 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11508 return 0;
11509 }
11510 }
11511
11512 if (s.app != null) {
11513 // This could have made the service more important.
11514 updateOomAdjLocked(s.app);
11515 }
11516
Joe Onorato8a9b2202010-02-26 18:56:32 -080011517 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011518 + ": received=" + b.intent.received
11519 + " apps=" + b.intent.apps.size()
11520 + " doRebind=" + b.intent.doRebind);
11521
11522 if (s.app != null && b.intent.received) {
11523 // Service is already running, so we can immediately
11524 // publish the connection.
11525 try {
11526 c.conn.connected(s.name, b.intent.binder);
11527 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011528 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011529 + " to connection " + c.conn.asBinder()
11530 + " (in " + c.binding.client.processName + ")", e);
11531 }
11532
11533 // If this is the first app connected back to this binding,
11534 // and the service had previously asked to be told when
11535 // rebound, then do so.
11536 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11537 requestServiceBindingLocked(s, b.intent, true);
11538 }
11539 } else if (!b.intent.requested) {
11540 requestServiceBindingLocked(s, b.intent, false);
11541 }
11542
11543 Binder.restoreCallingIdentity(origId);
11544 }
11545
11546 return 1;
11547 }
11548
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011549 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011550 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011551 IBinder binder = c.conn.asBinder();
11552 AppBindRecord b = c.binding;
11553 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011554 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11555 if (clist != null) {
11556 clist.remove(c);
11557 if (clist.size() == 0) {
11558 s.connections.remove(binder);
11559 }
11560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011561 b.connections.remove(c);
11562 if (c.activity != null && c.activity != skipAct) {
11563 if (c.activity.connections != null) {
11564 c.activity.connections.remove(c);
11565 }
11566 }
11567 if (b.client != skipApp) {
11568 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011569 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11570 b.client.updateHasAboveClientLocked();
11571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011572 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011573 clist = mServiceConnections.get(binder);
11574 if (clist != null) {
11575 clist.remove(c);
11576 if (clist.size() == 0) {
11577 mServiceConnections.remove(binder);
11578 }
11579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011580
11581 if (b.connections.size() == 0) {
11582 b.intent.apps.remove(b.client);
11583 }
11584
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011585 if (!c.serviceDead) {
11586 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11587 + ": shouldUnbind=" + b.intent.hasBound);
11588 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11589 && b.intent.hasBound) {
11590 try {
11591 bumpServiceExecutingLocked(s, "unbind");
11592 updateOomAdjLocked(s.app);
11593 b.intent.hasBound = false;
11594 // Assume the client doesn't want to know about a rebind;
11595 // we will deal with that later if it asks for one.
11596 b.intent.doRebind = false;
11597 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11598 } catch (Exception e) {
11599 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11600 serviceDoneExecutingLocked(s, true);
11601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011602 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011603
11604 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11605 bringDownServiceLocked(s, false);
11606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011607 }
11608 }
11609
11610 public boolean unbindService(IServiceConnection connection) {
11611 synchronized (this) {
11612 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011613 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011614 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11615 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011616 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011617 + connection.asBinder());
11618 return false;
11619 }
11620
11621 final long origId = Binder.clearCallingIdentity();
11622
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011623 while (clist.size() > 0) {
11624 ConnectionRecord r = clist.get(0);
11625 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011626
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011627 if (r.binding.service.app != null) {
11628 // This could have made the service less important.
11629 updateOomAdjLocked(r.binding.service.app);
11630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011631 }
11632
11633 Binder.restoreCallingIdentity(origId);
11634 }
11635
11636 return true;
11637 }
11638
11639 public void publishService(IBinder token, Intent intent, IBinder service) {
11640 // Refuse possible leaked file descriptors
11641 if (intent != null && intent.hasFileDescriptors() == true) {
11642 throw new IllegalArgumentException("File descriptors passed in Intent");
11643 }
11644
11645 synchronized(this) {
11646 if (!(token instanceof ServiceRecord)) {
11647 throw new IllegalArgumentException("Invalid service token");
11648 }
11649 ServiceRecord r = (ServiceRecord)token;
11650
11651 final long origId = Binder.clearCallingIdentity();
11652
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011653 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011654 + " " + intent + ": " + service);
11655 if (r != null) {
11656 Intent.FilterComparison filter
11657 = new Intent.FilterComparison(intent);
11658 IntentBindRecord b = r.bindings.get(filter);
11659 if (b != null && !b.received) {
11660 b.binder = service;
11661 b.requested = true;
11662 b.received = true;
11663 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011664 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011665 = r.connections.values().iterator();
11666 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011667 ArrayList<ConnectionRecord> clist = it.next();
11668 for (int i=0; i<clist.size(); i++) {
11669 ConnectionRecord c = clist.get(i);
11670 if (!filter.equals(c.binding.intent.intent)) {
11671 if (DEBUG_SERVICE) Slog.v(
11672 TAG, "Not publishing to: " + c);
11673 if (DEBUG_SERVICE) Slog.v(
11674 TAG, "Bound intent: " + c.binding.intent.intent);
11675 if (DEBUG_SERVICE) Slog.v(
11676 TAG, "Published intent: " + intent);
11677 continue;
11678 }
11679 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11680 try {
11681 c.conn.connected(r.name, service);
11682 } catch (Exception e) {
11683 Slog.w(TAG, "Failure sending service " + r.name +
11684 " to connection " + c.conn.asBinder() +
11685 " (in " + c.binding.client.processName + ")", e);
11686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011687 }
11688 }
11689 }
11690 }
11691
11692 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11693
11694 Binder.restoreCallingIdentity(origId);
11695 }
11696 }
11697 }
11698
11699 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11700 // Refuse possible leaked file descriptors
11701 if (intent != null && intent.hasFileDescriptors() == true) {
11702 throw new IllegalArgumentException("File descriptors passed in Intent");
11703 }
11704
11705 synchronized(this) {
11706 if (!(token instanceof ServiceRecord)) {
11707 throw new IllegalArgumentException("Invalid service token");
11708 }
11709 ServiceRecord r = (ServiceRecord)token;
11710
11711 final long origId = Binder.clearCallingIdentity();
11712
11713 if (r != null) {
11714 Intent.FilterComparison filter
11715 = new Intent.FilterComparison(intent);
11716 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011717 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718 + " at " + b + ": apps="
11719 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011720
11721 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011722 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011723 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011724 // Applications have already bound since the last
11725 // unbind, so just rebind right here.
11726 requestServiceBindingLocked(r, b, true);
11727 } else {
11728 // Note to tell the service the next time there is
11729 // a new client.
11730 b.doRebind = true;
11731 }
11732 }
11733
Per Edelberg78f9fff2010-08-30 20:01:35 +020011734 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011735
11736 Binder.restoreCallingIdentity(origId);
11737 }
11738 }
11739 }
11740
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011741 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011742 synchronized(this) {
11743 if (!(token instanceof ServiceRecord)) {
11744 throw new IllegalArgumentException("Invalid service token");
11745 }
11746 ServiceRecord r = (ServiceRecord)token;
11747 boolean inStopping = mStoppingServices.contains(token);
11748 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011749 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011750 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011751 + " with incorrect token: given " + token
11752 + ", expected " + r);
11753 return;
11754 }
11755
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011756 if (type == 1) {
11757 // This is a call from a service start... take care of
11758 // book-keeping.
11759 r.callStart = true;
11760 switch (res) {
11761 case Service.START_STICKY_COMPATIBILITY:
11762 case Service.START_STICKY: {
11763 // We are done with the associated start arguments.
11764 r.findDeliveredStart(startId, true);
11765 // Don't stop if killed.
11766 r.stopIfKilled = false;
11767 break;
11768 }
11769 case Service.START_NOT_STICKY: {
11770 // We are done with the associated start arguments.
11771 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011772 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011773 // There is no more work, and this service
11774 // doesn't want to hang around if killed.
11775 r.stopIfKilled = true;
11776 }
11777 break;
11778 }
11779 case Service.START_REDELIVER_INTENT: {
11780 // We'll keep this item until they explicitly
11781 // call stop for it, but keep track of the fact
11782 // that it was delivered.
11783 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11784 if (si != null) {
11785 si.deliveryCount = 0;
11786 si.doneExecutingCount++;
11787 // Don't stop if killed.
11788 r.stopIfKilled = true;
11789 }
11790 break;
11791 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011792 case Service.START_TASK_REMOVED_COMPLETE: {
11793 // Special processing for onTaskRemoved(). Don't
11794 // impact normal onStartCommand() processing.
11795 r.findDeliveredStart(startId, true);
11796 break;
11797 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011798 default:
11799 throw new IllegalArgumentException(
11800 "Unknown service start result: " + res);
11801 }
11802 if (res == Service.START_STICKY_COMPATIBILITY) {
11803 r.callStart = false;
11804 }
11805 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011806 if (DEBUG_MU)
11807 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
11808 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011809 final long origId = Binder.clearCallingIdentity();
11810 serviceDoneExecutingLocked(r, inStopping);
11811 Binder.restoreCallingIdentity(origId);
11812 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011813 Slog.w(TAG, "Done executing unknown service from pid "
11814 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011815 }
11816 }
11817 }
11818
11819 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011820 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
11821 + ": nesting=" + r.executeNesting
11822 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011823 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011824 r.executeNesting--;
11825 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011826 if (DEBUG_SERVICE) Slog.v(TAG,
11827 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 r.app.executingServices.remove(r);
11829 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011830 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
11831 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
11833 }
11834 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011835 if (DEBUG_SERVICE) Slog.v(TAG,
11836 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011837 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020011838 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011839 }
11840 updateOomAdjLocked(r.app);
11841 }
11842 }
11843
11844 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011845 String anrMessage = null;
11846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011847 synchronized(this) {
11848 if (proc.executingServices.size() == 0 || proc.thread == null) {
11849 return;
11850 }
11851 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
11852 Iterator<ServiceRecord> it = proc.executingServices.iterator();
11853 ServiceRecord timeout = null;
11854 long nextTime = 0;
11855 while (it.hasNext()) {
11856 ServiceRecord sr = it.next();
11857 if (sr.executingStart < maxTime) {
11858 timeout = sr;
11859 break;
11860 }
11861 if (sr.executingStart > nextTime) {
11862 nextTime = sr.executingStart;
11863 }
11864 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011865 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011866 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011867 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011868 } else {
11869 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11870 msg.obj = proc;
11871 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
11872 }
11873 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011874
11875 if (anrMessage != null) {
11876 appNotResponding(proc, null, null, anrMessage);
11877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011878 }
11879
11880 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011881 // BACKUP AND RESTORE
11882 // =========================================================
11883
11884 // Cause the target app to be launched if necessary and its backup agent
11885 // instantiated. The backup agent will invoke backupAgentCreated() on the
11886 // activity manager to announce its creation.
11887 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011888 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011889 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11890
11891 synchronized(this) {
11892 // !!! TODO: currently no check here that we're already bound
11893 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11894 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11895 synchronized (stats) {
11896 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11897 }
11898
Dianne Hackborne7f97212011-02-24 14:40:20 -080011899 // Backup agent is now in use, its package can't be stopped.
11900 try {
11901 AppGlobals.getPackageManager().setPackageStoppedState(
11902 app.packageName, false);
11903 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011904 } catch (IllegalArgumentException e) {
11905 Slog.w(TAG, "Failed trying to unstop package "
11906 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011907 }
11908
Christopher Tate181fafa2009-05-14 11:12:14 -070011909 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011910 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11911 ? new ComponentName(app.packageName, app.backupAgentName)
11912 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011913 // startProcessLocked() returns existing proc's record if it's already running
11914 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011915 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011916 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011917 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011918 return false;
11919 }
11920
11921 r.app = proc;
11922 mBackupTarget = r;
11923 mBackupAppName = app.packageName;
11924
Christopher Tate6fa95972009-06-05 18:43:55 -070011925 // Try not to kill the process during backup
11926 updateOomAdjLocked(proc);
11927
Christopher Tate181fafa2009-05-14 11:12:14 -070011928 // If the process is already attached, schedule the creation of the backup agent now.
11929 // If it is not yet live, this will be done when it attaches to the framework.
11930 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011931 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011932 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011933 proc.thread.scheduleCreateBackupAgent(app,
11934 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011935 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011936 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011937 }
11938 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011939 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011940 }
11941 // Invariants: at this point, the target app process exists and the application
11942 // is either already running or in the process of coming up. mBackupTarget and
11943 // mBackupAppName describe the app, so that when it binds back to the AM we
11944 // know that it's scheduled for a backup-agent operation.
11945 }
11946
11947 return true;
11948 }
11949
11950 // A backup agent has just come up
11951 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011952 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011953 + " = " + agent);
11954
11955 synchronized(this) {
11956 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011957 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011958 return;
11959 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011960 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011961
Dianne Hackborn06740692010-09-22 22:46:21 -070011962 long oldIdent = Binder.clearCallingIdentity();
11963 try {
11964 IBackupManager bm = IBackupManager.Stub.asInterface(
11965 ServiceManager.getService(Context.BACKUP_SERVICE));
11966 bm.agentConnected(agentPackageName, agent);
11967 } catch (RemoteException e) {
11968 // can't happen; the backup manager service is local
11969 } catch (Exception e) {
11970 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11971 e.printStackTrace();
11972 } finally {
11973 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011974 }
11975 }
11976
11977 // done with this agent
11978 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011979 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011980 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011981 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011982 return;
11983 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011984
11985 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011986 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011987 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011988 return;
11989 }
11990
Christopher Tate181fafa2009-05-14 11:12:14 -070011991 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011992 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011993 return;
11994 }
11995
Christopher Tate6fa95972009-06-05 18:43:55 -070011996 ProcessRecord proc = mBackupTarget.app;
11997 mBackupTarget = null;
11998 mBackupAppName = null;
11999
12000 // Not backing this app up any more; reset its OOM adjustment
12001 updateOomAdjLocked(proc);
12002
Christopher Tatec7b31e32009-06-10 15:49:30 -070012003 // If the app crashed during backup, 'thread' will be null here
12004 if (proc.thread != null) {
12005 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012006 proc.thread.scheduleDestroyBackupAgent(appInfo,
12007 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012008 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012009 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012010 e.printStackTrace();
12011 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012012 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012013 }
12014 }
12015 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012016 // BROADCASTS
12017 // =========================================================
12018
Josh Bartel7f208742010-02-25 11:01:44 -060012019 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012020 List cur) {
12021 final ContentResolver resolver = mContext.getContentResolver();
12022 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12023 if (list == null) {
12024 return cur;
12025 }
12026 int N = list.size();
12027 for (int i=0; i<N; i++) {
12028 Intent intent = list.get(i);
12029 if (filter.match(resolver, intent, true, TAG) >= 0) {
12030 if (cur == null) {
12031 cur = new ArrayList<Intent>();
12032 }
12033 cur.add(intent);
12034 }
12035 }
12036 return cur;
12037 }
12038
Christopher Tatef46723b2012-01-26 14:19:24 -080012039 boolean isPendingBroadcastProcessLocked(int pid) {
12040 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12041 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012043
Christopher Tatef46723b2012-01-26 14:19:24 -080012044 void skipPendingBroadcastLocked(int pid) {
12045 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12046 for (BroadcastQueue queue : mBroadcastQueues) {
12047 queue.skipPendingBroadcastLocked(pid);
12048 }
12049 }
12050
12051 // The app just attached; send any pending broadcasts that it should receive
12052 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12053 boolean didSomething = false;
12054 for (BroadcastQueue queue : mBroadcastQueues) {
12055 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012056 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012057 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012058 }
12059
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012060 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012061 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012062 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012063 synchronized(this) {
12064 ProcessRecord callerApp = null;
12065 if (caller != null) {
12066 callerApp = getRecordForAppLocked(caller);
12067 if (callerApp == null) {
12068 throw new SecurityException(
12069 "Unable to find app for caller " + caller
12070 + " (pid=" + Binder.getCallingPid()
12071 + ") when registering receiver " + receiver);
12072 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012073 if (callerApp.info.uid != Process.SYSTEM_UID &&
12074 !callerApp.pkgList.contains(callerPackage)) {
12075 throw new SecurityException("Given caller package " + callerPackage
12076 + " is not running in process " + callerApp);
12077 }
12078 } else {
12079 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012080 }
12081
12082 List allSticky = null;
12083
12084 // Look for any matching sticky broadcasts...
12085 Iterator actions = filter.actionsIterator();
12086 if (actions != null) {
12087 while (actions.hasNext()) {
12088 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012089 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012090 }
12091 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012092 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012093 }
12094
12095 // The first sticky in the list is returned directly back to
12096 // the client.
12097 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12098
Joe Onorato8a9b2202010-02-26 18:56:32 -080012099 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012100 + ": " + sticky);
12101
12102 if (receiver == null) {
12103 return sticky;
12104 }
12105
12106 ReceiverList rl
12107 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12108 if (rl == null) {
12109 rl = new ReceiverList(this, callerApp,
12110 Binder.getCallingPid(),
12111 Binder.getCallingUid(), receiver);
12112 if (rl.app != null) {
12113 rl.app.receivers.add(rl);
12114 } else {
12115 try {
12116 receiver.asBinder().linkToDeath(rl, 0);
12117 } catch (RemoteException e) {
12118 return sticky;
12119 }
12120 rl.linkedToDeath = true;
12121 }
12122 mRegisteredReceivers.put(receiver.asBinder(), rl);
12123 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012124 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012125 rl.add(bf);
12126 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012127 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012128 }
12129 mReceiverResolver.addFilter(bf);
12130
12131 // Enqueue broadcasts for all existing stickies that match
12132 // this filter.
12133 if (allSticky != null) {
12134 ArrayList receivers = new ArrayList();
12135 receivers.add(bf);
12136
12137 int N = allSticky.size();
12138 for (int i=0; i<N; i++) {
12139 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012140 BroadcastQueue queue = broadcastQueueForIntent(intent);
12141 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012142 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012143 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012144 queue.enqueueParallelBroadcastLocked(r);
12145 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012146 }
12147 }
12148
12149 return sticky;
12150 }
12151 }
12152
12153 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012154 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012155
Christopher Tatef46723b2012-01-26 14:19:24 -080012156 final long origId = Binder.clearCallingIdentity();
12157 try {
12158 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012159
Christopher Tatef46723b2012-01-26 14:19:24 -080012160 synchronized(this) {
12161 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012162 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012163 if (rl != null) {
12164 if (rl.curBroadcast != null) {
12165 BroadcastRecord r = rl.curBroadcast;
12166 final boolean doNext = finishReceiverLocked(
12167 receiver.asBinder(), r.resultCode, r.resultData,
12168 r.resultExtras, r.resultAbort, true);
12169 if (doNext) {
12170 doTrim = true;
12171 r.queue.processNextBroadcast(false);
12172 }
12173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012174
Christopher Tatef46723b2012-01-26 14:19:24 -080012175 if (rl.app != null) {
12176 rl.app.receivers.remove(rl);
12177 }
12178 removeReceiverLocked(rl);
12179 if (rl.linkedToDeath) {
12180 rl.linkedToDeath = false;
12181 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012183 }
12184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012185
Christopher Tatef46723b2012-01-26 14:19:24 -080012186 // If we actually concluded any broadcasts, we might now be able
12187 // to trim the recipients' apps from our working set
12188 if (doTrim) {
12189 trimApplications();
12190 return;
12191 }
12192
12193 } finally {
12194 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012196 }
12197
12198 void removeReceiverLocked(ReceiverList rl) {
12199 mRegisteredReceivers.remove(rl.receiver.asBinder());
12200 int N = rl.size();
12201 for (int i=0; i<N; i++) {
12202 mReceiverResolver.removeFilter(rl.get(i));
12203 }
12204 }
12205
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012206 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12207 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12208 ProcessRecord r = mLruProcesses.get(i);
12209 if (r.thread != null) {
12210 try {
12211 r.thread.dispatchPackageBroadcast(cmd, packages);
12212 } catch (RemoteException ex) {
12213 }
12214 }
12215 }
12216 }
12217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012218 private final int broadcastIntentLocked(ProcessRecord callerApp,
12219 String callerPackage, Intent intent, String resolvedType,
12220 IIntentReceiver resultTo, int resultCode, String resultData,
12221 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012222 boolean ordered, boolean sticky, int callingPid, int callingUid,
12223 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012224 intent = new Intent(intent);
12225
Dianne Hackborne7f97212011-02-24 14:40:20 -080012226 // By default broadcasts do not go to stopped apps.
12227 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12228
Joe Onorato8a9b2202010-02-26 18:56:32 -080012229 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012230 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12231 + " ordered=" + ordered);
12232 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012233 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012234 }
12235
12236 // Handle special intents: if this broadcast is from the package
12237 // manager about a package being removed, we need to remove all of
12238 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012239 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012240 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012241 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12242 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012243 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012244 || uidRemoved) {
12245 if (checkComponentPermission(
12246 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012247 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012248 == PackageManager.PERMISSION_GRANTED) {
12249 if (uidRemoved) {
12250 final Bundle intentExtras = intent.getExtras();
12251 final int uid = intentExtras != null
12252 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12253 if (uid >= 0) {
12254 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12255 synchronized (bs) {
12256 bs.removeUidStatsLocked(uid);
12257 }
12258 }
12259 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012260 // If resources are unvailble just force stop all
12261 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012262 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012263 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12264 if (list != null && (list.length > 0)) {
12265 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070012266 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012267 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012268 sendPackageBroadcastLocked(
12269 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012270 }
12271 } else {
12272 Uri data = intent.getData();
12273 String ssp;
12274 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12275 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12276 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070012277 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012278 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012279 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012280 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12281 new String[] {ssp});
12282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012283 }
12284 }
12285 }
12286 } else {
12287 String msg = "Permission Denial: " + intent.getAction()
12288 + " broadcast from " + callerPackage + " (pid=" + callingPid
12289 + ", uid=" + callingUid + ")"
12290 + " requires "
12291 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012292 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012293 throw new SecurityException(msg);
12294 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012295
12296 // Special case for adding a package: by default turn on compatibility
12297 // mode.
12298 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012299 Uri data = intent.getData();
12300 String ssp;
12301 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12302 mCompatModePackages.handlePackageAddedLocked(ssp,
12303 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012305 }
12306
12307 /*
12308 * If this is the time zone changed action, queue up a message that will reset the timezone
12309 * of all currently running processes. This message will get queued up before the broadcast
12310 * happens.
12311 */
12312 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12313 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12314 }
12315
Robert Greenwalt03595d02010-11-02 14:08:23 -070012316 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12317 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12318 }
12319
Robert Greenwalt434203a2010-10-11 16:00:27 -070012320 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12321 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12322 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12323 }
12324
Dianne Hackborn854060af2009-07-09 18:14:31 -070012325 /*
12326 * Prevent non-system code (defined here to be non-persistent
12327 * processes) from sending protected broadcasts.
12328 */
12329 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12330 || callingUid == Process.SHELL_UID || callingUid == 0) {
12331 // Always okay.
12332 } else if (callerApp == null || !callerApp.persistent) {
12333 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012334 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012335 intent.getAction())) {
12336 String msg = "Permission Denial: not allowed to send broadcast "
12337 + intent.getAction() + " from pid="
12338 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012339 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012340 throw new SecurityException(msg);
12341 }
12342 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012343 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012344 return BROADCAST_SUCCESS;
12345 }
12346 }
12347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012348 // Add to the sticky list if requested.
12349 if (sticky) {
12350 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12351 callingPid, callingUid)
12352 != PackageManager.PERMISSION_GRANTED) {
12353 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12354 + callingPid + ", uid=" + callingUid
12355 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012356 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012357 throw new SecurityException(msg);
12358 }
12359 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012360 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012361 + " and enforce permission " + requiredPermission);
12362 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
12363 }
12364 if (intent.getComponent() != null) {
12365 throw new SecurityException(
12366 "Sticky broadcasts can't target a specific component");
12367 }
12368 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12369 if (list == null) {
12370 list = new ArrayList<Intent>();
12371 mStickyBroadcasts.put(intent.getAction(), list);
12372 }
12373 int N = list.size();
12374 int i;
12375 for (i=0; i<N; i++) {
12376 if (intent.filterEquals(list.get(i))) {
12377 // This sticky already exists, replace it.
12378 list.set(i, new Intent(intent));
12379 break;
12380 }
12381 }
12382 if (i >= N) {
12383 list.add(new Intent(intent));
12384 }
12385 }
12386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012387 // Figure out who all will receive this broadcast.
12388 List receivers = null;
12389 List<BroadcastFilter> registeredReceivers = null;
12390 try {
12391 if (intent.getComponent() != null) {
12392 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012393 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012394 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012395 if (ai != null) {
12396 receivers = new ArrayList();
12397 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012398 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012399 receivers.add(ri);
12400 }
12401 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070012402 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012403 // Need to resolve the intent to interested receivers...
12404 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12405 == 0) {
12406 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012407 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012408 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012409 }
Mihai Preda074edef2009-05-18 17:13:31 +020012410 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012411 }
12412 } catch (RemoteException ex) {
12413 // pm is in same process, this will never happen.
12414 }
12415
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012416 final boolean replacePending =
12417 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12418
Joe Onorato8a9b2202010-02-26 18:56:32 -080012419 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012420 + " replacePending=" + replacePending);
12421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012422 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12423 if (!ordered && NR > 0) {
12424 // If we are not serializing this broadcast, then send the
12425 // registered receivers separately so they don't wait for the
12426 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012427 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12428 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012429 callerPackage, callingPid, callingUid, requiredPermission,
12430 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012431 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012432 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012433 TAG, "Enqueueing parallel broadcast " + r);
12434 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012435 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012436 queue.enqueueParallelBroadcastLocked(r);
12437 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439 registeredReceivers = null;
12440 NR = 0;
12441 }
12442
12443 // Merge into one list.
12444 int ir = 0;
12445 if (receivers != null) {
12446 // A special case for PACKAGE_ADDED: do not allow the package
12447 // being added to see this broadcast. This prevents them from
12448 // using this as a back door to get run as soon as they are
12449 // installed. Maybe in the future we want to have a special install
12450 // broadcast or such for apps, but we'd like to deliberately make
12451 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012452 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012453 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12454 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12455 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012456 Uri data = intent.getData();
12457 if (data != null) {
12458 String pkgName = data.getSchemeSpecificPart();
12459 if (pkgName != null) {
12460 skipPackages = new String[] { pkgName };
12461 }
12462 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012463 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012464 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012465 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012466 if (skipPackages != null && (skipPackages.length > 0)) {
12467 for (String skipPackage : skipPackages) {
12468 if (skipPackage != null) {
12469 int NT = receivers.size();
12470 for (int it=0; it<NT; it++) {
12471 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12472 if (curt.activityInfo.packageName.equals(skipPackage)) {
12473 receivers.remove(it);
12474 it--;
12475 NT--;
12476 }
12477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012478 }
12479 }
12480 }
12481
12482 int NT = receivers != null ? receivers.size() : 0;
12483 int it = 0;
12484 ResolveInfo curt = null;
12485 BroadcastFilter curr = null;
12486 while (it < NT && ir < NR) {
12487 if (curt == null) {
12488 curt = (ResolveInfo)receivers.get(it);
12489 }
12490 if (curr == null) {
12491 curr = registeredReceivers.get(ir);
12492 }
12493 if (curr.getPriority() >= curt.priority) {
12494 // Insert this broadcast record into the final list.
12495 receivers.add(it, curr);
12496 ir++;
12497 curr = null;
12498 it++;
12499 NT++;
12500 } else {
12501 // Skip to the next ResolveInfo in the final list.
12502 it++;
12503 curt = null;
12504 }
12505 }
12506 }
12507 while (ir < NR) {
12508 if (receivers == null) {
12509 receivers = new ArrayList();
12510 }
12511 receivers.add(registeredReceivers.get(ir));
12512 ir++;
12513 }
12514
12515 if ((receivers != null && receivers.size() > 0)
12516 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012517 BroadcastQueue queue = broadcastQueueForIntent(intent);
12518 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012519 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012520 receivers, resultTo, resultCode, resultData, map, ordered,
12521 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012522 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012523 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012524 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012525 if (DEBUG_BROADCAST) {
12526 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012527 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012528 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012529 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012530 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012531 queue.enqueueOrderedBroadcastLocked(r);
12532 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012534 }
12535
12536 return BROADCAST_SUCCESS;
12537 }
12538
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012539 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012540 // Refuse possible leaked file descriptors
12541 if (intent != null && intent.hasFileDescriptors() == true) {
12542 throw new IllegalArgumentException("File descriptors passed in Intent");
12543 }
12544
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012545 int flags = intent.getFlags();
12546
12547 if (!mProcessesReady) {
12548 // if the caller really truly claims to know what they're doing, go
12549 // ahead and allow the broadcast without launching any receivers
12550 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12551 intent = new Intent(intent);
12552 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12553 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12554 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12555 + " before boot completion");
12556 throw new IllegalStateException("Cannot broadcast before boot completed");
12557 }
12558 }
12559
12560 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12561 throw new IllegalArgumentException(
12562 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12563 }
12564
12565 return intent;
12566 }
12567
12568 public final int broadcastIntent(IApplicationThread caller,
12569 Intent intent, String resolvedType, IIntentReceiver resultTo,
12570 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012571 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012572 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012573 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012574 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012576 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12577 final int callingPid = Binder.getCallingPid();
12578 final int callingUid = Binder.getCallingUid();
12579 final long origId = Binder.clearCallingIdentity();
12580 int res = broadcastIntentLocked(callerApp,
12581 callerApp != null ? callerApp.info.packageName : null,
12582 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012583 resultCode, resultData, map, requiredPermission, serialized, sticky,
12584 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585 Binder.restoreCallingIdentity(origId);
12586 return res;
12587 }
12588 }
12589
12590 int broadcastIntentInPackage(String packageName, int uid,
12591 Intent intent, String resolvedType, IIntentReceiver resultTo,
12592 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012593 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012594 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012595 intent = verifyBroadcastLocked(intent);
12596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012597 final long origId = Binder.clearCallingIdentity();
12598 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12599 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012600 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012601 Binder.restoreCallingIdentity(origId);
12602 return res;
12603 }
12604 }
12605
Amith Yamasani742a6712011-05-04 14:49:28 -070012606 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12607 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012608 // Refuse possible leaked file descriptors
12609 if (intent != null && intent.hasFileDescriptors() == true) {
12610 throw new IllegalArgumentException("File descriptors passed in Intent");
12611 }
12612
12613 synchronized(this) {
12614 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12615 != PackageManager.PERMISSION_GRANTED) {
12616 String msg = "Permission Denial: unbroadcastIntent() from pid="
12617 + Binder.getCallingPid()
12618 + ", uid=" + Binder.getCallingUid()
12619 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012620 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012621 throw new SecurityException(msg);
12622 }
12623 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12624 if (list != null) {
12625 int N = list.size();
12626 int i;
12627 for (i=0; i<N; i++) {
12628 if (intent.filterEquals(list.get(i))) {
12629 list.remove(i);
12630 break;
12631 }
12632 }
12633 }
12634 }
12635 }
12636
12637 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12638 String resultData, Bundle resultExtras, boolean resultAbort,
12639 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012640 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12641 if (r == null) {
12642 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012643 return false;
12644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012645
Christopher Tatef46723b2012-01-26 14:19:24 -080012646 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12647 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012648 }
12649
12650 public void finishReceiver(IBinder who, int resultCode, String resultData,
12651 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012652 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012653
12654 // Refuse possible leaked file descriptors
12655 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12656 throw new IllegalArgumentException("File descriptors passed in Bundle");
12657 }
12658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012659 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012660 try {
12661 boolean doNext = false;
12662 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012663
Christopher Tatef46723b2012-01-26 14:19:24 -080012664 synchronized(this) {
12665 r = broadcastRecordForReceiverLocked(who);
12666 if (r != null) {
12667 doNext = r.queue.finishReceiverLocked(r, resultCode,
12668 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012670 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012671
Christopher Tatef46723b2012-01-26 14:19:24 -080012672 if (doNext) {
12673 r.queue.processNextBroadcast(false);
12674 }
12675 trimApplications();
12676 } finally {
12677 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012681 // =========================================================
12682 // INSTRUMENTATION
12683 // =========================================================
12684
12685 public boolean startInstrumentation(ComponentName className,
12686 String profileFile, int flags, Bundle arguments,
12687 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012688 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012689 // Refuse possible leaked file descriptors
12690 if (arguments != null && arguments.hasFileDescriptors()) {
12691 throw new IllegalArgumentException("File descriptors passed in Bundle");
12692 }
12693
12694 synchronized(this) {
12695 InstrumentationInfo ii = null;
12696 ApplicationInfo ai = null;
12697 try {
12698 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012699 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012700 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012701 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012702 } catch (PackageManager.NameNotFoundException e) {
12703 }
12704 if (ii == null) {
12705 reportStartInstrumentationFailure(watcher, className,
12706 "Unable to find instrumentation info for: " + className);
12707 return false;
12708 }
12709 if (ai == null) {
12710 reportStartInstrumentationFailure(watcher, className,
12711 "Unable to find instrumentation target package: " + ii.targetPackage);
12712 return false;
12713 }
12714
12715 int match = mContext.getPackageManager().checkSignatures(
12716 ii.targetPackage, ii.packageName);
12717 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12718 String msg = "Permission Denial: starting instrumentation "
12719 + className + " from pid="
12720 + Binder.getCallingPid()
12721 + ", uid=" + Binder.getCallingPid()
12722 + " not allowed because package " + ii.packageName
12723 + " does not have a signature matching the target "
12724 + ii.targetPackage;
12725 reportStartInstrumentationFailure(watcher, className, msg);
12726 throw new SecurityException(msg);
12727 }
12728
12729 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012730 // Instrumentation can kill and relaunch even persistent processes
12731 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012732 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012733 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012734 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012735 app.instrumentationProfileFile = profileFile;
12736 app.instrumentationArguments = arguments;
12737 app.instrumentationWatcher = watcher;
12738 app.instrumentationResultClass = className;
12739 Binder.restoreCallingIdentity(origId);
12740 }
12741
12742 return true;
12743 }
12744
12745 /**
12746 * Report errors that occur while attempting to start Instrumentation. Always writes the
12747 * error to the logs, but if somebody is watching, send the report there too. This enables
12748 * the "am" command to report errors with more information.
12749 *
12750 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12751 * @param cn The component name of the instrumentation.
12752 * @param report The error report.
12753 */
12754 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12755 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012756 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012757 try {
12758 if (watcher != null) {
12759 Bundle results = new Bundle();
12760 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12761 results.putString("Error", report);
12762 watcher.instrumentationStatus(cn, -1, results);
12763 }
12764 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012765 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012766 }
12767 }
12768
12769 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12770 if (app.instrumentationWatcher != null) {
12771 try {
12772 // NOTE: IInstrumentationWatcher *must* be oneway here
12773 app.instrumentationWatcher.instrumentationFinished(
12774 app.instrumentationClass,
12775 resultCode,
12776 results);
12777 } catch (RemoteException e) {
12778 }
12779 }
12780 app.instrumentationWatcher = null;
12781 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012782 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012783 app.instrumentationProfileFile = null;
12784 app.instrumentationArguments = null;
12785
Christopher Tate3dacd842011-08-19 14:56:15 -070012786 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012787 }
12788
12789 public void finishInstrumentation(IApplicationThread target,
12790 int resultCode, Bundle results) {
12791 // Refuse possible leaked file descriptors
12792 if (results != null && results.hasFileDescriptors()) {
12793 throw new IllegalArgumentException("File descriptors passed in Intent");
12794 }
12795
12796 synchronized(this) {
12797 ProcessRecord app = getRecordForAppLocked(target);
12798 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012799 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012800 return;
12801 }
12802 final long origId = Binder.clearCallingIdentity();
12803 finishInstrumentationLocked(app, resultCode, results);
12804 Binder.restoreCallingIdentity(origId);
12805 }
12806 }
12807
12808 // =========================================================
12809 // CONFIGURATION
12810 // =========================================================
12811
12812 public ConfigurationInfo getDeviceConfigurationInfo() {
12813 ConfigurationInfo config = new ConfigurationInfo();
12814 synchronized (this) {
12815 config.reqTouchScreen = mConfiguration.touchscreen;
12816 config.reqKeyboardType = mConfiguration.keyboard;
12817 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012818 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12819 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012820 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12821 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012822 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12823 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012824 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12825 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012826 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012827 }
12828 return config;
12829 }
12830
12831 public Configuration getConfiguration() {
12832 Configuration ci;
12833 synchronized(this) {
12834 ci = new Configuration(mConfiguration);
12835 }
12836 return ci;
12837 }
12838
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012839 public void updatePersistentConfiguration(Configuration values) {
12840 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12841 "updateConfiguration()");
12842 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12843 "updateConfiguration()");
12844 if (values == null) {
12845 throw new NullPointerException("Configuration must not be null");
12846 }
12847
12848 synchronized(this) {
12849 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012850 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012851 Binder.restoreCallingIdentity(origId);
12852 }
12853 }
12854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012855 public void updateConfiguration(Configuration values) {
12856 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12857 "updateConfiguration()");
12858
12859 synchronized(this) {
12860 if (values == null && mWindowManager != null) {
12861 // sentinel: fetch the current configuration from the window manager
12862 values = mWindowManager.computeNewConfiguration();
12863 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012864
12865 if (mWindowManager != null) {
12866 mProcessList.applyDisplaySize(mWindowManager);
12867 }
12868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012870 if (values != null) {
12871 Settings.System.clearConfiguration(values);
12872 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012873 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012874 Binder.restoreCallingIdentity(origId);
12875 }
12876 }
12877
12878 /**
12879 * Do either or both things: (1) change the current configuration, and (2)
12880 * make sure the given activity is running with the (now) current
12881 * configuration. Returns true if the activity has been left running, or
12882 * false if <var>starting</var> is being destroyed to match the new
12883 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012884 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012885 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012886 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012887 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012888 // do nothing if we are headless
12889 if (mHeadless) return true;
12890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012891 int changes = 0;
12892
12893 boolean kept = true;
12894
12895 if (values != null) {
12896 Configuration newConfig = new Configuration(mConfiguration);
12897 changes = newConfig.updateFrom(values);
12898 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012899 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012900 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012901 }
12902
Doug Zongker2bec3d42009-12-04 12:52:44 -080012903 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012904
Dianne Hackborn813075a62011-11-14 17:45:19 -080012905 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012906 saveLocaleLocked(values.locale,
12907 !values.locale.equals(mConfiguration.locale),
12908 values.userSetLocale);
12909 }
12910
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012911 mConfigurationSeq++;
12912 if (mConfigurationSeq <= 0) {
12913 mConfigurationSeq = 1;
12914 }
12915 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012916 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012917 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012918
12919 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012920
12921 // TODO: If our config changes, should we auto dismiss any currently
12922 // showing dialogs?
12923 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012924
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012925 AttributeCache ac = AttributeCache.instance();
12926 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012927 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012929
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012930 // Make sure all resources in our process are updated
12931 // right now, so that anyone who is going to retrieve
12932 // resource values after we return will be sure to get
12933 // the new ones. This is especially important during
12934 // boot, where the first config change needs to guarantee
12935 // all resources have that config before following boot
12936 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012937 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012938
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012939 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012940 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012941 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012942 mHandler.sendMessage(msg);
12943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012944
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012945 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12946 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012947 try {
12948 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012949 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012950 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012951 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012952 }
12953 } catch (Exception e) {
12954 }
12955 }
12956 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012957 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12958 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070012960 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012961 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12962 broadcastIntentLocked(null, null,
12963 new Intent(Intent.ACTION_LOCALE_CHANGED),
12964 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070012965 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012967 }
12968 }
12969
12970 if (changes != 0 && starting == null) {
12971 // If the configuration changed, and the caller is not already
12972 // in the process of starting an activity, then find the top
12973 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012974 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012975 }
12976
12977 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012978 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012979 // And we need to make sure at this point that all other activities
12980 // are made visible with the correct configuration.
12981 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012982 }
12983
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012984 if (values != null && mWindowManager != null) {
12985 mWindowManager.setNewConfiguration(mConfiguration);
12986 }
12987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012988 return kept;
12989 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012990
12991 /**
12992 * Decide based on the configuration whether we should shouw the ANR,
12993 * crash, etc dialogs. The idea is that if there is no affordnace to
12994 * press the on-screen buttons, we shouldn't show the dialog.
12995 *
12996 * A thought: SystemUI might also want to get told about this, the Power
12997 * dialog / global actions also might want different behaviors.
12998 */
12999 private static final boolean shouldShowDialogs(Configuration config) {
13000 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13001 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013003
13004 /**
13005 * Save the locale. You must be inside a synchronized (this) block.
13006 */
13007 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13008 if(isDiff) {
13009 SystemProperties.set("user.language", l.getLanguage());
13010 SystemProperties.set("user.region", l.getCountry());
13011 }
13012
13013 if(isPersist) {
13014 SystemProperties.set("persist.sys.language", l.getLanguage());
13015 SystemProperties.set("persist.sys.country", l.getCountry());
13016 SystemProperties.set("persist.sys.localevar", l.getVariant());
13017 }
13018 }
13019
13020 // =========================================================
13021 // LIFETIME MANAGEMENT
13022 // =========================================================
13023
Christopher Tatef46723b2012-01-26 14:19:24 -080013024 // Returns which broadcast queue the app is the current [or imminent] receiver
13025 // on, or 'null' if the app is not an active broadcast recipient.
13026 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13027 BroadcastRecord r = app.curReceiver;
13028 if (r != null) {
13029 return r.queue;
13030 }
13031
13032 // It's not the current receiver, but it might be starting up to become one
13033 synchronized (this) {
13034 for (BroadcastQueue queue : mBroadcastQueues) {
13035 r = queue.mPendingBroadcast;
13036 if (r != null && r.curApp == app) {
13037 // found it; report which queue it's in
13038 return queue;
13039 }
13040 }
13041 }
13042
13043 return null;
13044 }
13045
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013046 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013047 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013048 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013049 // This adjustment has already been computed. If we are calling
13050 // from the top, we may have already computed our adjustment with
13051 // an earlier hidden adjustment that isn't really for us... if
13052 // so, use the new hidden adjustment.
13053 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013054 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013055 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013056 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013057 }
13058
13059 if (app.thread == null) {
13060 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013061 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013062 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063 }
13064
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013065 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13066 app.adjSource = null;
13067 app.adjTarget = null;
13068 app.empty = false;
13069 app.hidden = false;
13070
13071 final int activitiesSize = app.activities.size();
13072
Dianne Hackborn7d608422011-08-07 16:24:18 -070013073 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013074 // The max adjustment doesn't allow this app to be anything
13075 // below foreground, so it is not worth doing work for it.
13076 app.adjType = "fixed";
13077 app.adjSeq = mAdjSeq;
13078 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013079 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013080 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013081 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013082 // System process can do UI, and when they do we want to have
13083 // them trim their memory after the user leaves the UI. To
13084 // facilitate this, here we need to determine whether or not it
13085 // is currently showing UI.
13086 app.systemNoUi = true;
13087 if (app == TOP_APP) {
13088 app.systemNoUi = false;
13089 } else if (activitiesSize > 0) {
13090 for (int j = 0; j < activitiesSize; j++) {
13091 final ActivityRecord r = app.activities.get(j);
13092 if (r.visible) {
13093 app.systemNoUi = false;
13094 break;
13095 }
13096 }
13097 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013098 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013099 }
13100
13101 final boolean hadForegroundActivities = app.foregroundActivities;
13102
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013103 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013104 app.keeping = false;
13105 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013106
The Android Open Source Project4df24232009-03-05 14:34:35 -080013107 // Determine the importance of the process, starting with most
13108 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013109 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013110 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013111 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013112 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013113 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013114 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013115 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013116 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013117 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013118 } else if (app.instrumentationClass != null) {
13119 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013120 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013121 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013122 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013123 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013124 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013125 // counts as being in the foreground for OOM killer purposes.
13126 // It's placed in a sched group based on the nature of the
13127 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013128 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013129 schedGroup = (queue == mFgBroadcastQueue)
13130 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013131 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013132 } else if (app.executingServices.size() > 0) {
13133 // An app that is currently executing a service callback also
13134 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013135 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013136 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013137 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013138 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013139 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013140 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013141 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013142 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013143 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013144 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013145 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013146 // A very not-needed process. If this is lower in the lru list,
13147 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013148 adj = hiddenAdj;
13149 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013150 app.hidden = true;
13151 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013152 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013153 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013154
13155 // Examine all activities if not already foreground.
13156 if (!app.foregroundActivities && activitiesSize > 0) {
13157 for (int j = 0; j < activitiesSize; j++) {
13158 final ActivityRecord r = app.activities.get(j);
13159 if (r.visible) {
13160 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013161 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13162 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013163 app.adjType = "visible";
13164 }
13165 schedGroup = Process.THREAD_GROUP_DEFAULT;
13166 app.hidden = false;
13167 app.foregroundActivities = true;
13168 break;
13169 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13170 || r.state == ActivityState.STOPPING) {
13171 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013172 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13173 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013174 app.adjType = "stopping";
13175 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013176 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013177 app.foregroundActivities = true;
13178 }
13179 }
13180 }
13181
Dianne Hackborn7d608422011-08-07 16:24:18 -070013182 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013183 if (app.foregroundServices) {
13184 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013185 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013186 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013187 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013188 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013189 } else if (app.forcingToForeground != null) {
13190 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013191 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013192 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013193 app.adjType = "force-foreground";
13194 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013195 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013196 }
13197 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013198
Dianne Hackborn7d608422011-08-07 16:24:18 -070013199 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013200 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013201 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013202 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013203 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013204 app.adjType = "heavy";
13205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013206
Dianne Hackborn7d608422011-08-07 16:24:18 -070013207 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013208 // This process is hosting what we currently consider to be the
13209 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013210 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013211 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013212 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013213 app.adjType = "home";
13214 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013215
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013216 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13217 && app.activities.size() > 0) {
13218 // This was the previous process that showed UI to the user.
13219 // We want to try to keep it around more aggressively, to give
13220 // a good experience around switching between two apps.
13221 adj = ProcessList.PREVIOUS_APP_ADJ;
13222 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13223 app.hidden = false;
13224 app.adjType = "previous";
13225 }
13226
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013227 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13228 + " reason=" + app.adjType);
13229
The Android Open Source Project4df24232009-03-05 14:34:35 -080013230 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013231 // there are applications dependent on our services or providers, but
13232 // this gives us a baseline and makes sure we don't get into an
13233 // infinite recursion.
13234 app.adjSeq = mAdjSeq;
13235 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013236
Christopher Tate6fa95972009-06-05 18:43:55 -070013237 if (mBackupTarget != null && app == mBackupTarget.app) {
13238 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013239 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013240 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013241 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013242 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013243 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013244 }
13245 }
13246
Dianne Hackborn7d608422011-08-07 16:24:18 -070013247 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013248 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013249 final long now = SystemClock.uptimeMillis();
13250 // This process is more important if the top activity is
13251 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013252 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013253 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013254 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013255 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013256 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013257 // If this process has shown some UI, let it immediately
13258 // go to the LRU list because it may be pretty heavy with
13259 // UI stuff. We'll tag it with a label just to help
13260 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013261 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013262 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013263 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013264 } else {
13265 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13266 // This service has seen some activity within
13267 // recent memory, so we will keep its process ahead
13268 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013269 if (adj > ProcessList.SERVICE_ADJ) {
13270 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013271 app.adjType = "started-services";
13272 app.hidden = false;
13273 }
13274 }
13275 // If we have let the service slide into the background
13276 // state, still have some text describing what it is doing
13277 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013278 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013279 app.adjType = "started-bg-services";
13280 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013281 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013282 // Don't kill this process because it is doing work; it
13283 // has said it is doing work.
13284 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013285 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013286 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013287 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013288 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013289 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013290 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013291 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013292 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013293 // XXX should compute this based on the max of
13294 // all connected clients.
13295 ConnectionRecord cr = clist.get(i);
13296 if (cr.binding.client == app) {
13297 // Binding to ourself is not interesting.
13298 continue;
13299 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013300 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013301 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013302 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013303 int myHiddenAdj = hiddenAdj;
13304 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013305 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013306 myHiddenAdj = client.hiddenAdj;
13307 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013308 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013309 }
13310 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013311 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013312 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013313 String adjType = null;
13314 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13315 // Not doing bind OOM management, so treat
13316 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013317 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013318 // If this process has shown some UI, let it immediately
13319 // go to the LRU list because it may be pretty heavy with
13320 // UI stuff. We'll tag it with a label just to help
13321 // debug and understand what is going on.
13322 if (adj > clientAdj) {
13323 adjType = "bound-bg-ui-services";
13324 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013325 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013326 clientAdj = adj;
13327 } else {
13328 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13329 // This service has not seen activity within
13330 // recent memory, so allow it to drop to the
13331 // LRU list if there is no other reason to keep
13332 // it around. We'll also tag it with a label just
13333 // to help debug and undertand what is going on.
13334 if (adj > clientAdj) {
13335 adjType = "bound-bg-services";
13336 }
13337 clientAdj = adj;
13338 }
13339 }
13340 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013341 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013342 // If this process has recently shown UI, and
13343 // the process that is binding to it is less
13344 // important than being visible, then we don't
13345 // care about the binding as much as we care
13346 // about letting this process get into the LRU
13347 // list to be killed and restarted if needed for
13348 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013349 if (app.hasShownUi && app != mHomeProcess
13350 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013351 adjType = "bound-bg-ui-services";
13352 } else {
13353 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13354 |Context.BIND_IMPORTANT)) != 0) {
13355 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013356 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13357 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13358 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13359 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13360 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013361 adj = clientAdj;
13362 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013363 app.pendingUiClean = true;
13364 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13365 adj = ProcessList.VISIBLE_APP_ADJ;
13366 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013367 }
13368 if (!client.hidden) {
13369 app.hidden = false;
13370 }
13371 if (client.keeping) {
13372 app.keeping = true;
13373 }
13374 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013375 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013376 }
13377 if (adjType != null) {
13378 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013379 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13380 .REASON_SERVICE_IN_USE;
13381 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013382 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013383 app.adjTarget = s.name;
13384 }
13385 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13386 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13387 schedGroup = Process.THREAD_GROUP_DEFAULT;
13388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013389 }
13390 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013391 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13392 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013393 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013394 (a.visible || a.state == ActivityState.RESUMED
13395 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013396 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013397 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13398 schedGroup = Process.THREAD_GROUP_DEFAULT;
13399 }
13400 app.hidden = false;
13401 app.adjType = "service";
13402 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13403 .REASON_SERVICE_IN_USE;
13404 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013405 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013406 app.adjTarget = s.name;
13407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013409 }
13410 }
13411 }
13412 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013413
Dianne Hackborn287952c2010-09-22 22:34:31 -070013414 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013415 // would like to avoid killing it unless it would prevent the current
13416 // application from running. By default we put the process in
13417 // with the rest of the background processes; as we scan through
13418 // its services we may bump it up from there.
13419 if (adj > hiddenAdj) {
13420 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013421 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013422 app.adjType = "bg-services";
13423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013424 }
13425
Dianne Hackborn7d608422011-08-07 16:24:18 -070013426 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013427 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013428 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013429 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013430 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013431 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013432 if (cpr.clients.size() != 0) {
13433 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013434 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013435 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013436 if (client == app) {
13437 // Being our own client is not interesting.
13438 continue;
13439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013440 int myHiddenAdj = hiddenAdj;
13441 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013442 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013443 myHiddenAdj = client.hiddenAdj;
13444 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013445 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013446 }
13447 }
13448 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013449 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013450 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013451 if (app.hasShownUi && app != mHomeProcess
13452 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013453 app.adjType = "bg-ui-provider";
13454 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013455 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13456 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013457 app.adjType = "provider";
13458 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013459 if (!client.hidden) {
13460 app.hidden = false;
13461 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013462 if (client.keeping) {
13463 app.keeping = true;
13464 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013465 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13466 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013467 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013468 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013469 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013470 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013471 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13472 schedGroup = Process.THREAD_GROUP_DEFAULT;
13473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013474 }
13475 }
13476 // If the provider has external (non-framework) process
13477 // dependencies, ensure that its adjustment is at least
13478 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013479 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013480 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13481 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013482 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013483 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013484 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013485 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013486 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013487 }
13488 }
13489 }
13490 }
13491
13492 app.curRawAdj = adj;
13493
Joe Onorato8a9b2202010-02-26 18:56:32 -080013494 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013495 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13496 if (adj > app.maxAdj) {
13497 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013498 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013499 schedGroup = Process.THREAD_GROUP_DEFAULT;
13500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013501 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013502 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013503 app.keeping = true;
13504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013505
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013506 if (app.hasAboveClient) {
13507 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13508 // then we need to drop its adjustment to be lower than the service's
13509 // in order to honor the request. We want to drop it by one adjustment
13510 // level... but there is special meaning applied to various levels so
13511 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013512 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013513 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013514 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13515 adj = ProcessList.VISIBLE_APP_ADJ;
13516 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13517 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13518 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13519 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013520 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013521 adj++;
13522 }
13523 }
13524
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013525 if (adj == ProcessList.SERVICE_ADJ) {
13526 if (doingAll) {
13527 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13528 mNewNumServiceProcs++;
13529 }
13530 if (app.serviceb) {
13531 adj = ProcessList.SERVICE_B_ADJ;
13532 }
13533 } else {
13534 app.serviceb = false;
13535 }
13536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013537 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013538 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013539
13540 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013541 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13542 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013543 }
13544
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013545 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013546 }
13547
13548 /**
13549 * Ask a given process to GC right now.
13550 */
13551 final void performAppGcLocked(ProcessRecord app) {
13552 try {
13553 app.lastRequestedGc = SystemClock.uptimeMillis();
13554 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013555 if (app.reportLowMemory) {
13556 app.reportLowMemory = false;
13557 app.thread.scheduleLowMemory();
13558 } else {
13559 app.thread.processInBackground();
13560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013561 }
13562 } catch (Exception e) {
13563 // whatever.
13564 }
13565 }
13566
13567 /**
13568 * Returns true if things are idle enough to perform GCs.
13569 */
Josh Bartel7f208742010-02-25 11:01:44 -060013570 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013571 boolean processingBroadcasts = false;
13572 for (BroadcastQueue q : mBroadcastQueues) {
13573 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13574 processingBroadcasts = true;
13575 }
13576 }
13577 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013578 && (mSleeping || (mMainStack.mResumedActivity != null &&
13579 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013580 }
13581
13582 /**
13583 * Perform GCs on all processes that are waiting for it, but only
13584 * if things are idle.
13585 */
13586 final void performAppGcsLocked() {
13587 final int N = mProcessesToGc.size();
13588 if (N <= 0) {
13589 return;
13590 }
Josh Bartel7f208742010-02-25 11:01:44 -060013591 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013592 while (mProcessesToGc.size() > 0) {
13593 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013594 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013595 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13596 <= SystemClock.uptimeMillis()) {
13597 // To avoid spamming the system, we will GC processes one
13598 // at a time, waiting a few seconds between each.
13599 performAppGcLocked(proc);
13600 scheduleAppGcsLocked();
13601 return;
13602 } else {
13603 // It hasn't been long enough since we last GCed this
13604 // process... put it in the list to wait for its time.
13605 addProcessToGcListLocked(proc);
13606 break;
13607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 }
13609 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013610
13611 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013612 }
13613 }
13614
13615 /**
13616 * If all looks good, perform GCs on all processes waiting for them.
13617 */
13618 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013619 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013620 performAppGcsLocked();
13621 return;
13622 }
13623 // Still not idle, wait some more.
13624 scheduleAppGcsLocked();
13625 }
13626
13627 /**
13628 * Schedule the execution of all pending app GCs.
13629 */
13630 final void scheduleAppGcsLocked() {
13631 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013632
13633 if (mProcessesToGc.size() > 0) {
13634 // Schedule a GC for the time to the next process.
13635 ProcessRecord proc = mProcessesToGc.get(0);
13636 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13637
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013638 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013639 long now = SystemClock.uptimeMillis();
13640 if (when < (now+GC_TIMEOUT)) {
13641 when = now + GC_TIMEOUT;
13642 }
13643 mHandler.sendMessageAtTime(msg, when);
13644 }
13645 }
13646
13647 /**
13648 * Add a process to the array of processes waiting to be GCed. Keeps the
13649 * list in sorted order by the last GC time. The process can't already be
13650 * on the list.
13651 */
13652 final void addProcessToGcListLocked(ProcessRecord proc) {
13653 boolean added = false;
13654 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13655 if (mProcessesToGc.get(i).lastRequestedGc <
13656 proc.lastRequestedGc) {
13657 added = true;
13658 mProcessesToGc.add(i+1, proc);
13659 break;
13660 }
13661 }
13662 if (!added) {
13663 mProcessesToGc.add(0, proc);
13664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013665 }
13666
13667 /**
13668 * Set up to ask a process to GC itself. This will either do it
13669 * immediately, or put it on the list of processes to gc the next
13670 * time things are idle.
13671 */
13672 final void scheduleAppGcLocked(ProcessRecord app) {
13673 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013674 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013675 return;
13676 }
13677 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013678 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013679 scheduleAppGcsLocked();
13680 }
13681 }
13682
Dianne Hackborn287952c2010-09-22 22:34:31 -070013683 final void checkExcessivePowerUsageLocked(boolean doKills) {
13684 updateCpuStatsNow();
13685
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013686 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013687 boolean doWakeKills = doKills;
13688 boolean doCpuKills = doKills;
13689 if (mLastPowerCheckRealtime == 0) {
13690 doWakeKills = false;
13691 }
13692 if (mLastPowerCheckUptime == 0) {
13693 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013694 }
13695 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013696 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013697 }
13698 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013699 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13700 final long curUptime = SystemClock.uptimeMillis();
13701 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13702 mLastPowerCheckRealtime = curRealtime;
13703 mLastPowerCheckUptime = curUptime;
13704 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13705 doWakeKills = false;
13706 }
13707 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13708 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013709 }
13710 int i = mLruProcesses.size();
13711 while (i > 0) {
13712 i--;
13713 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013714 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013715 long wtime;
13716 synchronized (stats) {
13717 wtime = stats.getProcessWakeTime(app.info.uid,
13718 app.pid, curRealtime);
13719 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013720 long wtimeUsed = wtime - app.lastWakeTime;
13721 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13722 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013723 StringBuilder sb = new StringBuilder(128);
13724 sb.append("Wake for ");
13725 app.toShortString(sb);
13726 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013727 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013728 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013729 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013730 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013731 sb.append((wtimeUsed*100)/realtimeSince);
13732 sb.append("%)");
13733 Slog.i(TAG, sb.toString());
13734 sb.setLength(0);
13735 sb.append("CPU for ");
13736 app.toShortString(sb);
13737 sb.append(": over ");
13738 TimeUtils.formatDuration(uptimeSince, sb);
13739 sb.append(" used ");
13740 TimeUtils.formatDuration(cputimeUsed, sb);
13741 sb.append(" (");
13742 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013743 sb.append("%)");
13744 Slog.i(TAG, sb.toString());
13745 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013746 // If a process has held a wake lock for more
13747 // than 50% of the time during this period,
13748 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013749 if (doWakeKills && realtimeSince > 0
13750 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13751 synchronized (stats) {
13752 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13753 realtimeSince, wtimeUsed);
13754 }
13755 Slog.w(TAG, "Excessive wake lock in " + app.processName
13756 + " (pid " + app.pid + "): held " + wtimeUsed
13757 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013758 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13759 app.processName, app.setAdj, "excessive wake lock");
13760 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013761 } else if (doCpuKills && uptimeSince > 0
13762 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13763 synchronized (stats) {
13764 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13765 uptimeSince, cputimeUsed);
13766 }
13767 Slog.w(TAG, "Excessive CPU in " + app.processName
13768 + " (pid " + app.pid + "): used " + cputimeUsed
13769 + " during " + uptimeSince);
13770 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13771 app.processName, app.setAdj, "excessive cpu");
13772 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013773 } else {
13774 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013775 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013776 }
13777 }
13778 }
13779 }
13780
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013781 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013782 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013783 app.hiddenAdj = hiddenAdj;
13784
13785 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013786 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013787 }
13788
Dianne Hackborn287952c2010-09-22 22:34:31 -070013789 final boolean wasKeeping = app.keeping;
13790
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013791 boolean success = true;
13792
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013793 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013794
Jeff Brown10e89712011-07-08 18:52:57 -070013795 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013796 if (false) {
13797 // Removing for now. Forcing GCs is not so useful anymore
13798 // with Dalvik, and the new memory level hint facility is
13799 // better for what we need to do these days.
13800 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
13801 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13802 // If this app is transitioning from foreground to
13803 // non-foreground, have it do a gc.
13804 scheduleAppGcLocked(app);
13805 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13806 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13807 // Likewise do a gc when an app is moving in to the
13808 // background (such as a service stopping).
13809 scheduleAppGcLocked(app);
13810 }
Jeff Brown10e89712011-07-08 18:52:57 -070013811 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013812
Jeff Brown10e89712011-07-08 18:52:57 -070013813 if (wasKeeping && !app.keeping) {
13814 // This app is no longer something we want to keep. Note
13815 // its current wake lock time to later know to kill it if
13816 // it is not behaving well.
13817 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13818 synchronized (stats) {
13819 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13820 app.pid, SystemClock.elapsedRealtime());
13821 }
13822 app.lastCpuTime = app.curCpuTime;
13823 }
13824
13825 app.setRawAdj = app.curRawAdj;
13826 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013827
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013828 if (app.curAdj != app.setAdj) {
13829 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013830 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013831 TAG, "Set " + app.pid + " " + app.processName +
13832 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013833 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013834 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013835 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013836 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013837 }
13838 }
13839 if (app.setSchedGroup != app.curSchedGroup) {
13840 app.setSchedGroup = app.curSchedGroup;
13841 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13842 "Setting process group of " + app.processName
13843 + " to " + app.curSchedGroup);
13844 if (app.waitingToKill != null &&
13845 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13846 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13847 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13848 app.processName, app.setAdj, app.waitingToKill);
13849 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013850 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013851 } else {
13852 if (true) {
13853 long oldId = Binder.clearCallingIdentity();
13854 try {
13855 Process.setProcessGroup(app.pid, app.curSchedGroup);
13856 } catch (Exception e) {
13857 Slog.w(TAG, "Failed setting process group of " + app.pid
13858 + " to " + app.curSchedGroup);
13859 e.printStackTrace();
13860 } finally {
13861 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013862 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013863 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013864 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013865 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013866 app.thread.setSchedulingGroup(app.curSchedGroup);
13867 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013868 }
13869 }
13870 }
13871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013872 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013873 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013874 }
13875
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013876 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013877 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013878 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013879 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013880 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013881 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013882 }
13883 }
13884 return resumedActivity;
13885 }
13886
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013887 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013888 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013889 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13890 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013891 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13892 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013893
13894 mAdjSeq++;
13895
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013896 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013897 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13898 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013899 if (nowHidden != wasHidden) {
13900 // Changed to/from hidden state, so apps after it in the LRU
13901 // list may also be changed.
13902 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013903 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013904 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013905 }
13906
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013907 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013908 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013909 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13910
13911 if (false) {
13912 RuntimeException e = new RuntimeException();
13913 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013914 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013915 }
13916
13917 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013918 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013919
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013920 // Let's determine how many processes we have running vs.
13921 // how many slots we have for background processes; we may want
13922 // to put multiple processes in a slot of there are enough of
13923 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013924 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013925 int factor = (mLruProcesses.size()-4)/numSlots;
13926 if (factor < 1) factor = 1;
13927 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013928 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013929
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013930 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013931 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013932 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013933 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013934 while (i > 0) {
13935 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013936 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013937 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013938 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
13939 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013940 && app.curAdj == curHiddenAdj) {
13941 step++;
13942 if (step >= factor) {
13943 step = 0;
13944 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013945 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013946 }
13947 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013948 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013949 numHidden++;
13950 if (numHidden > mProcessLimit) {
13951 Slog.i(TAG, "No longer want " + app.processName
13952 + " (pid " + app.pid + "): hidden #" + numHidden);
13953 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13954 app.processName, app.setAdj, "too many background");
13955 app.killedBackground = true;
13956 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013957 }
13958 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013959 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
13960 // If this is an isolated process, and there are no
13961 // services running in it, then the process is no longer
13962 // needed. We agressively kill these because we can by
13963 // definition not re-use the same process again, and it is
13964 // good to avoid having whatever code was running in them
13965 // left sitting around after no longer needed.
13966 Slog.i(TAG, "Isolated process " + app.processName
13967 + " (pid " + app.pid + ") no longer needed");
13968 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13969 app.processName, app.setAdj, "isolated not needed");
13970 app.killedBackground = true;
13971 Process.killProcessQuiet(app.pid);
13972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013973 }
13974 }
13975
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013976 mNumServiceProcs = mNewNumServiceProcs;
13977
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013978 // Now determine the memory trimming level of background processes.
13979 // Unfortunately we need to start at the back of the list to do this
13980 // properly. We only do this if the number of background apps we
13981 // are managing to keep around is less than half the maximum we desire;
13982 // if we are keeping a good number around, we'll let them use whatever
13983 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013984 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013985 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013986 factor = numHidden/3;
13987 int minFactor = 2;
13988 if (mHomeProcess != null) minFactor++;
13989 if (mPreviousProcess != null) minFactor++;
13990 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013991 step = 0;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013992 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013993 for (i=0; i<N; i++) {
13994 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013995 if (app.curAdj >= ProcessList.HOME_APP_ADJ
13996 && app.curAdj != ProcessList.SERVICE_B_ADJ
13997 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013998 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13999 try {
14000 app.thread.scheduleTrimMemory(curLevel);
14001 } catch (RemoteException e) {
14002 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014003 if (false) {
14004 // For now we won't do this; our memory trimming seems
14005 // to be good enough at this point that destroying
14006 // activities causes more harm than good.
14007 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14008 && app != mHomeProcess && app != mPreviousProcess) {
14009 // For these apps we will also finish their activities
14010 // to help them free memory.
14011 mMainStack.destroyActivitiesLocked(app, false, "trim");
14012 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014013 }
14014 }
14015 app.trimMemoryLevel = curLevel;
14016 step++;
14017 if (step >= factor) {
14018 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014019 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14020 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014021 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014022 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14023 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014024 break;
14025 }
14026 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014027 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014028 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014029 && app.thread != null) {
14030 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014031 app.thread.scheduleTrimMemory(
14032 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014033 } catch (RemoteException e) {
14034 }
14035 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014036 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014037 } else if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014038 && app.pendingUiClean) {
14039 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14040 && app.thread != null) {
14041 try {
14042 app.thread.scheduleTrimMemory(
14043 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14044 } catch (RemoteException e) {
14045 }
14046 }
14047 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14048 app.pendingUiClean = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014049 } else {
14050 app.trimMemoryLevel = 0;
14051 }
14052 }
14053 } else {
14054 final int N = mLruProcesses.size();
14055 for (i=0; i<N; i++) {
14056 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014057 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014058 && app.pendingUiClean) {
14059 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14060 && app.thread != null) {
14061 try {
14062 app.thread.scheduleTrimMemory(
14063 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14064 } catch (RemoteException e) {
14065 }
14066 }
14067 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14068 app.pendingUiClean = false;
14069 } else {
14070 app.trimMemoryLevel = 0;
14071 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014072 }
14073 }
14074
14075 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014076 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014078 }
14079
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014080 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014081 synchronized (this) {
14082 int i;
14083
14084 // First remove any unused application processes whose package
14085 // has been removed.
14086 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14087 final ProcessRecord app = mRemovedProcesses.get(i);
14088 if (app.activities.size() == 0
14089 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014090 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014091 TAG, "Exiting empty application process "
14092 + app.processName + " ("
14093 + (app.thread != null ? app.thread.asBinder() : null)
14094 + ")\n");
14095 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014096 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14097 app.processName, app.setAdj, "empty");
14098 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014099 } else {
14100 try {
14101 app.thread.scheduleExit();
14102 } catch (Exception e) {
14103 // Ignore exceptions.
14104 }
14105 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014106 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014107 mRemovedProcesses.remove(i);
14108
14109 if (app.persistent) {
14110 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014111 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014112 }
14113 }
14114 }
14115 }
14116
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014117 // Now update the oom adj for all processes.
14118 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014119 }
14120 }
14121
14122 /** This method sends the specified signal to each of the persistent apps */
14123 public void signalPersistentProcesses(int sig) throws RemoteException {
14124 if (sig != Process.SIGNAL_USR1) {
14125 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14126 }
14127
14128 synchronized (this) {
14129 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14130 != PackageManager.PERMISSION_GRANTED) {
14131 throw new SecurityException("Requires permission "
14132 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14133 }
14134
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014135 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14136 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014137 if (r.thread != null && r.persistent) {
14138 Process.sendSignal(r.pid, sig);
14139 }
14140 }
14141 }
14142 }
14143
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014144 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14145 if (proc == null || proc == mProfileProc) {
14146 proc = mProfileProc;
14147 path = mProfileFile;
14148 profileType = mProfileType;
14149 clearProfilerLocked();
14150 }
14151 if (proc == null) {
14152 return;
14153 }
14154 try {
14155 proc.thread.profilerControl(false, path, null, profileType);
14156 } catch (RemoteException e) {
14157 throw new IllegalStateException("Process disappeared");
14158 }
14159 }
14160
14161 private void clearProfilerLocked() {
14162 if (mProfileFd != null) {
14163 try {
14164 mProfileFd.close();
14165 } catch (IOException e) {
14166 }
14167 }
14168 mProfileApp = null;
14169 mProfileProc = null;
14170 mProfileFile = null;
14171 mProfileType = 0;
14172 mAutoStopProfiler = false;
14173 }
14174
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014175 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014176 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014177
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014178 try {
14179 synchronized (this) {
14180 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14181 // its own permission.
14182 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14183 != PackageManager.PERMISSION_GRANTED) {
14184 throw new SecurityException("Requires permission "
14185 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014186 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014187
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014188 if (start && fd == null) {
14189 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014190 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014191
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014192 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014193 if (process != null) {
14194 try {
14195 int pid = Integer.parseInt(process);
14196 synchronized (mPidsSelfLocked) {
14197 proc = mPidsSelfLocked.get(pid);
14198 }
14199 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014200 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014201
14202 if (proc == null) {
14203 HashMap<String, SparseArray<ProcessRecord>> all
14204 = mProcessNames.getMap();
14205 SparseArray<ProcessRecord> procs = all.get(process);
14206 if (procs != null && procs.size() > 0) {
14207 proc = procs.valueAt(0);
14208 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014209 }
14210 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014211
14212 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014213 throw new IllegalArgumentException("Unknown process: " + process);
14214 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014215
14216 if (start) {
14217 stopProfilerLocked(null, null, 0);
14218 setProfileApp(proc.info, proc.processName, path, fd, false);
14219 mProfileProc = proc;
14220 mProfileType = profileType;
14221 try {
14222 fd = fd.dup();
14223 } catch (IOException e) {
14224 fd = null;
14225 }
14226 proc.thread.profilerControl(start, path, fd, profileType);
14227 fd = null;
14228 mProfileFd = null;
14229 } else {
14230 stopProfilerLocked(proc, path, profileType);
14231 if (fd != null) {
14232 try {
14233 fd.close();
14234 } catch (IOException e) {
14235 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014236 }
14237 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014238
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014239 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014240 }
14241 } catch (RemoteException e) {
14242 throw new IllegalStateException("Process disappeared");
14243 } finally {
14244 if (fd != null) {
14245 try {
14246 fd.close();
14247 } catch (IOException e) {
14248 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014249 }
14250 }
14251 }
Andy McFadden824c5102010-07-09 16:26:57 -070014252
14253 public boolean dumpHeap(String process, boolean managed,
14254 String path, ParcelFileDescriptor fd) throws RemoteException {
14255
14256 try {
14257 synchronized (this) {
14258 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14259 // its own permission (same as profileControl).
14260 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14261 != PackageManager.PERMISSION_GRANTED) {
14262 throw new SecurityException("Requires permission "
14263 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14264 }
14265
14266 if (fd == null) {
14267 throw new IllegalArgumentException("null fd");
14268 }
14269
14270 ProcessRecord proc = null;
14271 try {
14272 int pid = Integer.parseInt(process);
14273 synchronized (mPidsSelfLocked) {
14274 proc = mPidsSelfLocked.get(pid);
14275 }
14276 } catch (NumberFormatException e) {
14277 }
14278
14279 if (proc == null) {
14280 HashMap<String, SparseArray<ProcessRecord>> all
14281 = mProcessNames.getMap();
14282 SparseArray<ProcessRecord> procs = all.get(process);
14283 if (procs != null && procs.size() > 0) {
14284 proc = procs.valueAt(0);
14285 }
14286 }
14287
14288 if (proc == null || proc.thread == null) {
14289 throw new IllegalArgumentException("Unknown process: " + process);
14290 }
14291
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014292 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14293 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014294 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14295 throw new SecurityException("Process not debuggable: " + proc);
14296 }
14297 }
14298
14299 proc.thread.dumpHeap(managed, path, fd);
14300 fd = null;
14301 return true;
14302 }
14303 } catch (RemoteException e) {
14304 throw new IllegalStateException("Process disappeared");
14305 } finally {
14306 if (fd != null) {
14307 try {
14308 fd.close();
14309 } catch (IOException e) {
14310 }
14311 }
14312 }
14313 }
14314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014315 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14316 public void monitor() {
14317 synchronized (this) { }
14318 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014319
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014320 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014321 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14322 ProcessRecord processRecord = mLruProcesses.get(i);
14323 try {
14324 if (processRecord.thread != null) {
14325 processRecord.thread.setCoreSettings(settings);
14326 }
14327 } catch (RemoteException re) {
14328 /* ignore */
14329 }
14330 }
14331 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014332
14333 // Multi-user methods
14334
Amith Yamasani742a6712011-05-04 14:49:28 -070014335 private int mCurrentUserId;
14336 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014337 private ArrayList<UserListener> mUserListeners = new ArrayList<UserListener>(3);
14338
14339 public interface UserListener {
14340 public void onUserChanged(int userId);
14341
14342 public void onUserAdded(int userId);
14343
14344 public void onUserRemoved(int userId);
14345
14346 public void onUserLoggedOut(int userId);
14347 }
14348
14349 public void addUserListener(UserListener listener) {
14350 synchronized (this) {
14351 if (!mUserListeners.contains(listener)) {
14352 mUserListeners.add(listener);
14353 }
14354 }
14355 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014356
14357 public boolean switchUser(int userId) {
14358 final int callingUid = Binder.getCallingUid();
14359 if (callingUid != 0 && callingUid != Process.myUid()) {
14360 Slog.e(TAG, "Trying to switch user from unauthorized app");
14361 return false;
14362 }
14363 if (mCurrentUserId == userId)
14364 return true;
14365
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014366 ArrayList<UserListener> listeners;
14367
Amith Yamasani742a6712011-05-04 14:49:28 -070014368 synchronized (this) {
14369 // Check if user is already logged in, otherwise check if user exists first before
14370 // adding to the list of logged in users.
14371 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14372 if (!userExists(userId)) {
14373 return false;
14374 }
14375 mLoggedInUsers.append(userId, userId);
14376 }
14377
14378 mCurrentUserId = userId;
14379 boolean haveActivities = mMainStack.switchUser(userId);
14380 if (!haveActivities) {
14381 startHomeActivityLocked(userId);
14382 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014383
14384 listeners = (ArrayList<UserListener>) mUserListeners.clone();
14385 }
14386 // Inform the listeners
14387 for (UserListener listener : listeners) {
14388 listener.onUserChanged(userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070014389 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014390 return true;
14391 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014392
14393 private boolean userExists(int userId) {
14394 try {
14395 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14396 for (UserInfo user : users) {
14397 if (user.id == userId) {
14398 return true;
14399 }
14400 }
14401 } catch (RemoteException re) {
14402 // Won't happen, in same process
14403 }
14404
14405 return false;
14406 }
14407
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014408 private void checkValidCaller(int uid, int userId) {
14409 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14410
14411 throw new SecurityException("Caller uid=" + uid
14412 + " is not privileged to communicate with user=" + userId);
14413 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014414
14415 private int applyUserId(int uid, int userId) {
14416 return UserId.getUid(userId, uid);
14417 }
14418
14419 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014420 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014421 ApplicationInfo newInfo = new ApplicationInfo(info);
14422 newInfo.uid = applyUserId(info.uid, userId);
14423 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14424 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14425 + info.packageName;
14426 }
14427 return newInfo;
14428 }
14429
14430 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014431 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014432 || userId < 1) {
14433 return aInfo;
14434 }
14435
14436 ActivityInfo info = new ActivityInfo(aInfo);
14437 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14438 return info;
14439 }
14440
14441 static class ServiceMap {
14442
14443 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14444 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14445 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14446 mServicesByIntentPerUser = new SparseArray<
14447 HashMap<Intent.FilterComparison, ServiceRecord>>();
14448
14449 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14450 // TODO: Deal with global services
14451 if (DEBUG_MU)
14452 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14453 return getServices(callingUser).get(name);
14454 }
14455
14456 ServiceRecord getServiceByName(ComponentName name) {
14457 return getServiceByName(name, -1);
14458 }
14459
14460 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14461 // TODO: Deal with global services
14462 if (DEBUG_MU)
14463 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14464 return getServicesByIntent(callingUser).get(filter);
14465 }
14466
14467 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14468 return getServiceByIntent(filter, -1);
14469 }
14470
14471 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14472 // TODO: Deal with global services
14473 getServices(callingUser).put(name, value);
14474 }
14475
14476 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14477 ServiceRecord value) {
14478 // TODO: Deal with global services
14479 getServicesByIntent(callingUser).put(filter, value);
14480 }
14481
14482 void removeServiceByName(ComponentName name, int callingUser) {
14483 // TODO: Deal with global services
14484 ServiceRecord removed = getServices(callingUser).remove(name);
14485 if (DEBUG_MU)
14486 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14487 + " removed=" + removed);
14488 }
14489
14490 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14491 // TODO: Deal with global services
14492 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14493 if (DEBUG_MU)
14494 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14495 + " removed=" + removed);
14496 }
14497
14498 Collection<ServiceRecord> getAllServices(int callingUser) {
14499 // TODO: Deal with global services
14500 return getServices(callingUser).values();
14501 }
14502
14503 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14504 HashMap map = mServicesByNamePerUser.get(callingUser);
14505 if (map == null) {
14506 map = new HashMap<ComponentName, ServiceRecord>();
14507 mServicesByNamePerUser.put(callingUser, map);
14508 }
14509 return map;
14510 }
14511
14512 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14513 int callingUser) {
14514 HashMap map = mServicesByIntentPerUser.get(callingUser);
14515 if (map == null) {
14516 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14517 mServicesByIntentPerUser.put(callingUser, map);
14518 }
14519 return map;
14520 }
14521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014522}